diff --git a/CODEOWNERS b/CODEOWNERS index 59abea64af78d6f245925f04cb315afcb55bfac4..81d411b4860e6baaff515d258356e6c6e84b2a56 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -129,8 +129,10 @@ zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23 zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 -zh-cn/application-dev/ability/ @RayShih -zh-cn/application-dev/ui/ @HelloCrease +zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/ui/ @HelloCrease @qieqiewl @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih zh-cn/application-dev/windowmanager/ @ge-yafang zh-cn/application-dev/webgl/ @ge-yafang @@ -445,8 +447,19 @@ zh-cn/application-dev/reference/apis/js-apis-formextensioncontext.md @RayShih @l zh-cn/application-dev/reference/apis/js-apis-formhost.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-formInfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-formprovider.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errcode-usb.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-colorspace-manager.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-display.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-missionManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen diff --git a/README_zh.md b/README_zh.md index ebf1bc8d7557d35f99eaacf8fd1427972d61d3b0..386fa1d7449553f92f399839d947a0dacd4e18b8 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,15 +18,15 @@ - master:最新开发版本。 - - OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。 + - OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - 该已更新至OpenHarmony 3.1.1 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.1-release.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.1.3 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.3-release.md)了解版本详情。 - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - 该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.0.6 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 @@ -34,7 +34,7 @@ ### 历史稳定版本 -OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md)了解版本详情。 +OpenHarmony_v1.x_release:OpenHarmony 1.1.5 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md)了解版本详情。 如需了解更多版本详情,点击[此处](zh-cn/release-notes/)。 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/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index 1fddf868604e564e4b6a6701f8d3a8088c4d8326..0eeef8040da8abd9710f3996f0b5f2c65ecf71e2 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -10,7 +10,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat | Class/Interface | Function | Description | | --------------- | -------- | ----------- | -| IRemoteBroker | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | +| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | | IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | @@ -25,10 +25,10 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ``` class ITestAbility : public IRemoteBroker { public: - // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. - DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); - int TRANS_ID_PING_ABILITY = 1; // Define the message code. - virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. + // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. + DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); + int TRANS_ID_PING_ABILITY = 1; // Define the message code. + virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. }; ``` diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index 4c51f50e9c29c9df846011e80c06a46a59045794..f3572352e718bb77493d7dd2d097d2d7a82058c9 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -66,25 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. - To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows: - - - ``` - { - "module": { - "reqPermissions": [ - "name": "ohos.permission.LOCATION", - "reason": "$string:reason_description", - "usedScene": { - "ability": ["com.myapplication.LocationAbility"], - "when": "inuse" - } - ] - } - } - ``` - - For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). + You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.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/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 1446d4fcef22eb94e6c4796be4e55fd0968c8e69..754d30b06c7dda42dbe16203be2342bf6f70fc2a 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) @@ -68,13 +69,13 @@ - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) - - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md) - [@ohos.zlib](js-apis-zlib.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) - bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md) + - bundle/[BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) - bundle/[DispatchInfo](js-apis-dispatchInfo.md) - bundle/[ElementName](js-apis-bundle-ElementName.md) @@ -90,12 +91,13 @@ - 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) - [@ohos.effectKit](js-apis-effectKit.md) + - [@ohos.graphics.colorSpaceManager](js-apis-colorSpaceManager.md) - [@ohos.screen](js-apis-screen.md) - [@ohos.screenshot](js-apis-screenshot.md) - [@ohos.window](js-apis-window.md) @@ -145,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) @@ -260,6 +263,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) @@ -284,3 +288,4 @@ - [@system.sensor](js-apis-system-sensor.md) - [@system.storage](js-apis-system-storage.md) - [@system.vibrator](js-apis-system-vibrate.md) + - [console](js-apis-logs.md) diff --git a/en/application-dev/reference/apis/figures/en-us_image_0001.gif b/en/application-dev/reference/apis/figures/en-us_image_0001.gif new file mode 100644 index 0000000000000000000000000000000000000000..099acf91f8a1a6936c56e0ae09aaf7530b080828 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0001.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0002.gif b/en/application-dev/reference/apis/figures/en-us_image_0002.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e4c041811c24ffba57eee64c64d12532150fe4b Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0002.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0004.gif b/en/application-dev/reference/apis/figures/en-us_image_0004.gif new file mode 100644 index 0000000000000000000000000000000000000000..f622ab0eca3995baece321539984c289ab1b8b1a Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0004.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0005.gif b/en/application-dev/reference/apis/figures/en-us_image_0005.gif new file mode 100644 index 0000000000000000000000000000000000000000..5d904fbfabdc50751afd51e9a29b0aa18c6e445f Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0005.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0006.gif b/en/application-dev/reference/apis/figures/en-us_image_0006.gif new file mode 100644 index 0000000000000000000000000000000000000000..7477b94b0437fadfc2d875841f182648d1bcccc9 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0006.gif differ diff --git a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..2f601b14073d922a6b5812dc0d0368e16024a751 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @@ -0,0 +1,19 @@ +# BundleStatusCallback + +The **BundleStatusCallback** module provides bundle callback information, which is obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). + +> **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. + +## BundleStatusCallback + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Description | +| ------ | --------------------------------------------- | -------------------------------------- | +| add | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is added.| +| update | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is updated.| +| remove | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is removed.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 3691d636ac769e8bfad9099f92554a2476925d40..8beab3711f2933ce0701e5cdb79319c4d0bfdfcd 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -106,8 +106,8 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------------------- | --------------------- | ---- | ---------------------------------------------------- | -| type | "BundleStatusChange" | Yes | Event type. | -| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported. | +| bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. | | callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| ## innerBundleManager.on @@ -130,10 +130,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------------------- | -------------------- | ---- | ------------------ | -| type | "BundleStatusChange" | Yes | Event type. | -| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.| +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported.| +| bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. | **Return value** @@ -163,7 +163,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------------------- | -| type | "BundleStatusChange" | Yes | Event type. | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported. | | callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| ## innerBundleManager.off @@ -186,9 +186,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------------------- | ---- | ---------------- | -| type | "BundleStatusChange" | Yes | Event type.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------------------------------ | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported.| **Return value** 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-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index 205c9f15192c4c2c9abfcb08b1f1ae156d7baf75..4a22bff59f56ba6756e08c0af59046530fea1a80 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,20 +1,24 @@ # ElementName -The **ElementName** module provides the element name information. +The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md). > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## ElementName +## ElementName(deprecated) -**System capability**: SystemCapability.BundleManager.BundleFramework +> This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead. + + **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | -| deviceId | string | Yes | Yes | Device ID. | -| bundleName | string | Yes | Yes | Bundle name of the application. | -| abilityName | string | Yes | Yes | Name of the ability. | -| uri | string | Yes | Yes | URI. | -| shortName | string | Yes | Yes | Short name of the ability. | -| moduleName9+ | string | Yes | Yes | Name of the HAP file to which the ability belongs. | +| deviceId | string | Yes | Yes | Device ID. | +| bundleName | string | Yes | Yes | Bundle name of the application. | +| abilityName | string | Yes | Yes | Name of the ability. | +| uri | string | Yes | Yes | Resource ID. | +| shortName | string | Yes | Yes | Short name of the ability. | +| moduleName9+ | string | Yes | Yes | Name of the HAP file to which the ability belongs. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index ab561f552758ed5af3c79bc2c4406d84ceb56f2b..34fe47f45abe436abf986da809e343fd638540d7 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -403,7 +403,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. **Example** ```js -call.formatPhoneNumber("138xxxxxxxx",{ +call.formatPhoneNumber("138xxxxxxxx", { countryCode: "CN" }, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); diff --git a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md new file mode 100644 index 0000000000000000000000000000000000000000..ca879b489145b7d741cdf990e36656b78cd3033b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md @@ -0,0 +1,197 @@ +# Color Space Management + +The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes. + +> **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 colorSpaceManager from '@ohos.graphics.colorSpaceManager'; +``` + +## ColorSpace + +Enumerates the color space types. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +| Name | Value | Description | +| --------------------------- | ------ | ----------------------- | +| UNKNOWN | 0 | Unknown type.| +| ADOBE_RGB_1998 | 1 | Adobe RGB (1998).| +| DCI_P3 | 2 | DCI-P3.| +| DISPLAY_P3 | 3 | Display P3.| +| SRGB | 4 | SRGB.
This is the default color space type.| +| CUSTOM | 5 | Custom type.| + +## ColorSpacePrimaries + +Defines the color space primaries. A color space is defined by chromaticity coordinates of the red, green, and blue additive primaries, the white point, and the gamma. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +| Name | Type| Readable| Writable| Description | +| ---------------------------- | -------- | ---- | ---- | ----------------------------------------------------- | +| redX | number | Yes | Yes | X coordinate of the red color in the color space.| +| redY | number | Yes | Yes | Y coordinate of the red color in the color space.| +| greenX | number | Yes | Yes | X coordinate of the green color in the color space.| +| greenY | number | Yes | Yes | Y coordinate of the green color in the color space.| +| blueX | number | Yes | Yes | X coordinate of the blue color in the color space.| +| blueY | number | Yes | Yes | Y coordinate of the blue color in the color space.| +| whitePointX | number | Yes | Yes | X coordinate of the white point in the color space.| +| whitePointY | number | Yes | Yes | Y coordinate of the white point in the color space.| + +## colorSpaceManager.create + +create(colorSpaceName: ColorSpace): ColorSpaceManager + +Creates a standard color space object. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Parameters** + +| Parameter | Type | Mandatory| Description | +| --------------- | ------------------------ | ---- | -----------------------------| +| colorSpaceName | [ColorSpace](#colorspace)| Yes | Type of the color space.
**UNKNOWN** and **CUSTOM** cannot be used when creating standard color space objects. | + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| [ColorSpaceManager](#colorspacemanager) | Color space object created. | + +**Example** + +```js +let colorSpace = null; +try { + colorSpace = colorSpaceManager.create(colorSpaceManager.ColorSpace.SRGB); +} catch (err) { + console.log(`Failed to create SRGB colorSpace. Cause: ` + JSON.stringify(err)); +} +``` + +## colorSpaceManager.create + +create(primaries: ColorSpacePrimaries, gamma: number): ColorSpaceManager + +Creates a custom color space object. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Parameters** + +| Parameter | Type | Mandatory| Description | +| --------------- | ------------------------------------------ | ---- | -----------------------------| +| primaries | [ColorSpacePrimaries](#colorspaceprimaries)| Yes | Primaries of the color space. | +| gamma | number | Yes | Gamma of the color space. | + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| [ColorSpaceManager](#colorspacemanager) | Color space object created.
The color space type is **CUSTOM** of [ColorSpace](#colorspace).| + +**Example** + +```js +let colorSpace = null; +try { + let primaries = { + redX: 0.1, + redY: 0.1, + greenX: 0.2, + greenY: 0.2, + blueX: 0.3, + blueY: 0.3, + whitePointX: 0.4, + whitePointY: 0.4 + }; + let gamma = 2.2; + colorSpace = colorSpaceManager.create(primaries, gamma); +} catch (err) { + console.log(`Failed to create colorSpace with customized primaries and gamma. Cause: ` + JSON.stringify(err)); +} +``` + +## ColorSpaceManager + +Implements management of color space objects. + +Before calling any of the following APIs, you must use [create()](#colorspacemanagercreate) to create a color space object. + +### getColorSpaceName + +getColorSpaceName(): ColorSpace + +Obtains the color space type. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| [ColorSpace](#colorspace) | Color space type.| + +**Example** + +```js +try { + let csType = colorSpace.getColorSpaceName(); +} catch (err) { + console.log(`Fail to get colorSpace's name. Cause: ` + JSON.stringify(err)); +} +``` + +### getWhitePoint + +getWhitePoint(): Array\ + +Obtains the coordinates of the white point of the color space. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| Array\ | Coordinates [x, y] of the white point.| + +**Example** + +```js +try { + let wp = colorSpace.getWhitePoint(); +} catch (err) { + console.log(`Failed to get white point. Cause: ` + JSON.stringify(err)); +} +``` + +### getGamma + +getGamma(): number + +Obtains the gamma of the color space. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| number | Gamma of the color space.| + +**Example** + +```js +try { + let gamma = colorSpace.getGamma(); +} catch (err) { + console.log(`Failed to get gamma. Cause: ` + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 02c4680e1e082798d81c692cb178ca72fe21cf9a..199469589d8a67a47b993eacc36eac69a25aa8c1 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -11,7 +11,6 @@ The **Display** module provides APIs for managing displays, such as obtaining in import display from '@ohos.display'; ``` - ## DisplayState Enumerates the display states. @@ -65,61 +64,6 @@ Describes the cutout, which is an area that is not intended for displaying conte | boundingRects | Array\<[Rect](#rect9)> | Yes | No | Bounding rectangle for punch holes and notches.| | waterfallDisplayAreaRects | [WaterfallDisplayAreaRects](#waterfalldisplayarearects9) | Yes| No| Curved area on the waterfall display.| -## display.getDefaultDisplay - -getDefaultDisplay(callback: AsyncCallback<Display>): void - -Obtains the default display object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| - -**Example** - -```js -var displayClass = null; -display.getDefaultDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); - displayClass = data; -}); -``` - -## display.getDefaultDisplay - -getDefaultDisplay(): Promise<Display> - -Obtains the default display object. This API uses a promise to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Return value** - - | Type | Description | - | ---------------------------------- | ---------------------------------------------- | - | Promise<[Display](#display)> | Promise used to return the default display object.| - -**Example** - -```js -var displayClass = null; -let promise = display.getDefaultDisplay(); -promise.then((data) => { - displayClass = data; - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); -}); -``` - ## display.getDefaultDisplaySync9+ getDefaultDisplaySync(): Display @@ -134,15 +78,28 @@ Obtains the default display object. This API returns the result synchronously. | ------------------------------| ----------------------------------------------| | [Display](#display) | Default display object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var displayClass = display.getDefaultDisplaySync(); +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +}; ``` -## display.getAllDisplay +## display.getAllDisplays9+ -getAllDisplay(callback: AsyncCallback<Array<Display>>): void +getAllDisplays(callback: AsyncCallback<Array<Display>>): void Obtains all display objects. This API uses an asynchronous callback to return the result. @@ -150,14 +107,24 @@ Obtains all display objects. This API uses an asynchronous callback to return th **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ---------------------------------------------------- | ---- | ------------------------------- | - | callback | AsyncCallback<Array<[Display](#display)>> | Yes | Callback used to return all the display objects.| +| Name| Type| Mandatory| Description| +| -------- | ---------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<Array<[Display](#display)>> | Yes| Callback used to return all the display objects.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js -display.getAllDisplay((err, data) => { +let displayClass = null; +display.getAllDisplays((err, data) => { + displayClass = data; if (err.code) { console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); return; @@ -166,9 +133,9 @@ display.getAllDisplay((err, data) => { }); ``` -## display.getAllDisplay +## display.getAllDisplays9+ -getAllDisplay(): Promise<Array<Display>> +getAllDisplays(): Promise<Array<Display>> Obtains all display objects. This API uses a promise to return the result. @@ -176,15 +143,25 @@ Obtains all display objects. This API uses a promise to return the result. **Return value** - | Type | Description | - | ----------------------------------------------- | ------------------------------------------------------- | - | Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| +| Type| Description| +| ----------------------------------------------- | ------------------------------------------------------- | +| Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js -let promise = display.getAllDisplay(); +let displayClass = null; +let promise = display.getAllDisplays(); promise.then((data) => { + displayClass = data; console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); @@ -195,7 +172,7 @@ promise.then((data) => { hasPrivateWindow(displayId: number): boolean -Checks whether there is a visible privacy window on a display. The privacy window can be set by calling `[setPrivacyMode](js-apis-window.md#setprivacymode7)`. The content in the privacy window cannot be captured or recorded. +Checks whether there is a visible privacy window on a display. The privacy window can be set by calling [setWindowPrivacyMode()](js-apis-window.md#setwindowprivacymode9). The content in the privacy window cannot be captured or recorded. **System API**: This is a system API. @@ -211,30 +188,41 @@ Checks whether there is a visible privacy window on a display. The privacy windo | Type | Description | | -------------------------------- |-----------------------------------------------------------------------| -|boolean | Whether there is a visible privacy window on the display.
The value `true` means that there is a visible privacy window on the display, and `false` means the opposite.
| +|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | **Example** ```js -var displayClass = null; -display.getDefaultDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); return; - } - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); - displayClass = data; -}); - -var ret = display.hasPrivateWindow(displayClass.id); +}; + +let ret = undefined; +try { + ret = display.hasPrivateWindow(displayClass.id); +} catch (exception) { + console.error('Failed to check has privateWindow or not. Code: ' + JSON.stringify(exception)); +}; if (ret == undefined) { - console.log("Failed to check has privateWindow or not."); + console.log("Failed to check has privateWindow or not."); } if (ret) { console.log("There has privateWindow."); } else if (!ret) { console.log("There has no privateWindow."); -} +}; ``` ## display.on('add'|'remove'|'change') @@ -249,16 +237,20 @@ Subscribes to display changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event indicating that a display is connected to a PC.
- **remove**, indicating the display removal event. Example: event that a display is disconnected from a PC.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| | callback | Callback<number> | Yes| Callback used to return the ID of the display.| **Example** ```js -var callback = (data) => { +let callback = (data) => { console.info('Listening enabled. Data: ' + JSON.stringify(data)); -} -display.on("add", callback); +}; +try { + display.on("add", callback); +} catch (exception) { + console.error('Failed to register callback. Code: ' + JSON.stringify(exception)); +}; ``` ## display.off('add'|'remove'|'change') @@ -271,21 +263,147 @@ Unsubscribes from display changes. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| - | callback | Callback<number> | No| Callback used to return the ID of the display.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event indicating that a display is connected to a PC.
- **remove**, indicating the display removal event. Example: event that a display is disconnected from a PC.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| +| callback | Callback<number> | No| Callback used to return the ID of the display.| + +**Example** + +```js +try { + display.off("remove"); +} catch (exception) { + console.error('Failed to unregister callback. Code: ' + JSON.stringify(exception)); +}; +``` + +## display.getDefaultDisplay(deprecated) + +getDefaultDisplay(callback: AsyncCallback<Display>): void + +Obtains the default display object. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| + +**Example** + +```js +let displayClass = null; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; +}); +``` + +## display.getDefaultDisplay(deprecated) + +getDefaultDisplay(): Promise<Display> + +Obtains the default display object. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------------------------------------- | +| Promise<[Display](#display)> | Promise used to return the default display object.| + +**Example** + +```js +let displayClass = null; +let promise = display.getDefaultDisplay(); +promise.then((data) => { + displayClass = data; + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); +}); +``` + +## display.getAllDisplay(deprecated) + +getAllDisplay(callback: AsyncCallback<Array<Display>>): void + +Obtains all display objects. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getAllDisplays()](#displaygetalldisplays9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<Array<[Display](#display)>> | Yes | Callback used to return all the display objects.| **Example** ```js -display.off("remove"); +display.getAllDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}); +``` + +## display.getAllDisplay(deprecated) + +getAllDisplay(): Promise<Array<Display>> + +Obtains all display objects. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getAllDisplays()](#displaygetalldisplays9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------- | +| Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| + +**Example** + +```js +let promise = display.getAllDisplay(); +promise.then((data) => { + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); +}); ``` ## Display -Implements a `Display` instance, with properties and APIs defined. +Implements a **Display** instance, with properties and APIs defined. -To call an API in the following API examples, you must first use `[getAllDisplay()](#displaygetalldisplay)`, `[getDefaultDisplay()](#displaygetdefaultdisplay)`, or `[getDefaultDisplaySync()](#displaygetdefaultdisplaysync)` to obtain a `Display` instance. +Before calling any API in **Display**, you must use [getAllDisplays()](#displaygetalldisplays9) or [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) to obtain a **Display** instance. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -296,7 +414,7 @@ To call an API in the following API examples, you must first use `[getAllDisplay | alive | boolean | Yes| No| Whether the display is alive.| | state | [DisplayState](#displaystate) | Yes| No| State of the display.| | refreshRate | number | Yes| No| Refresh rate of the display.| -| rotation | number | Yes| No| Screen rotation angle of the display.| +| rotation | number | Yes| No| Screen rotation angle of the display.
The value **0** indicates that the screen of the display rotates by 0°.
The value **1** indicates that the screen of the display rotates by 90°.
The value **2** indicates that the screen of the display rotates by 180°.
The value **3** indicates that the screen of the display rotates by 270°.| | width | number | Yes| No| Width of the display, in pixels.| | height | number | Yes| No| Height of the display, in pixels.| | densityDPI | number | Yes| No| Screen density of the display, in DPI.| @@ -308,29 +426,46 @@ To call an API in the following API examples, you must first use `[getAllDisplay ### getCutoutInfo9+ getCutoutInfo(callback: AsyncCallback<CutoutInfo>): void -Obtains the cutout information of the display. This API uses an asynchronous callback to return the result. +Obtains the cutout information of the display. This API uses an asynchronous callback to return the result. You are advised not to use the cutout area during application layout. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | Yes | Callback used to If the operation is successful, `err` is `undefined` and `data` is the `CutoutInfo` object obtained. Otherwise, `err` is an error object.| +| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **CutoutInfo** object obtained. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +}; + displayClass.getCutoutInfo((err, data) => { if (err.code) { - console.error('Failed to get cutoutInfo. Cause: ' + JSON.stringify(err)); + console.error('Failed to get cutoutInfo. Code: ' + JSON.stringify(err)); return; } console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); -}) +}); ``` ### getCutoutInfo9+ getCutoutInfo(): Promise<CutoutInfo> -Obtains the cutout information of the display. This API uses a promise to return the result. +Obtains the cutout information of the display. This API uses a promise to return the result. You are advised not to use the cutout area during application layout. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -338,11 +473,26 @@ Obtains the cutout information of the display. This API uses a promise to return | Type | Description | | ------------------- | ------------------------- | -| Promise<[CutoutInfo](#cutoutinfo9)> | Promise used to return the `CutoutInfo` object.| +| Promise<[CutoutInfo](#cutoutinfo9)> | Promise used to return the **CutoutInfo** object.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +}; + let promise = displayClass.getCutoutInfo(); promise.then((data) => { console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index f15805a326e19b0a579d1da1ae0e44e9937fef6f..92118167ad603189eac98eae73e156a794542f99 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -14,7 +14,7 @@ import geolocation from '@ohos.geolocation'; ## geolocation.on('locationChange') -on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void Registers a listener for location changes with a location request initiated. @@ -34,6 +34,7 @@ Registers a listener for location changes with a location request initiated. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -44,7 +45,7 @@ Registers a listener for location changes with a location request initiated. ## geolocation.off('locationChange') -off(type: 'locationChange', callback?: Callback<Location>) : void +off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. @@ -63,6 +64,7 @@ Unregisters the listener for location changes with the corresponding location re **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -74,7 +76,7 @@ Unregisters the listener for location changes with the corresponding location re ## geolocation.on('locationServiceState') -on(type: 'locationServiceState', callback: Callback<boolean>) : void +on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. @@ -93,6 +95,7 @@ Registers a listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } @@ -102,7 +105,7 @@ Registers a listener for location service status change events. ## geolocation.off('locationServiceState') -off(type: 'locationServiceState', callback?: Callback<boolean>) : void; +off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. @@ -121,6 +124,7 @@ Unregisters the listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } @@ -131,7 +135,7 @@ Unregisters the listener for location service status change events. ## geolocation.on('cachedGnssLocationsReporting')8+ -on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; +on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. @@ -151,6 +155,7 @@ Registers a listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -161,7 +166,7 @@ Registers a listener for cached GNSS location reports. ## geolocation.off('cachedGnssLocationsReporting')8+ -off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; +off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. @@ -180,6 +185,7 @@ Unregisters the listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -191,7 +197,7 @@ Unregisters the listener for cached GNSS location reports. ## geolocation.on('gnssStatusChange')8+ -on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; +on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. @@ -210,6 +216,7 @@ Registers a listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -219,7 +226,7 @@ Registers a listener for GNSS satellite status change events. ## geolocation.off('gnssStatusChange')8+ -off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; +off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. @@ -237,6 +244,7 @@ Unregisters the listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -247,7 +255,7 @@ Unregisters the listener for GNSS satellite status change events. ## geolocation.on('nmeaMessageChange')8+ -on(type: 'nmeaMessageChange', callback: Callback<string>) : void; +on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. @@ -266,6 +274,7 @@ Registers a listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -275,7 +284,7 @@ Registers a listener for GNSS NMEA message change events. ## geolocation.off('nmeaMessageChange')8+ -off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; +off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. @@ -294,6 +303,7 @@ Unregisters the listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -304,7 +314,7 @@ Unregisters the listener for GNSS NMEA message change events. ## geolocation.on('fenceStatusChange')8+ -on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. @@ -331,13 +341,13 @@ Registers a listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -349,7 +359,7 @@ Registers a listener for status change events of the specified geofence. ## geolocation.off('fenceStatusChange')8+ -off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. @@ -375,7 +385,7 @@ Unregisters the listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], @@ -392,62 +402,9 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.on('countryCodeChange')9+ - -on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; - -Subscribe to country code information reporting events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means subscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - ``` - - -## geolocation.off('countryCodeChange')9+ - -off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; - -Unsubscribe from the country code to report events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means unsubscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - geolocation.off('countryCodeChange', callback); - ``` - - ## geolocation.getCurrentLocation -getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void Obtains the current location. This API uses an asynchronous callback to return the result. @@ -466,6 +423,7 @@ Obtains the current location. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { if (err) { @@ -482,7 +440,7 @@ Obtains the current location. This API uses an asynchronous callback to return t ## geolocation.getCurrentLocation -getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> Obtains the current location. This API uses a promise to return the result. @@ -507,6 +465,7 @@ Obtains the current location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); @@ -516,7 +475,7 @@ Obtains the current location. This API uses a promise to return the result. ## geolocation.getLastLocation -getLastLocation(callback: AsyncCallback<Location>) : void +getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. @@ -534,6 +493,7 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { console.log('getLastLocation: err=' + JSON.stringify(err)); @@ -547,7 +507,7 @@ Obtains the previous location. This API uses an asynchronous callback to return ## geolocation.getLastLocation -getLastLocation() : Promise<Location> +getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. @@ -565,6 +525,7 @@ Obtains the previous location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -573,7 +534,7 @@ Obtains the previous location. This API uses a promise to return the result. ## geolocation.isLocationEnabled -isLocationEnabled(callback: AsyncCallback<boolean>) : void +isLocationEnabled(callback: AsyncCallback<boolean>): void Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. @@ -591,6 +552,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { console.log('isLocationEnabled: err=' + JSON.stringify(err)); @@ -604,7 +566,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ## geolocation.isLocationEnabled -isLocationEnabled() : Promise<boolean> +isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. @@ -621,15 +583,16 @@ Checks whether the location service is enabled. This API uses a promise to retur **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { - console.log('promise, isLocationEnabled: ' + result); + console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); }); ``` ## geolocation.requestEnableLocation -requestEnableLocation(callback: AsyncCallback<boolean>) : void +requestEnableLocation(callback: AsyncCallback<boolean>): void Requests to enable the location service. This API uses an asynchronous callback to return the result. @@ -647,6 +610,7 @@ Requests to enable the location service. This API uses an asynchronous callback **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { console.log('requestEnableLocation: err=' + JSON.stringify(err)); @@ -660,7 +624,7 @@ Requests to enable the location service. This API uses an asynchronous callback ## geolocation.requestEnableLocation -requestEnableLocation() : Promise<boolean> +requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. @@ -677,6 +641,7 @@ Requests to enable the location service. This API uses a promise to return the r **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation().then((result) => { console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); @@ -685,7 +650,7 @@ Requests to enable the location service. This API uses a promise to return the r ## geolocation.enableLocation -enableLocation(callback: AsyncCallback<boolean>) : void; +enableLocation(callback: AsyncCallback<boolean>): void; Enables the location service. This API uses an asynchronous callback to return the result. @@ -704,6 +669,7 @@ Enables the location service. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation((err, data) => { if (err) { console.log('enableLocation: err=' + JSON.stringify(err)); @@ -717,7 +683,7 @@ Enables the location service. This API uses an asynchronous callback to return t ## geolocation.enableLocation -enableLocation() : Promise<boolean> +enableLocation(): Promise<boolean> Enables the location service. This API uses a promise to return the result. @@ -736,6 +702,7 @@ Enables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation().then((result) => { console.log('promise, enableLocation: ' + JSON.stringify(result)); }); @@ -743,7 +710,7 @@ Enables the location service. This API uses a promise to return the result. ## geolocation.disableLocation -disableLocation(callback: AsyncCallback<boolean>) : void; +disableLocation(callback: AsyncCallback<boolean>): void; Disables the location service. This API uses an asynchronous callback to return the result. @@ -762,6 +729,7 @@ Disables the location service. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation((err, data) => { if (err) { console.log('disableLocation: err=' + JSON.stringify(err)); @@ -775,7 +743,7 @@ Disables the location service. This API uses an asynchronous callback to return ## geolocation.disableLocation -disableLocation() : Promise<boolean> +disableLocation(): Promise<boolean> Disables the location service. This API uses a promise to return the result. @@ -794,6 +762,7 @@ Disables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation().then((result) => { console.log('promise, disableLocation: ' + JSON.stringify(result)); }); @@ -801,7 +770,7 @@ Disables the location service. This API uses a promise to return the result. ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void +isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. @@ -818,6 +787,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); @@ -831,7 +801,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable() : Promise<boolean> +isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. @@ -848,6 +818,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); @@ -856,7 +827,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. @@ -874,6 +845,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -888,7 +860,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. @@ -911,6 +883,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -920,7 +893,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. @@ -938,6 +911,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -952,7 +926,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. @@ -975,6 +949,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -984,7 +959,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. @@ -1001,6 +976,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); @@ -1014,7 +990,7 @@ Obtains the number of cached GNSS locations. ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize() : Promise<number>; +getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. @@ -1031,6 +1007,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); @@ -1039,7 +1016,7 @@ Obtains the number of cached GNSS locations. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; +flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1056,6 +1033,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); @@ -1069,7 +1047,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations() : Promise<boolean>; +flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1086,6 +1064,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); @@ -1094,7 +1073,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; +sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1112,6 +1091,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1126,7 +1106,7 @@ Sends an extended command to the location subsystem. This API can only be called ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand) : Promise<boolean>; +sendCommand(command: LocationCommand): Promise<boolean>; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1149,6 +1129,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); @@ -1156,826 +1137,182 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.isLocationPrivacyConfirmed8+ - -isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; - -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## LocationRequestPriority -**System API**: This is a system API and cannot be called by third-party applications. +Sets the priority of the location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - if (err) { - console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); - } - if (result) { - console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); - } - }); - ``` +## LocationRequestScenario + + Sets the scenario of the location request. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.isLocationPrivacyConfirmed8+ +| Name| Default Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| -isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## GeoLocationErrorCode -**System API**: This is a system API and cannot be called by third-party applications. +Enumerates error codes of the location service. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -**Return value** +## ReverseGeoCodeRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| +Defines a reverse geocoding request. -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | No| Maximum number of location records to be returned.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## GeoCodeRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a geocoding request. **Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core +**System capability**: SystemCapability.Location.Location.Geocoder -**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| +| maxItems | number | No| Maximum number of location records to be returned.| +| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| +| minLongitude | number | No| Minimum longitude.| +| maxLatitude | number | No| Maximum latitude.| +| maxLongitude | number | No| Maximum longitude.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - if (err) { - console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); - } - if (result) { - console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); - } - }); - ``` +## GeoAddress + +Defines a geographic location. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | No| Landmark of the location.| +| countryCode7+ | string | No| Country code.| +| countryName7+ | string | No| Country name.| +| administrativeArea7+ | string | No| Administrative region name.| +| subAdministrativeArea7+ | string | No| Sub-administrative region name.| +| locality7+ | string | No| Locality information. | +| subLocality7+ | string | No| Sub-locality information. | +| roadName7+ | string | No| Road name.| +| subRoadName7+ | string | No| Auxiliary road information.| +| premises7+ | string | No| House information.| +| postalCode7+ | string | No| Postal code.| +| phoneNumber7+ | string | No| Phone number.| +| addressUrl7+ | string | No| Website URL.| +| descriptions7+ | Array<string> | No| Additional description.| +| descriptionsSize7+ | number | No| Total number of additional descriptions.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## LocationRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| +| timeInterval | number | No| Time interval at which location information is reported.| +| distanceInterval | number | No| Distance interval at which location information is reported.| +| maxAccuracy | number | No| Location accuracy.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Return value** +## CurrentLocationRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| +Defines the current location request. -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.getCountryCode9+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| +| maxAccuracy | number | No| Location accuracy, in meters.| +| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| -getCountryCode(callback: AsyncCallback<CountryCode>) : void; -Query the current country code. +## SatelliteStatusInfo8+ -**System capability**: SystemCapability.Location.Location.Core +Defines the satellite status information. -**Parameters** +**Permission required**: ohos.permission.LOCATION - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<CountryCode> | Yes | Callback is used to receive the country code. | +**System capability**: SystemCapability.Location.Location.Gnss -**Example**: - - ```js - geolocation.getCountryCode((err, result) => { - if (err) { - console.log('getCountryCode: err=' + JSON.stringify(err)); - } - if (result) { - console.log('getCountryCode: result=' + JSON.stringify(result)); - } - }); - ``` +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| Number of satellites.| +| satelliteIds | Array<number> | Yes| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| Altitude information.| +| azimuths | Array<number> | Yes| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| Carrier frequency.| -## geolocation.getCountryCode9+ +## CachedGnssLocationsRequest8+ -getCountryCode() : Promise<CountryCode>; +Represents a request for reporting cached GNSS locations. -Query the current country code. +**Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<CountryCode> | return country code. | - -**Example**: - - ```js - geolocation.getCountryCode() - .then((result) => { - console.log('promise, getCountryCode: result=' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCountryCode: error=' + JSON.stringify(error)); - }); - ``` - - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates under what scenario the position simulation function is enabled. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request, (err, result) => { - if (err) { - console.log('enableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('enableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates which scene's position simulation function is enabled. If this parameter is not carried, it means that the position simulation function of all scenes is enabled. | - - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request, (err, result) => { - if (err) { - console.log('disableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr, otherwise it will return an error message | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations": locations}; - geolocation.setMockedLocations(config, (err, data) => { - if (err) { - console.log('setMockedLocations: err=' + JSON.stringify(err)); - } - if (data) { - console.log('setMockedLocations: data=' + JSON.stringify(data)); - } - }); - ``` - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig) : Promise<void>; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations":locations}; - geolocation.setMockedLocations(config) - .then((result) => { - if (result) { - console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); - } - }); - ``` - - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock((err, data) => { - if (err) { - console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock() : Promise<void>; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock((err, result) => { - if (err) { - console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock() : Promise<void>; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { - if (err) { - console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); - } - if (data) { - console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos) - .then((result) => { - if (result) { - console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); - } - }); - ``` - - -## LocationRequestPriority - -Sets the priority of the location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| UNSET | 0x200 | Priority unspecified.| -| ACCURACY | 0x201 | Location accuracy.| -| LOW_POWER | 0x202 | Power efficiency.| -| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| - - -## LocationRequestScenario - - Sets the scenario of the location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| UNSET | 0x300 | Scenario unspecified.| -| NAVIGATION | 0x301 | Navigation.| -| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| -| CAR_HAILING | 0x303 | Ride hailing.| -| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| -| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| - - -## GeoLocationErrorCode - -Enumerates error codes of the location service. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| NOT_SUPPORTED9+ | 100 | Indicates that the interface function is not supported. | -| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| -| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| -| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| -| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| -| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -| QUERY_COUNTRY_CODE_ERROR9+ | 108 | Indicates that the country code query failed. | - - -## ReverseGeoCodeRequest - -Defines a reverse geocoding request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| maxItems | number | No| Maximum number of location records to be returned.| - - -## GeoCodeRequest - -Defines a geocoding request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| -| maxItems | number | No| Maximum number of location records to be returned.| -| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| -| minLongitude | number | No| Minimum longitude.| -| maxLatitude | number | No| Maximum latitude.| -| maxLongitude | number | No| Maximum longitude.| - - -## GeoAddress - -Defines a geographic location. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName7+ | string | No| Landmark of the location.| -| countryCode7+ | string | No| Country code.| -| countryName7+ | string | No| Country name.| -| administrativeArea7+ | string | No| Administrative region name.| -| subAdministrativeArea7+ | string | No| Sub-administrative region name.| -| locality7+ | string | No| Locality information. | -| subLocality7+ | string | No| Sub-locality information. | -| roadName7+ | string | No| Road name.| -| subRoadName7+ | string | No| Auxiliary road information.| -| premises7+ | string | No| House information.| -| postalCode7+ | string | No| Postal code.| -| phoneNumber7+ | string | No| Phone number.| -| addressUrl7+ | string | No| Website URL.| -| descriptions7+ | Array<string> | No| Additional description.| -| descriptionsSize7+ | number | No| Total number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the geographical name information comes from the reverse geocoding simulation function. | - - -## LocationRequest - -Defines a location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| -| timeInterval | number | No| Time interval at which location information is reported.| -| distanceInterval | number | No| Distance interval at which location information is reported.| -| maxAccuracy | number | No| Location accuracy.| - - -## CurrentLocationRequest - -Defines the current location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| -| maxAccuracy | number | No| Location accuracy, in meters.| -| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| - - -## SatelliteStatusInfo8+ - -Defines the satellite status information. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes| Number of satellites.| -| satelliteIds | Array<number> | Yes| Array of satellite IDs.| -| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| -| altitudes | Array<number> | Yes| Altitude information.| -| azimuths | Array<number> | Yes| Azimuth information.| -| carrierFrequencies | Array<number> | Yes| Carrier frequency.| - - -## CachedGnssLocationsRequest8+ - -Represents a request for reporting cached GNSS locations. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss +**System capability**: SystemCapability.Location.Location.Gnss | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -2063,58 +1400,3 @@ Defines a location. | timeSinceBoot7+ | number | Yes| Location timestamp since boot.| | additions7+ | Array<string> | No| Additional information.| | additionSize7+ | number | No| Number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the location information comes from the location simulation function. | - - -## ReverseGeocodingMockInfo9+ - -The configuration information of the reverse geocoding simulation function includes a location information and a place name information. - -**System capability**:SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| location | ReverseGeoCodeRequest | Yes | Indicates longitude and latitude information. | -| geoAddress | GeoAddress | Yes | Represents a geographic location. | - - -## LocationMockConfig9+ - -The configuration parameters of the location simulation function include the time interval of the simulation position report and the array of simulation locations. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timeInterval | number | Yes | Indicates the time interval of analog location reporting, in seconds. | -| locations | Array<Location> | Yes | Represents an array of mocked locations. | - - -## CountryCode9+ - -The country code information structure contains the country code string and the source information of the country code. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| country | string | Yes | Represents the country code string. | -| type | CountryCodeType | Yes | Indicates the source of country code information. | - - -## CountryCodeType9+ - -Country code source type. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | The country code obtained from the language configuration information of the globalization module. | -| COUNTRY_CODE_FROM_SIM | 2 | The country code obtained from the SIM card. | -| COUNTRY_CODE_FROM_LOCATION | 3 | Based on the user's location information, the country code is queried through reverse geocoding. | -| COUNTRY_CODE_FROM_NETWORK | 4 | The country code obtained from the cellular network registration information. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index ae8312d452b3a7a0fdea35b0330b5f092ddef05d..a6554d89363a60c801a547d76f306b1b8744e71e 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -47,10 +47,11 @@ Starts an ability with the **want** parameter. This API uses an asynchronous cal ```js let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility"}; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); + 'bundleName': 'com.example.myapp', + 'abilityName': 'MyAbility' + }; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringify(err)); }); ``` @@ -79,8 +80,8 @@ Starts an ability with the mandatory **want** and optional **options** parameter ```js let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" + 'bundleName': 'com.example.myapp', + 'abilityName': 'MyAbility' }; this.context.startAbility(want).then((data) => { console.log('success:' + JSON.stringify(data)); @@ -110,15 +111,15 @@ Starts an ability with the **want** and **options** parameters. This API uses an ```js var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + 'deviceId': '', + 'bundleName': 'com.extreme.test', + 'abilityName': 'MainAbility' }; var options = { windowMode: 0, }; this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) + console.log('error.code = ' + error.code) }) ``` @@ -140,7 +141,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re ```js this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); + console.log('terminateSelf result:' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index da2443a7c87c363ae79085a9b0dfeda4f7f5af99..4502b4cd9601bf0ae050f972a674028fb271a86a 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -16,7 +16,7 @@ import connection from '@ohos.net.connection' getDefaultNet(callback: AsyncCallback\): void -Obtains the default active data network. This API uses an asynchronous callback to return the result. +Obtains the default active data network. This API uses an asynchronous callback to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -41,7 +41,7 @@ connection.getDefaultNet(function (error, netHandle) { getDefaultNet(): Promise\ -Obtains the default active data network. This API uses a promise to return the result. +Obtains the default active data network. This API uses a promise to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -65,7 +65,7 @@ connection.getDefaultNet().then(function (netHandle) { getDefaultNetSync(): NetHandle; -Obtains the default active data network in synchronous mode. +Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -88,8 +88,7 @@ let netHandle = connection.getDefaultNetSync(); hasDefaultNet(callback: AsyncCallback\): void -Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. -The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. +Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -114,8 +113,7 @@ connection.hasDefaultNet(function (error, has) { hasDefaultNet(): Promise\ -Checks whether the default data network is activated. This API uses a promise to return the result. -The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. +Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. **Required permission**: ohos.permission.GET_NETWORK_INFO diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index e88c899e36745869e6009616b1c8581c3fa37b49..1fd0357783d6cf3ead6913cfc07a0e4b4e1c3c82 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -4,6 +4,8 @@ The **Prompt** module provides APIs for creating and showing toasts, dialog boxe > **NOTE** > +> The APIs of this module are deprecated since API Version 9. You are advised to use [@ohos.promptAction](js-apis-promptAction.md) instead. +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -35,6 +37,8 @@ prompt.showToast({ }); ``` +![en-us_image_0001](figures/en-us_image_0001.gif) + ## ShowToastOptions Describes the options for showing the toast. @@ -43,9 +47,9 @@ Describes the options for showing the toast. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text to display. | | duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. | ## prompt.showDialog @@ -92,6 +96,8 @@ prompt.showDialog({ }) ``` +![en-us_image_0002](figures/en-us_image_0002.gif) + ## prompt.showDialog showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void @@ -132,6 +138,8 @@ prompt.showDialog({ }); ``` +![en-us_image_0004](figures/en-us_image_0004.gif) + ## ShowDialogOptions Describes the options for showing the dialog box. @@ -140,8 +148,8 @@ Describes the options for showing the dialog box. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | -| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Text body. | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Text body. | | buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -170,7 +178,6 @@ Shows an action menu. This API uses a callback to return the result asynchronous | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | | callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| - **Example** ```js @@ -195,6 +202,8 @@ prompt.showActionMenu({ }) ``` +![en-us_image_0005](figures/en-us_image_0005.gif) + ## prompt.showActionMenu showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> @@ -238,6 +247,8 @@ prompt.showActionMenu({ console.info('showActionMenu error: ' + err); }) ``` +![en-us_image_0006](figures/en-us_image_0006.gif) + ## ActionMenuOptions Describes the options for showing the action menu. @@ -246,7 +257,7 @@ Describes the options for showing the action menu. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | | buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -267,5 +278,5 @@ Describes the menu item button in the action menu. | Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | ------- | -| text | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Button text.| -| color | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Button text.| +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md new file mode 100644 index 0000000000000000000000000000000000000000..268673b046bbb5f775dfffe3986105718319d009 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -0,0 +1,341 @@ +# Prompt + +The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import promptAction from '@ohos.promptAction' +``` + +## promptAction.showToast + +showToast(options: ShowToastOptions): void + +Shows a toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | ------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showToast({ + message: 'Message Info', + duration: 2000, + }); +} catch (error) { + console.error(`showToast args error code is ${error.code}, message is ${error.message}`); +}; + +``` + +![en-us_image_0001](figures/en-us_image_0001.gif) + +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | + +## promptAction.showDialog + +showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> + +Shows a dialog box. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------- | +| Promise<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ], + }) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0002](figures/en-us_image_0002.gif) + +## promptAction.showDialog + +showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void + +Shows a dialog box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ] + }, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; + } + console.info('showDialog success callback, click button: ' + data.index); + }); +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0002](figures/en-us_image_0002.gif) + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| + +## ShowDialogSuccessResponse + +Describes the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Description | +| ----- | ------ | ------------------- | +| index | number | Index of the selected button in the **buttons** array.| + +## promptAction.showActionMenu + +showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void + +Shows an action menu. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | +| callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; + } + console.info('showActionMenu success callback, click button: ' + data.index); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0005](figures/en-us_image_0005.gif) + +## promptAction.showActionMenu + +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> + +Shows an action menu. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0005](figures/en-us_image_0005.gif) + +## ActionMenuOptions + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| + +## ActionMenuSuccessResponse + +Describes the action menu response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------------------ | +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------- | +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Button text.| +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index ec920f58cab6825ce1dd286f42d1eb24e759f10b..ad01b50bc77d167a58eff666777c2d383cec8922 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1840,10 +1840,10 @@ Defines the network status. | Name | Value | Description | | ----------------------------- | ---- | -------------------------- | -| REG_STATE_NO_SERVICE | 0 | The device cannot use any service. | -| REG_STATE_IN_SERVICE | 1 | The device can use services normally. | -| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service.| -| REG_STATE_POWER_OFF | 3 | The cellular radio service is disabled. | +| REG_STATE_NO_SERVICE | 0 | The device cannot use any services, including data, SMS, and call services. | +| REG_STATE_IN_SERVICE | 1 | The device can use services properly, including data, SMS, and call services. | +| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service. | +| REG_STATE_POWER_OFF | 3 | The device cannot communicate with the network because the cellular radio service is disabled or the modem is powered off. | ## NsaState diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2609d848a83392c8b0630015b2f135894fde0a61..27e794f1f636971f637b4cfe3bda4eff9fbb0852 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -14,108 +14,404 @@ The **Router** module provides APIs to access pages through URLs. You can use th import router from '@ohos.router' ``` -## router.push +## router.pushUrl9+ -push(options: RouterOptions): void +pushUrl(options: RouterOptions): Promise<void> Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | --------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | **Example** + ```js -router.push({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, }, - }, -}); + }) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` -## router.push9+ -push(options: RouterOptions, mode: RouterMode): void +## router.pushUrl9+ + +pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | + +**Example** + +```js +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); + }); +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` +## router.pushUrl9+ + +pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | **Example** + ```js -router.push({ - url: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, }, - }, -},router.RouterMode.Standard); + }, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` -## router.replace +## router.pushUrl9+ -replace(options: RouterOptions): void +pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void -Replaces the current page with another one in the application and destroys the current page. +Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | + +**Example** + +```js +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); + }); +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------ | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + **Example** ```js -router.replace({ - url: 'pages/detail', - params: { - data1: 'message', - }, -}); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` - ## router.replace9+ +## router.replaceUrl9+ -replace(options: RouterOptions, mode: RouterMode): void +replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + +**Example** + +```js +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); + }); +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + **Example** ```js -router.replace({ - url: 'pages/detail/detail', - params: { - data1: 'message', - }, -}, router.RouterMode.Standard); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + +**Example** + +```js +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); + }); +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` ## router.back @@ -127,6 +423,7 @@ Returns to the previous page or a specified page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------------------------------------------------ | | options | [RouterOptions](#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the previous page is returned, and the page in the page stack is not reclaimed. It will be reclaimed after being popped up.| @@ -160,11 +457,13 @@ Obtains the number of pages in the current stack. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Return value** + | Type | Description | | ------ | ------------------ | | string | Number of pages in the stack. The maximum value is **32**.| **Example** + ```js var size = router.getLength(); console.log('pages stack size = ' + size); @@ -205,25 +504,38 @@ Describes the page routing state. | name | string | Name of the current page, that is, the file name. | | path | string | Path of the current page. | -## router.enableAlertBeforeBackPage +## router.enableBackPageAlert9+ -enableAlertBeforeBackPage(options: EnableAlertOptions): void +enableBackPageAlert(options: EnableAlertOptions): void Enables the display of a confirm dialog box before returning to the previous page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | --------- | | options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + **Example** - ```js - router.enableAlertBeforeBackPage({ + ```js +try { + router.enableBackPageAlert({ message: 'Message Info' - }); + }); +} catch(error) { + console.error(`enableBackPageAlert failed, code is ${error.code}, message is ${error.message}`); +} ``` ## EnableAlertOptions @@ -244,6 +556,7 @@ Disables the display of a confirm dialog box before returning to the previous pa **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** + ```js router.disableAlertBeforeBackPage(); ``` @@ -274,10 +587,10 @@ Describes the page routing options. **System capability**: SystemCapability.ArkUI.ArkUI.Lite -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| url | string | Yes | URI of the destination page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No | Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| url | string | Yes | URL of the target page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URL is a slash (/), the home page is displayed.| +| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| > **NOTE** @@ -291,7 +604,7 @@ Enumerates the routing modes. | Name | Description | | -------- | ---------------------------------------- | -| Standard | Standard mode. | +| Standard | Standard mode.
The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack. | | Single | Singleton mode.
If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.
If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.| ## Examples @@ -401,3 +714,144 @@ struct Second { } } ``` + +## router.push(deprecated) + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| + + +**Example** + +```js +router.push({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +}); +``` +## router.push(deprecated) + +push(options: RouterOptions, mode: RouterMode): void + +Navigates to a specified page in the application. + +This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + + +**Example** + +```js +router.push({ + url: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +},router.RouterMode.Standard); +``` + +## router.replace(deprecated) + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| + +**Example** + +```js +router.replace({ + url: 'pages/detail', + params: { + data1: 'message', + }, +}); +``` + + ## router.replace(deprecated) + +replace(options: RouterOptions, mode: RouterMode): void + +Replaces the current page with another one in the application and destroys the current page. + +This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Example** + +```js +router.replace({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, +}, router.RouterMode.Standard); +``` + +## router.enableAlertBeforeBackPage(deprecated) + +enableAlertBeforeBackPage(options: EnableAlertOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +This API is deprecated since API version 9. You are advised to use [enableBackPageAlert9+](#routerenablebackpagealert9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | --------- | +| options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| + +**Example** + + ```js + router.enableAlertBeforeBackPage({ + message: 'Message Info' + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 73ea5d3c915d2ba91c129ed8d7c8ed80efe8170d..47cb10179c1d12d9bd7d010b9db08dc316b57f7f 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,4 +1,5 @@ # Screen + The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. > **NOTE** @@ -6,6 +7,7 @@ The **Screen** module implements basic screen management. You can use the APIs o > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > The APIs provided by this module are system APIs. + ## Modules to Import ```js @@ -26,19 +28,28 @@ Obtains all screens. This API uses an asynchronous callback to return the result | -------- | --------------------------------------------------- | ---- | -------------------------------------- | | callback | AsyncCallback<Array<[Screen](#screen)>> | Yes | Callback used to return all the **Screen** objects obtained.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var screenClass = null; +let screenClass = null; screen.getAllScreens((err, data) => { if (err.code) { - console.error('Failed to get all screens . Cause: ' + JSON.stringify(err)); + console.error('Failed to get all screens. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in getting all screens . Data:' + JSON.stringify(data)); + console.info('Succeeded in getting all screens. Data:' + JSON.stringify(data)); screenClass = data[0]; }); ``` + ## screen.getAllScreens getAllScreens(): Promise<Array<Screen>> @@ -48,22 +59,34 @@ Obtains all screens. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** + | Type | Description | | --------------------------------------------- | ----------------------------------------- | | Promise<Array<[Screen](#screen)>> | Promise used to return all the **Screen** objects obtained.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenClass = null; +let screenClass = null; let promise = screen.getAllScreens(); promise.then((data) => { screenClass = data[0]; - console.log('Succeeded in getting all screens . Data:'+ JSON.stringify(data)); + console.log('Succeeded in getting all screens. Data:'+ JSON.stringify(data)); }).catch((err) => { - console.log('Failed to get all screens . Cause: ' + JSON.stringify(err)); + console.log('Failed to get all screens. Cause: ' + JSON.stringify(err)); }); ``` + ## screen.on('connect' | 'disconnect' | 'change') + on(eventType: 'connect' | 'disconnect' | 'change', callback: Callback<number>): void Subscribes to events related to the screen state. @@ -71,19 +94,27 @@ Subscribes to events related to the screen state. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | --------- | ---------------------- | ---- | ------------------------------------------------------------ | | eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| | callback | Callback<number> | Yes | Callback used to return the screen ID. | **Example** + ```js -var callback = (data) => { - console.info('Register the callback for screen changes. Data: ' + JSON.stringify(data)) +try { + let callback = (data) => { + console.info('Succeeded in registering the callback for screen changes. Data: ' + JSON.stringify(data)) + }; + screen.on('connect', callback); +} catch (exception) { + console.error('Failed to register the callback for screen changes. Code: ' + JSON.stringify(exception)); }; -screen.on("connect", callback); ``` + ## screen.off('connect' | 'disconnect' | 'change') + off(eventType: 'connect' | 'disconnect' | 'change', callback?: Callback<number>): void Unsubscribes from events related to the screen state. @@ -91,20 +122,27 @@ Unsubscribes from events related to the screen state. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | --------- | ---------------------- | ---- | ------------------------------------------------------------ | | eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| | callback | Callback<number> | No | Callback used to return the screen ID. | **Example** + ```js -var callback = (data) => { - console.info('Unregister the callback for screen changes. Data: ' + JSON.stringify(data)) +try { + let callback = (data) => { + console.info('Succeeded in unregistering the callback for screen changes. Data: ' + JSON.stringify(data)) + }; + screen.off('connect', callback); +} catch (exception) { + console.error('Failed to register the callback for screen changes. Code: ' + JSON.stringify(exception)); }; -screen.off("connect", callback); ``` ## screen.makeExpand + makeExpand(options:Array<ExpandOption>, callback: AsyncCallback<number>): void Sets the screen to the expanded mode. This API uses an asynchronous callback to return the result. @@ -112,26 +150,40 @@ Sets the screen to the expanded mode. This API uses an asynchronous callback to **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------------ | ---- | -------------------------------- | | options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen. | | callback | Callback<number> | Yes | Callback used to return the group ID of the expanded screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var groupId = null; -screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}], (err, data) => { - if (err.code) { - console.error('Failed to make screens as expand-screen. Cause:' + JSON.stringify(err)); - return; - } - groupId = data; - console.info('Succeeded in making screens as expand-screen.Data:' + JSON.stringify(data)); -}); +try { + let groupId = null; + screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}], (err, data) => { + if (err.code) { + console.error('Failed to expand the screen. Code:' + JSON.stringify(err)); + return; + } + groupId = data; + console.info('Succeeded in expanding the screen. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to expand the screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.makeExpand + makeExpand(options:Array<ExpandOption>): Promise<number> Sets the screen to the expanded mode. This API uses a promise to return the result. @@ -145,20 +197,35 @@ Sets the screen to the expanded mode. This API uses a promise to return the resu | options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen.| **Return value** + | Type | Description | | --------------------- | ----------------------------------- | | Promise<number> | Promise used to return the group ID of the expanded screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}]).then((data) => { - console.info('Succeeded in making screens as expand-screen.Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to make screens as expand-screen. Cause:' + JSON.stringify(err)); -}); +try { + screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}]).then((data) => { + console.info('Succeeded in expanding the screen. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to expand the screen. Code:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to expand the screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.makeMirror + makeMirror(mainScreen:number, mirrorScreen:Array<number>, callback: AsyncCallback<number>): void Sets screen mirroring. This API uses an asynchronous callback to return the result. @@ -173,20 +240,34 @@ Sets screen mirroring. This API uses an asynchronous callback to return the resu | mirrorScreen | Array<number> | Yes | IDs of secondary screens. | | callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the secondary screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var mainScreenId = 0; -var mirrorScreenIds = [1, 2, 3]; -screen.makeMirror(mainScreenId, mirrorScreenIds, (err, data) => { - if (err.code) { - console.error('Failed to make screens as mirror-screen.Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in making screens as mirror-screen.Data:' + JSON.stringify(data)); -}); +let mainScreenId = 0; +let mirrorScreenIds = [1, 2, 3]; +try { + screen.makeMirror(mainScreenId, mirrorScreenIds, (err, data) => { + if (err.code) { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting screen mirroring. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.makeMirror + makeMirror(mainScreen:number, mirrorScreen:Array<number>): Promise<number> Sets screen mirroring. This API uses a promise to return the result. @@ -201,22 +282,37 @@ Sets screen mirroring. This API uses a promise to return the result. | mirrorScreen | Array<number> | Yes | IDs of secondary screens.| **Return value** + | Type | Description | | --------------------- | ----------------------------------- | | Promise<number> | Promise used to return the group ID of the secondary screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var mainScreenId = 0; -var mirrorScreenIds = [1, 2, 3]; -screen.makeMirror(mainScreenId, mirrorScreenIds).then((data) => { - console.info('Succeeded in making screens as mirror-screen.Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to make screens as mirror-screen.Cause:' + JSON.stringify(err)); -}); +let mainScreenId = 0; +let mirrorScreenIds = [1, 2, 3]; +try { + screen.makeMirror(mainScreenId, mirrorScreenIds).then((data) => { + console.info('Succeeded in setting screen mirroring. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.createVirtualScreen + createVirtualScreen(options:VirtualScreenOption, callback: AsyncCallback<Screen>): void Creates a virtual screen. This API uses an asynchronous callback to return the result. @@ -232,35 +328,50 @@ Creates a virtual screen. This API uses an asynchronous callback to return the r | options | [VirtualScreenOption](#virtualscreenoption) | Yes | Virtual screen parameters. | | callback | AsyncCallback<[Screen](#screen)> | Yes | Callback used to return the created virtual screen.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenClass = null; -screen.createVirtualScreen({ - name: 'screen01', - width: 1080, - height: 2340, - density: 2, - surfaceId: '' -}, (err, data) => { - if (err.code) { - console.error('Failed to create virtual screen.Cause:' + JSON.stringify(err)); - return; - } - screenClass = data; - console.info('Succeeded in creating virtual screen.Data:' + JSON.stringify(data)); -}); +let screenClass = null; +try { + screen.createVirtualScreen({ + name: 'screen01', + width: 1080, + height: 2340, + density: 2, + surfaceId: '' + }, (err, data) => { + if (err.code) { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(err)); + return; + } + screenClass = data; + console.info('Succeeded in creating the virtual screen. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.createVirtualScreen + createVirtualScreen(options:VirtualScreenOption): Promise<Screen> Creates a virtual screen. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid available only to system applications) +**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid; available only to system applications) **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------------------- | ---- | ------------------------ | | options | [VirtualScreenOption](#virtualscreenoption) | Yes | Virtual screen parameters.| @@ -271,24 +382,38 @@ Creates a virtual screen. This API uses a promise to return the result. | -------------------------------- | ------------------------------------- | | Promise<[Screen](#screen)> | Promise used to return the created virtual screen.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenClass = null; -screen.createVirtualScreen({ - name: 'screen01', - width: 1080, - height: 2340, - density: 2, - surfaceId: '' -}).then((data) => { - screenClass = data; - console.info('Succeeded in creating virtual screen.Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to create virtual screen.Cause:' + JSON.stringify(err)); -}); +let screenClass = null; +try { + screen.createVirtualScreen({ + name: 'screen01', + width: 1080, + height: 2340, + density: 2, + surfaceId: '' + }).then((data) => { + screenClass = data; + console.info('Succeeded in creating the virtual screen. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.destroyVirtualScreen + destroyVirtualScreen(screenId:number, callback: AsyncCallback<void>): void Destroys a virtual screen. This API uses an asynchronous callback to return the result. @@ -296,24 +421,39 @@ Destroys a virtual screen. This API uses an asynchronous callback to return the **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | screenId | number | Yes | Screen ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------------- | +| 1400002 | Unauthorized operation. | + **Example** + ```js -var screenId = 1; -screen.destroyVirtualScreen(screenId, (err,data) => { - if (err.code) { - console.error('Failed to destroy virtual screen.Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying virtual screen.'); -}); +let screenId = 1; +try { + screen.destroyVirtualScreen(screenId, (err,data) => { + if (err.code) { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the virtual screen.'); + }); +} catch (exception) { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.destroyVirtualScreen + destroyVirtualScreen(screenId:number): Promise<void> Destroys a virtual screen. This API uses a promise to return the result. @@ -321,26 +461,42 @@ Destroys a virtual screen. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------- | | screenId | number | Yes | Screen ID.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------------- | +| 1400002 | Unauthorized operation. | + **Example** + ```js -var screenId = 1; -screen.destroyVirtualScreen(screenId).then((data) => { - console.info('Succeeded in destroying virtual screen.'); -}).catch((err) => { - console.error('Failed to destroy virtual screen.Cause:' + JSON.stringify(err)); -}); +let screenId = 1; +try { + screen.destroyVirtualScreen(screenId).then((data) => { + console.info('Succeeded in destroying the virtual screen.'); + }).catch((err) => { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.setVirtualScreenSurface + setVirtualScreenSurface(screenId:number, surfaceId: string, callback: AsyncCallback<void>): void Sets the surface for a virtual screen. This API uses an asynchronous callback to return the result. @@ -357,21 +513,34 @@ Sets the surface for a virtual screen. This API uses an asynchronous callback to | surfaceId | string | Yes | Surface ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen surface is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var screenId = 1; -var surfaceId = '2048'; -screen.setVirtualScreenSurface(screenId, surfaceId, (err,data) => { - if (err.code) { - console.error('Failed to set surface for the virtual screen. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting surface for the virtual screen.'); -}); +let screenId = 1; +let surfaceId = '2048'; +try { + screen.setVirtualScreenSurface(screenId, surfaceId, (err,data) => { + if (err.code) { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the surface for the virtual screen.'); + }); +} catch (exception) { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.setVirtualScreenSurface + setVirtualScreenSurface(screenId:number, surfaceId: string): Promise<void> Sets the surface for a virtual screen. This API uses a promise to return the result. @@ -381,28 +550,44 @@ Sets the surface for a virtual screen. This API uses a promise to return the res **Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------- | | screenId | number | Yes | Screen ID. | | surfaceId | string | Yes | Surface ID.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenId = 1; -var surfaceId = '2048'; -screen.setVirtualScreenSurface(screenId, surfaceId).then((data) => { - console.info('Succeeded in setting surface for the virtual screen.'); -}).catch((err) => { - console.error('Failed to set surface for the virtual screen. Cause:' + JSON.stringify(err)); -}); +let screenId = 1; +let surfaceId = '2048'; +try { + screen.setVirtualScreenSurface(screenId, surfaceId).then((data) => { + console.info('Succeeded in setting the surface for the virtual screen.'); + }).catch((err) => { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.isScreenRotationLocked + isScreenRotationLocked(): Promise<boolean> Checks whether auto rotate is locked. This API uses a promise to return the result. @@ -410,20 +595,23 @@ Checks whether auto rotate is locked. This API uses a promise to return the resu **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** + | Type | Description | | ---------------------- | ------------------------------------- | | Promise<boolean> | Promise used to return the result. If **true** is returned, auto rotate is locked. If **false** is returned, auto rotate is unlocked.| **Example** + ```js screen.isScreenRotationLocked().then((isLocked) => { - console.info('Succeeded in getting screen rotation lock status. isLocked:'+ JSON.stringify(isLocked)); + console.info('Succeeded in getting the screen rotation lock status. isLocked:'+ JSON.stringify(isLocked)); }).catch((err) => { - console.error('Failed to get screen rotation lock status. Cause:' + JSON.stringify(err)); + console.error('Failed to get the screen rotation lock status. Cause:' + JSON.stringify(err)); }); ``` ## screen.isScreenRotationLocked + isScreenRotationLocked(callback: AsyncCallback<boolean>): void Checks whether auto rotate is locked. This API uses an asynchronous callback to return the result. @@ -441,14 +629,15 @@ Checks whether auto rotate is locked. This API uses an asynchronous callback to ```js screen.isScreenRotationLocked((err, isLocked) => { if (err.code) { - console.error('Failed to get screen rotation lock status. Cause:' + JSON.stringify(err)); + console.error('Failed to get the screen rotation lock status. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in getting screen rotation lock status. isLocked:' + JSON.stringify(isLocked)); + console.info('Succeeded in getting the screen rotation lock status. isLocked:' + JSON.stringify(isLocked)); }); ``` ## screen.setScreenRotationLocked + setScreenRotationLocked(isLocked: boolean): Promise<void> Sets whether to lock auto rotate. This API uses a promise to return the result. @@ -456,26 +645,34 @@ Sets whether to lock auto rotate. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------- | | isLocked | boolean | Yes | Whether to lock auto rotate. The value **true** means to lock auto rotate, and **false** means the opposite.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js -var isLocked = false; -screen.setScreenRotationLocked(isLocked).then((data) => { - console.info('Succeeded in setting whether to lock screen rotation'); -}).catch((err) => { - console.error('Failed to set whether to lock screen rotation. Cause:' + JSON.stringify(err)); -}); +let isLocked = false; +try { + screen.setScreenRotationLocked(isLocked).then((data) => { + console.info('Succeeded in unlocking auto rotate'); + }).catch((err) => { + console.error('Failed to unlock auto rotate. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to unlock auto rotate. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.setScreenRotationLocked + setScreenRotationLocked(isLocked: boolean, callback: AsyncCallback<void>): void Sets whether to lock auto rotate. This API uses an asynchronous callback to return the result. @@ -492,17 +689,22 @@ Sets whether to lock auto rotate. This API uses an asynchronous callback to retu **Example** ```js -var isLocked = false; -screen.setScreenRotationLocked(isLocked, (err, data) => { - if (err.code) { - console.error('Failed to set whether to lock screen rotation. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting whether to lock screen rotation.'); -}); +let isLocked = false; +try { + screen.setScreenRotationLocked(isLocked, (err, data) => { + if (err.code) { + console.error('Failed to unlock auto rotate. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in unlocking auto rotate.'); + }); +} catch (exception) { + console.error('Failed to unlock auto rotate. Code: ' + JSON.stringify(exception)); +}; ``` ## ExpandOption + Defines the parameters for expanding a screen. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -514,6 +716,7 @@ Defines the parameters for expanding a screen. | startY | number | Yes | Yes | Start Y coordinate of the screen.| ## VirtualScreenOption + Defines virtual screen parameters. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -527,6 +730,7 @@ Defines virtual screen parameters. | surfaceId | string | Yes | Yes | Surface ID of the virtual screen.| ## Screen + Implements a **Screen** instance. Before calling any API in **Screen**, you must use **[getAllScreens()](#screengetallscreens)** or **[createVirtualScreen()](#screencreatevirtualscreen)** to obtain a **Screen** instance. @@ -542,6 +746,7 @@ Before calling any API in **Screen**, you must use **[getAllScreens()](#screenge | orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | ### setOrientation + setOrientation(orientation: Orientation, callback: AsyncCallback<void>): void Sets the screen orientation. This API uses an asynchronous callback to return the result. @@ -553,17 +758,32 @@ Sets the screen orientation. This API uses an asynchronous callback to return th | orientation | [Orientation](#orientation) | Yes | Screen orientation. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the screen orientation is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => { - if (err.code) { - console.error('Failed to setOrientation VERTICAL. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting Orientation VERTICAL. data: ' + JSON.stringify(data)); -}) +try { + screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => { + if (err.code) { + console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the vertical orientation. data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(exception)); +}; ``` + ### setOrientation + setOrientation(orientation: Orientation): Promise<void> Sets the screen orientation. This API uses a promise to return the result. @@ -575,20 +795,36 @@ Sets the screen orientation. This API uses a promise to return the result. | orientation | [Orientation](#orientation) | Yes | Screen orientation.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -let promise = screenClass.setOrientation(screen.Orientation.VERTICAL); -promise.then((data) => { - console.info('Succeeded in setting Orientation VERTICAL. Data: ' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to set Orientation VERTICAL. Cause: ' + JSON.stringify(err)); -}) +try { + let promise = screenClass.setOrientation(screen.Orientation.VERTICAL); + promise.then((data) => { + console.info('Succeeded in setting the vertical orientation. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set the vertical orientation. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(exception)); +}; ``` + ### setScreenActiveMode + setScreenActiveMode(modeIndex: number, callback: AsyncCallback<void>): void Sets the active mode of the screen. This API uses an asynchronous callback to return the result. @@ -600,19 +836,33 @@ Sets the active mode of the screen. This API uses an asynchronous callback to re | modeIndex | number | Yes | Index of the mode to set. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the active mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** ```js -var modeIndex = 0; -screenClass.setScreenActiveMode(modeIndex, (err, data) => { - if (err.code) { - console.error('Failed to set ScreenActiveMode 0. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting ScreenActiveMode 0. data: ' + JSON.stringify(data)); -}) +let modeIndex = 0; +try { + screenClass.setScreenActiveMode(modeIndex, (err, data) => { + if (err.code) { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting screen active mode 0. data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(exception)); +}; ``` + ### setScreenActiveMode + setScreenActiveMode(modeIndex: number): Promise<void> Sets the active mode of the screen. This API uses a promise to return the result. @@ -629,18 +879,32 @@ Sets the active mode of the screen. This API uses a promise to return the result | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -var modeIndex = 0; -let promise = screenClass.setScreenActiveMode(modeIndex); -promise.then((data) => { - console.info('Succeeded in setting ScreenActiveMode 0. Data: ' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to set ScreenActiveMode 0. Cause: ' + JSON.stringify(err)); -}) +let modeIndex = 0; +try { + let promise = screenClass.setScreenActiveMode(modeIndex); + promise.then((data) => { + console.info('Succeeded in setting screen active mode 0. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(exception)); +}; ``` ### setDensityDpi + setDensityDpi(densityDpi: number, callback: AsyncCallback<void>): void; Sets the pixel density of the screen. This API uses an asynchronous callback to return the result. @@ -652,19 +916,33 @@ Sets the pixel density of the screen. This API uses an asynchronous callback to | densityDpi | number | Yes | Pixel density. The value ranges from 80 to 640. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the pixel density is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -var densityDpi = 320; -screenClass.setDensityDpi(densityDpi, (err, data) => { - if (err.code) { - console.error('Failed to set DensityDpi 320. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeed in setting DensityDpi 320. data: ' + JSON.stringify(data)); -}) +let densityDpi = 320; +try { + screenClass.setDensityDpi(densityDpi, (err, data) => { + if (err.code) { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeed in setting the pixel density of the screen to 320. data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(exception)); +}; ``` ### setDensityDpi + setDensityDpi(densityDpi: number): Promise<void> Sets the pixel density of the screen. This API uses a promise to return the result. @@ -681,18 +959,32 @@ Sets the pixel density of the screen. This API uses a promise to return the resu | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -var densityDpi = 320; -var promise = screenClass.setDensityDpi(densityDpi); -promise.then((data) => { - console.info('Succeeded in setting DensityDpi 320. Data: ' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to set DensityDpi 320. Cause: ' + JSON.stringify(err)); -}) +let densityDpi = 320; +try { + let promise = screenClass.setDensityDpi(densityDpi); + promise.then((data) => { + console.info('Succeeded in setting the pixel density of the screen to 320. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(exception)); +}; ``` ## Orientation + Enumerates the screen orientations. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -706,6 +998,7 @@ Enumerates the screen orientations. | REVERSE_HORIZONTAL | 4 | Reverse horizontal. | ## ScreenModeInfo + Defines the screen mode information. **System capability**: SystemCapability.WindowManager.WindowManager.Core diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 550b62ed355d0a09eb57d17c5473c37cd7e45899..0e8b04295567caf1a018a9f9d3c8122b7f89e41d 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -73,7 +73,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async **Example** ```js - var screenshotOptions = { + let screenshotOptions = { "screenRect": { "left": 200, "top": 100, @@ -85,14 +85,18 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async "rotation": 0, "displayId": 0 }; - screenshot.save(screenshotOptions, (err, pixelMap) => { - if (err) { - console.log('Failed to save screenshot: ' + JSON.stringify(err)); - return; - } - console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. - }); + try { + screenshot.save(screenshotOptions, (err, pixelMap) => { + if (err) { + console.log('Failed to save screenshot. Code: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. + }); + } catch (exception) { + console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception)); + }; ``` ## screenshot.save @@ -114,14 +118,18 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async **Example** ```js - screenshot.save((err, pixelMap) => { - if (err) { - console.log('Failed to save screenshot: ' + JSON.stringify(err)); - return; - } - console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. - }); + try { + screenshot.save((err, pixelMap) => { + if (err) { + console.log('Failed to save screenshot. Code: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. + }); + } catch (exception) { + console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception)); + }; ``` ## screenshot.save @@ -149,7 +157,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis **Example** ```js - var screenshotOptions = { + let screenshotOptions = { "screenRect": { "left": 200, "top": 100, @@ -161,11 +169,15 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis "rotation": 0, "displayId": 0 }; - let promise = screenshot.save(screenshotOptions); - promise.then((pixelMap) => { - console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. - }).catch((err) => { - console.log('Failed to save screenshot: ' + JSON.stringify(err)); - }); + try { + let promise = screenshot.save(screenshotOptions); + promise.then((pixelMap) => { + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. + }).catch((err) => { + console.log('Failed to save screenshot. Code: ' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception)); + }; ``` diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 6622b4b719e95f2c87af19653fbf8a89905239f2..206ad668b6dbdaf8f12d74423a92c5d6ebaf2853 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -689,7 +689,7 @@ promise.then(data => { ## sim.**setShowName**8+ -setShowName\(slotId: number, name: string,callback: AsyncCallback\): void +setShowName\(slotId: number, name: string, callback: AsyncCallback\): void Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy **Example** ```js -let name = 'China Mobile'; +let name = "China Mobile"; 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 = "China Mobile"; let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); @@ -818,7 +818,7 @@ promise.then(data => { ## sim.**setShowNumber**8+ -setShowNumber\(slotId: number, number: string,callback: AsyncCallback\): void +setShowNumber\(slotId: number, number: string, callback: AsyncCallback\): void Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -848,7 +848,7 @@ sim.setShowNumber(0, number, (err, data) => { ## sim.**setShowNumber**8+ -setShowNumber\(slotId: number,number: string\): Promise\ +setShowNumber\(slotId: number, number: string\): Promise\ Sets a display number for the SIM card in the specified slot. This API uses a promise to return the result. @@ -885,7 +885,7 @@ promise.then(data => { ## sim.**getShowNumber**8+ -getShowNumber(slotId: number,callback: AsyncCallback): void +getShowNumber(slotId: number, callback: AsyncCallback): void Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1097,7 +1097,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy ```js let lockInfo = { lockType: sim.LockType.PIN_LOCK, - password = "1234", + password: "1234", state: sim.LockState.LOCK_OFF }; sim.setLockState(0, lockInfo, (err, data) => { @@ -1136,7 +1136,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom ```js let lockInfo = { lockType: sim.LockType.PIN_LOCK, - password = "1234", + password: "1234", state: sim.LockState.LOCK_OFF }; let promise = sim.setLockState(0, lockInfo); @@ -1344,7 +1344,7 @@ promise.then(data => { ## sim.**unlockPin**7+ -unlockPin(slotId: number,pin: string ,callback: AsyncCallback): void +unlockPin(slotId: number, pin: string, callback: AsyncCallback): void Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1374,7 +1374,7 @@ sim.unlockPin(0, pin, (err, data) => { ## sim.**unlockPin**7+ -unlockPin(slotId: number,pin: string): Promise<LockStatusResponse\> +unlockPin(slotId: number, pin: string): Promise<LockStatusResponse\> Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1411,7 +1411,7 @@ promise.then(data => { ## sim.**unlockPuk**7+ -unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback): void +unlockPuk(slotId: number, newPin: string, puk: string ,callback: AsyncCallback): void Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1443,7 +1443,7 @@ sim.unlockPuk(0, newPin, puk, (err, data) => { ## sim.**unlockPuk**7+ -unlockPuk(slotId: number,newPin: string,puk: string): Promise<LockStatusResponse\> +unlockPuk(slotId: number, newPin: string, puk: string): Promise<LockStatusResponse\> Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1482,7 +1482,7 @@ promise.then(data => { ## sim.**unlockPin**28+ -unlockPin2(slotId: number,pin2: string ,callback: AsyncCallback): void +unlockPin2(slotId: number, pin2: string, callback: AsyncCallback): void Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1512,7 +1512,7 @@ sim.unlockPin2(0, pin2, (err, data) => { ## sim.**unlockPin**28+ -unlockPin2(slotId: number,pin2: string): Promise<LockStatusResponse\> +unlockPin2(slotId: number, pin2: string): Promise<LockStatusResponse\> Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1539,7 +1539,7 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to ```js let pin2='1234'; -let promise = sim.unlockPin2(0,pin2); +let promise = sim.unlockPin2(0, pin2); promise.then(data => { console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1851,7 +1851,7 @@ Sets voice mailbox information for the SIM card in the specified slot. This API **Example** ```js -sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com" , (err, data) => { +sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com", (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2602,8 +2602,8 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba ```js let persoLockInfo = { - lockType = sim.PersoLockType.PN_PIN_LOCK, - password = "1234" + lockType: sim.PersoLockType.PN_PIN_LOCK, + password: "1234" }; sim.unlockSimLock(0, persoLockInfo, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2640,8 +2640,8 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th ```js let persoLockInfo = { - lockType = sim.PersoLockType.PN_PIN_LOCK, - password = "1234" + lockType: sim.PersoLockType.PN_PIN_LOCK, + password: "1234" }; let promise = sim.unlockSimLock(0, persoLockInfo); promise.then(data => { diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 6920c9dbf3aea204efb78c292e949a7ec0e4a053..7d372978202503f6ed0a0517fa69f85ae5dfcf44 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -160,7 +160,7 @@ promise.then(data => { ## sms.setDefaultSmsSlotId7+ -setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback<void>\): void +setDefaultSmsSlotId\(slotId: number, callback: AsyncCallback<void>\): void Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. @@ -180,7 +180,7 @@ Sets the default slot of the SIM card used to send SMS messages. This API uses a **Example** ```js -sms.setDefaultSmsSlotId(0,(err, data) => { +sms.setDefaultSmsSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -610,8 +610,8 @@ let updateSimMessageOptions = { slotId: 0, msgIndex: 1, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, - pdu = "xxxxxxx", - smsc = "test" + pdu: "xxxxxxx", + smsc: "test" }; sms.updateSimMessage(updateSimMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -650,8 +650,8 @@ let updateSimMessageOptions = { slotId: 0, msgIndex: 1, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, - pdu = "xxxxxxx", - smsc = "test" + pdu: "xxxxxxx", + smsc: "test" }; let promise = sms.updateSimMessage(updateSimMessageOptions); promise.then(data => { @@ -1054,13 +1054,13 @@ Encodes MMS messages. This API uses an asynchronous callback to return the resul ```js let mmsAcknowledgeInd = { - transactionId = "100", - version = 0x10, - reportAllowed = 128 + transactionId: "100", + version: sms.MmsVersionType.MMS_VERSION_1_0, + reportAllowed: sms.ReportType.MMS_YES }; let mmsInformation = { - messageType = 133, - mmsType = mmsAcknowledgeInd + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + mmsType: mmsAcknowledgeInd }; sms.encodeMms(mmsInformation, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -1096,10 +1096,10 @@ Encodes MMS messages. This API uses a promise to return the result. let mmsAcknowledgeInd = { transactionId: "100", version: sms.MmsVersionType.MMS_VERSION_1_0, - reportAllowed = sms.ReportType.MMS_YES + reportAllowed: sms.ReportType.MMS_YES }; let mmsInformation = { - messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, mmsType: mmsAcknowledgeInd }; let promise = sms.encodeMms(mmsInformation); diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index f3a29a9cc683fecc38b4c935af7607bd2a5415b8..a8ea022b24881bd1def701d3c59433270b0da762 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -88,7 +88,7 @@ console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) ## data.setDefaultCellularDataSlotId -setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void +setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\): void Sets the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. @@ -108,7 +108,7 @@ This is a system API. **Example** ```js -data.setDefaultCellularDataSlotId(0,(err, data) => { +data.setDefaultCellularDataSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -313,7 +313,7 @@ Checks whether the cellular data roaming service is enabled. This API uses an as **Example** ```js -data.isCellularDataRoamingEnabled(0,(err, data) => { +data.isCellularDataRoamingEnabled(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 91c284004f4b1e2f22d46ba27c3249d9b05dd5bb..e88c24874ded38ec76625957039617147d5664b6 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,6 +1,6 @@ # Window -The `Window` module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. +The **Window** module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. This module provides the following common window-related functions: @@ -44,18 +44,34 @@ Enumerates the window types. | TYPE_DIALOG9+ | 16 | Modal window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| | TYPE_SCREENSHOT9+ | 17 | Screenshot window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +## Configuration9+ + +Defines the parameters used for creating a subwindow. + +An asynchronous callback is used when a system window is created in the case that [ServiceExtensionContext](js-apis-service-extension-context.md) is used as the context. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name| Type| Mandatory| Description| +| ---------- | -------------------------- | -- | ----------------------------------- | +| name | string | Yes| Name of the subwindow. | +| windowType | [WindowType](#windowtype7) | Yes| Type of the subwindow. | +| ctx | BaseContext | No| Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).
If this parameter is not set, no context is used. | +| displayId | number | No| ID of the current physical screen. If this parameter is not set, the default value **-1** is used.| +| parentId | number | No| ID of the parent window. If this parameter is not set, the default value **-1** is used. | + ## AvoidAreaType7+ Enumerates the types of the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Value | Description | -|----------------------------------|-----| ----------------- | -| TYPE_SYSTEM | 0 | Default area of the system.| -| TYPE_CUTOUT | 1 | Notch. | -| TYPE_SYSTEM_GESTURE9+ | 2 | Gesture area. | -| TYPE_KEYBOARD9+ | 3 | Soft keyboard area. | +| Name | Value | Description | +| -------------------------------- | ---- | ------------------------------------------------------------ | +| TYPE_SYSTEM | 0 | Default area of the system. Generally, the status bar, navigation bar, and Dock bar are included. The default area may vary according to the device in use.| +| TYPE_CUTOUT | 1 | Notch. | +| TYPE_SYSTEM_GESTURE9+ | 2 | Gesture area. | +| TYPE_KEYBOARD9+ | 3 | Soft keyboard area. | ## WindowMode7+ @@ -92,14 +108,14 @@ Describes the properties of the status bar and navigation bar. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type| Readable| Writable| Description | -| -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | No | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| isStatusBarLightIcon7+ | boolean | No | Yes | Whether any icon on the status bar is highlighted. | -| statusBarContentColor8+ | string | No | Yes | Color of the text on the status bar. | -| navigationBarColor | string | No | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| isNavigationBarLightIcon7+ | boolean | No | Yes | Whether any icon on the navigation bar is highlighted. | -| navigationBarContentColor8+ | string | No | Yes | Color of the text on the navigation bar. | +| Name | Type| Readable| Writable| Mandatory| Description | +| -------------------------------------- | -------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| statusBarColor | string | No | Yes | No | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.| +| isStatusBarLightIcon7+ | boolean | No | Yes | No | Whether any icon on the status bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.| +| statusBarContentColor8+ | string | No | Yes | No | Color of the text on the status bar. After this property is set, the setting of **isStatusBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.| +| navigationBarColor | string | No | Yes | No | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.| +| isNavigationBarLightIcon7+ | boolean | No | Yes | No | Whether any icon on the navigation bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.| +| navigationBarContentColor8+ | string | No | Yes | No | Color of the text on the navigation bar. After this property is set, the setting of **isNavigationBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.| ## Orientation9+ @@ -147,10 +163,10 @@ Describes the callback for a single system bar. | Name | Type | Readable| Writable| Description | | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| type | [WindowType](#windowtype) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| -| isEnable | boolean | Yes | No | Whether the system bar is displayed. | -| region | [Rect](#rect) | Yes | No | Current position and size of the system bar. | -| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| type | [WindowType](#windowtype7) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| +| isEnable | boolean | Yes | No | Whether the system bar is displayed. The value **true** means that the system bar is displayed, and **false** means the opposite.| +| region | [Rect](#rect7) | Yes | No | Current position and size of the system bar. | +| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| | contentColor | string | Yes | No | Color of the text on the system bar. | ## SystemBarTintState8+ @@ -187,11 +203,11 @@ Describes the area where the window cannot be displayed. | Name | Type | Readable| Writable| Description | | ---------- | ------------- | ---- | ---- | ------------------ | -| visible9+ | boolean | Yes | Yes | Whether the window can be displayed in the area.| -| leftRect | [Rect](#rect) | Yes | Yes | Rectangle on the left of the screen.| -| topRect | [Rect](#rect) | Yes | Yes | Rectangle at the top of the screen.| -| rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| -| bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.| +| visible9+ | boolean | Yes | Yes | Whether the window can be displayed in the area. The value **true** means that the window can be displayed in the area, and **false** means the opposite.| +| leftRect | [Rect](#rect7) | Yes | Yes | Rectangle on the left of the screen.| +| topRect | [Rect](#rect7) | Yes | Yes | Rectangle at the top of the screen.| +| rightRect | [Rect](#rect7) | Yes | Yes | Rectangle on the right of the screen.| +| bottomRect | [Rect](#rect7) | Yes | Yes | Rectangle at the bottom of the screen.| ## Size7+ @@ -212,30 +228,30 @@ Describes the window properties. | Name | Type | Readable| Writable| Description | | ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | -| type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | -| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | -| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | -| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | -| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | -| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| -| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | -| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | -| isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| -| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | -| id9+ | number | Yes | No | Window ID. The default value is `0.0`. | +| windowRect7+ | [Rect](#rect7) | Yes | Yes | Window size. | +| type7+ | [WindowType](#windowtype7) | Yes | Yes | Window type. | +| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is **false**. The value **true** means that the window is displayed in full screen mode, and **false** means the opposite.| +| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is **false**. The value **true** means that the window is immersive, and **false** means the opposite.| +| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is **true**. The value **true** means that the window can gain focus, and **false** means the opposite.| +| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite.| +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. | +| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value **1** indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is **false**. The value **true** means that the screen is always on, and **false** means the opposite.| +| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is **false**. The value **true** means that the window is in privacy mode, and **false** means the opposite.| +| isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is **false**. The value **true** means that the window has rounded corners, and **false** means the opposite.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is **false**. The value **true** means that the window is transparent, and **false** means the opposite.| +| id9+ | number | Yes | No | Window ID. The default value is **0.0**. | ## ColorSpace8+ -Describes the color gamut mode. +Enumerates the color spaces. **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name | Default Value | Description | | ---------- | ------ | -------------- | -| DEFAULT | 0 | Default color gamut mode.| -| WIDE_GAMUT | 1 | Wide color gamut mode. | +| DEFAULT | 0 | Default gamut.| +| WIDE_GAMUT | 1 | Wide-gamut. | ## ScaleOptions9+ @@ -247,10 +263,10 @@ Describes the scale parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | -------------------------------------------------- | -| x | number | No | Yes | Scale factor along the x-axis. The default value is `1.0`. | -| y | number | No | Yes | Scale factor along the y-axis. The default value is `1.0`. | -| pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| -| pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| x | number | No | Yes | Scale factor along the x-axis. The default value is **1.0**. | +| y | number | No | Yes | Scale factor along the y-axis. The default value is **1.0**. | +| pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| +| pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| ## RotateOptions9+ @@ -262,11 +278,11 @@ Describes the rotation parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | -------------------------------------------------- | -| x | number | No | Yes | Rotation angle around the x-axis. The default value is `0.0`. | -| y | number | No | Yes | Rotation angle around the y-axis. The default value is `0.0`. | -| z | number | No | Yes | Rotation angle around the z-xis. The default value is `0.0`. | -| pivotX | number | No | Yes | X coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| -| pivotY | number | No | Yes | Y coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| x | number | No | Yes | Rotation angle around the x-axis. The default value is **0.0**. | +| y | number | No | Yes | Rotation angle around the y-axis. The default value is **0.0**. | +| z | number | No | Yes | Rotation angle around the z-xis. The default value is **0.0**. | +| pivotX | number | No | Yes | X coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| +| pivotY | number | No | Yes | Y coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| ## TranslateOptions9+ @@ -278,179 +294,106 @@ Describes the translation parameters. | Name| Type| Readable| Writable| Description | | ---- | -------- | ---- | ---- | ---------------------------- | -| x | number | No | Yes | Distance to translate along the x-axis. The default value is `0.0`.| -| y | number | No | Yes | Distance to translate along the y-axis. The default value is `0.0`.| -| z | number | No | Yes | Distance to translate along the z-axis. The default value is `0.0`.| +| x | number | No | Yes | Distance to translate along the x-axis. The default value is **0.0**.| +| y | number | No | Yes | Distance to translate along the y-axis. The default value is **0.0**.| +| z | number | No | Yes | Distance to translate along the z-axis. The default value is **0.0**.| -## window.create7+ +## window.createWindow9+ -create(id: string, type: WindowType, callback: AsyncCallback<Window>): void +createWindow(config: Configuration, callback: AsyncCallback<Window>): void Creates a subwindow. This API uses an asynchronous callback to return the result. -**Model restriction**: This API can be used only in the FA model. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------ | -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| - -**Example** - -```js -let windowClass = null; -window.create('first', window.WindowType.TYPE_APP,(err,data) => { - if(err.code){ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); -}); -``` - -## window.create7+ - -create(id: string, type: WindowType): Promise<Window> - -Creates a subwindow. This API uses a promise to return the result. - -**Model restriction**: This API can be used only in the FA model. - **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ---------- | -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type.| - -**Return value** - -| Type | Description | -| -------------------------------- | --------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the subwindow created.| - -**Example** - -```js -let windowClass = null; -let promise = window.create('first', window.WindowType.TYPE_APP); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); -}); -``` - -## window.create8+ - -create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void - -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses an asynchronous callback to return the result. +| Name| Type| Mandatory| Description| +| -------- | -------------------------------------- | -- | --------------------------------- | +| config | [Configuration](#configuration9) | Yes| Current application context. | +| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the subwindow created.| -**System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** -**Parameters** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | +| ID| Error Message| +| ------- | -------------------------------- | +| 1300001 | Repeated operation. | +| 1300006 | This window context is abnormal. | **Example** ```js let windowClass = null; - window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { - if (err.code) { - console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); - windowClass.resetSize(500, 1000); -}); +let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context}; +try { + window.createWindow(config, (err, data) => { + if (err.code) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); + }); +} catch (exception) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.create8+ +## window.createWindow9+ -create(ctx: Context, id: string, type: WindowType): Promise<Window> +createWindow(config: Configuration): Promise<Window> -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. +Creates a subwindow. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | +| Name| Type| Mandatory| Description| +| ------ | -------------------------------- | -- | ------------------ | +| config | [Configuration](#configuration9) | Yes| Current application context.| **Return value** -| Type | Description | -| -------------------------------- | --------------------------------------- | +| Type| Description| +| -------------------------------- | ------------------------------------ | | Promise<[Window](#window)> | Promise used to return the subwindow created.| -**Example** - -```js -let windowClass = null; -let promise = window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); -}); -``` - -## window.find7+ - -find(id: string, callback: AsyncCallback<Window>): void - -Finds a window based on the ID. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** -**Parameters** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------ | -| id | string | Yes | Window ID. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window found.| +| ID| Error Message| +| ------- | -------------------------------- | +| 1300001 | Repeated operation. | +| 1300006 | This window context is abnormal. | **Example** ```js let windowClass = null; - window.find('alertWindow', (err, data) => { - if (err.code) { - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); -}); +let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context}; +try { + let promise = window.createWindow(config); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.find7+ +## window.findWindow9+ -find(id: string): Promise<Window> +findWindow(name: string): Window -Finds a window based on the ID. This API uses a promise to return the result. +Finds a window based on the ID. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -458,118 +401,69 @@ Finds a window based on the ID. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------- | -| id | string | Yes | Window ID.| +| name | string | Yes | Window ID.| **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the window found.| +| Type| Description| +| ----------------- | ------------------- | +| [Window](#window) | Window found.| **Example** ```js -let windowClass = null; -let promise = window.find('alertWindow'); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); -}); +try { + let windowClass = window.findWindow('alertWindow'); +} catch (exception) { + console.error('Failed to find the Window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.getTopWindow +## window.getLastWindow9+ -getTopWindow(callback: AsyncCallback<Window>): void +getLastWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. -**Model restriction**: This API can be used only in the FA model. - **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | -------------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| - -**Example** - -```js -let windowClass = null; -window.getTopWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}); -``` - -## window.getTopWindow - -getTopWindow(): Promise<Window> - -Obtains the top window of the current application. This API uses a promise to return the result. - -**Model restriction**: This API can be used only in the FA model. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Return value** - -| Type | Description | -| -------------------------------- | ----------------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the top window obtained.| - -**Example** - -```js -let windowClass = null; -let promise = window.getTopWindow(); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); -}) -``` +| Name| Type| Mandatory| Description| +| -------- | -------------------------------------- | -- | ---------------------------------------- | +| ctx | BaseContext | Yes| Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the top window obtained.| -## window.getTopWindow8+ +**Error codes** -getTopWindow(ctx: Context, callback: AsyncCallback<Window>): void +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -Obtains the top window of the current application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | +| ID| Error Message| +| ------- | -------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300006 | This window context is abnormal. | **Example** ```js let windowClass = null; -window.getTopWindow(this.context, (err, data) => { - if (err.code) { - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}); +try { + window.getLastWindow(this.context, (err, data) => { + if (err.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.getTopWindow8+ +## window.getLastWindow9+ -getTopWindow(ctx: Context): Promise<Window> +getLastWindow(ctx: BaseContext): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. @@ -577,27 +471,40 @@ Obtains the top window of the current application. This API uses a promise to re **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| +| Name| Type| Mandatory| Description| +| ------ | ----------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| **Return value** -| Type | Description | -| -------------------------------- | ----------------------------------------------- | +| Type| Description| +| -------------------------------- | ------------------------------------------- | | Promise<[Window](#window)> | Promise used to return the top window obtained.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300006 | This window context is abnormal. | + **Example** ```js let windowClass = null; -let promise = window.getTopWindow(this.context); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); -}) +try { + let promise = window.getLastWindow(this.context); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.minimizeAll9+ @@ -616,26 +523,38 @@ Minimizes all windows on a display. This API uses an asynchronous callback to re | id | number | Yes | ID of the [display](js-apis-display.md#display).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js import display from '@ohos.display' import window from '@ohos.window' -let displayClass = null; -display.getDefaultDisplay((err, data) => { - if(err.code) { - return; - } - displayClass = data; - window.minimizeAll(displayClass.id, (err, data) => { +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); + return; +}; + +try { + window.minimizeAll(displayClass.id, (err) => { if(err.code) { console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); return; } console.info('Succeeded in minimizing all windows.'); }); -}); +} catch (exception) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.minimizeAll9+ @@ -659,6 +578,14 @@ Minimizes all windows on a display. This API uses a promise to return the result | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -666,18 +593,23 @@ import display from '@ohos.display' import window from '@ohos.window' let displayClass = null; -display.getDefaultDisplay((err, data) => { - if(err.code) { - return; - } - displayClass = data; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); + return; +}; + +try { let promise = window.minimizeAll(displayClass.id); - promise.then((data)=> { + promise.then(()=> { console.info('Succeeded in minimizing all windows.'); }).catch((err)=>{ console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); - }) -}); + }); +} catch (exception) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.toggleShownStateForAllAppWindows9+ @@ -695,10 +627,18 @@ Hides or restores the application's windows during quick multi-window switching. | -------- | ------------------------- | ---- | -------------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -window.toggleShownStateForAllAppWindows((err, data) => { +window.toggleShownStateForAllAppWindows((err) => { if (err.code) { console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); return; @@ -722,12 +662,20 @@ Hides or restores the application's windows during quick multi-window switching. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let promise = window.toggleShownStateForAllAppWindows(); -promise.then((data)=> { - console.info('Succeeded in toggling shown state for all app windows. Data: ' + JSON.stringify(data)); +promise.then(()=> { + console.info('Succeeded in toggling shown state for all app windows.'); }).catch((err)=>{ console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); }) @@ -749,12 +697,28 @@ Sets the window layout mode. This API uses an asynchronous callback to return th | mode | [WindowLayoutMode](#windowlayoutmode9) | Yes | Window layout mode to set.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Example** +**Error codes** -```js -window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE, (data) => { - console.info('Succeeded in setting window layout mode. Data: ' + JSON.stringify(data)); -}); +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +try { + window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE, (err) => { + if(err.code) { + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window layout mode.'); + }); +} catch (exception) { + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.setWindowLayoutMode9+ @@ -778,18 +742,30 @@ Sets the window layout mode. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -let promise = window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE); -promise.then((data)=> { - console.info('Succeeded in setting window layout mode. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); -}) +try { + let promise = window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE); + promise.then(()=> { + console.info('Succeeded in setting window layout mode.'); + }).catch((err)=>{ + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(exception)); +}; ``` -## on('systemBarTintChange')8+ +## window.on('systemBarTintChange')8+ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): void @@ -803,18 +779,22 @@ Enables listening for properties changes of the status bar and navigation bar. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| type | string | Yes | Event type. The value is fixed at **'systemBarTintChange'**, indicating the property change event of the status bar and navigation bar.| | callback | Callback<[SystemBarTintState](#systembartintstate)> | Yes | Callback used to return the properties of the status bar and navigation bar. | **Example** ```js -window.on('systemBarTintChange', (data) => { - console.info('Succeeded in enabling the listener for systemBarTint changes. Data: ' + JSON.stringify(data)); -}); +try { + window.on('systemBarTintChange', (data) => { + console.info('Succeeded in enabling the listener for systemBarTint changes. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to enable the listener for systemBarTint changes. Cause: ' + JSON.stringify(exception)); +}; ``` -## off('systemBarTintChange')8+ +## window.off('systemBarTintChange')8+ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >): void @@ -828,331 +808,432 @@ Disables listening for properties changes of the status bar and navigation bar. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| type | string | Yes | Event type. The value is fixed at **'systemBarTintChange'**, indicating the property change event of the status bar and navigation bar.| | callback | Callback<[SystemBarTintState](#systembartintstate)> | No | Callback used to return the properties of the status bar and navigation bar. | **Example** ```js -window.off('systemBarTintChange'); +try { + window.off('systemBarTintChange'); +} catch (exception) { + console.error('Failed to disable the listener for systemBarTint changes. Cause: ' + JSON.stringify(exception)); +}; ``` -## Window - -Represents the current window instance, which is the basic unit managed by the window manager. - -In the following API examples, you must use [getTopWindow()](#windowgettopwindow), [create()](#windowcreate7), or [find()](#windowfind7) to obtain a `Window` instance and then call a method in this instance. +## window.create(deprecated) -### hide7+ +create(id: string, type: WindowType, callback: AsyncCallback<Window>): void -hide (callback: AsyncCallback<void>): void +Creates a subwindow. This API uses an asynchronous callback to return the result. -Hides this window. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9) instead. -**System API**: This is a system API. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| **Example** ```js -windowClass.hide((err, data) => { - if (err.code) { - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); +let windowClass = null; +window.create('first', window.WindowType.TYPE_APP,(err,data) => { + if(err.code){ + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); +}); ``` -### hide7+ +## window.create(deprecated) -hide(): Promise<void> +create(id: string, type: WindowType): Promise<Window> -Hides this window. This API uses a promise to return the result. +Creates a subwindow. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9-1) instead. + +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ---------- | +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type.| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** ```js -let promise = windowClass.hide(); +let windowClass = null; +let promise = window.create('first', window.WindowType.TYPE_APP); promise.then((data)=> { - console.info('Succeeded in hiding the window. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); -}) + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); +}); ``` -### hideWithAnimation9+ +## window.create(deprecated) -hideWithAnimation(callback: AsyncCallback<void>): void +create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Hides this window and plays an animation during the process. This API uses an asynchronous callback to return the result. +Creates a subwindow in the FA model -**System API**: This is a system API. +or a system window in the stage model. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).| +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | **Example** ```js -windowClass.hideWithAnimation((err, data) => { +let windowClass = null; +window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { if (err.code) { - console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in hiding the window with animation. data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); +}); ``` -### hideWithAnimation9+ +## window.create(deprecated) -hideWithAnimation(): Promise<void> +create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> -Hides this window and plays an animation during the process. This API uses a promise to return the result. +Creates a subwindow in the FA model -**System API**: This is a system API. +or a system window in the stage model. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).| +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** ```js -let promise = windowClass.hideWithAnimation(); +let windowClass = null; +let promise = window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT); promise.then((data)=> { - console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); -}) + console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); +}); ``` -### show7+ +## window.find(deprecated) -show(callback: AsyncCallback<void>): void +find(id: string, callback: AsyncCallback<Window>): void -Shows this window. This API uses an asynchronous callback to return the result. +Finds a window based on the ID. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| id | string | Yes | Window ID. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window found.| **Example** ```js -windowClass.show((err, data) => { +let windowClass = null; +window.find('alertWindow', (err, data) => { if (err.code) { - console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); +}); ``` -### show7+ +## window.find(deprecated) -show(): Promise<void> +find(id: string): Promise<Window> -Shows this window. This API uses a promise to return the result. +Finds a window based on the ID. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| id | string | Yes | Window ID.| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | ------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the window found.| **Example** ```js -let promise = windowClass.show(); +let windowClass = null; +let promise = window.find('alertWindow'); promise.then((data)=> { - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); -}) + console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); +}); ``` -### showWithAnimation9+ +## window.getTopWindow(deprecated) -showWithAnimation(callback: AsyncCallback<void>): void +getTopWindow(callback: AsyncCallback<Window>): void -Shows this window and plays an animation during the process. This API uses an asynchronous callback to return the result. +Obtains the top window of the current application. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. + +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | -------------------------------------------- | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| **Example** ```js -windowClass.showWithAnimation((err, data) => { +let windowClass = null; +window.getTopWindow((err, data) => { if (err.code) { - console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}); ``` -### showWithAnimation9+ +## window.getTopWindow(deprecated) -showWithAnimation(): Promise<void> +getTopWindow(): Promise<Window> -Shows this window and plays an animation during the process. This API uses a promise to return the result. +Obtains the top window of the current application. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. + +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | ----------------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the top window obtained.| **Example** ```js -let promise = windowClass.showWithAnimation(); +let windowClass = null; +let promise = window.getTopWindow(); promise.then((data)=> { - console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); }) ``` -### destroy7+ +## window.getTopWindow(deprecated) -destroy(callback: AsyncCallback<void>): void +getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void -Destroys this window. This API uses an asynchronous callback to return the result. +Obtains the top window of the current application. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** ```js -windowClass.destroy((err, data) => { +let windowClass = null; +window.getTopWindow(this.context, (err, data) => { if (err.code) { - console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}); ``` -### destroy7+ +## window.getTopWindow(deprecated) -destroy(): Promise<void> +getTopWindow(ctx: BaseContext): Promise<Window> -Destroys this window. This API uses a promise to return the result. +Obtains the top window of the current application. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | ----------------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the top window obtained.| **Example** ```js -let promise = windowClass.destroy(); +let windowClass = null; +let promise = window.getTopWindow(this.context); promise.then((data)=> { - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); }) ``` -### moveTo7+ +## Window -moveTo(x: number, y: number, callback: AsyncCallback<void>): void +Represents the current window instance, which is the basic unit managed by the window manager. -Moves this window. This API uses an asynchronous callback to return the result. +In the following API examples, you must use [getLastWindow()](#windowgetlastwindow9), [createWindow()](#windowcreatewindow9), or [findWindow()](#windowfindwindow9) to obtain a **Window** instance and then call a method in this instance. + +### hide7+ + +hide (callback: AsyncCallback<void>): void + +Hides this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------- | -| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| -| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -windowClass.moveTo(300, 300, (err, data)=>{ +windowClass.hide((err) => { if (err.code) { - console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); - -}); + console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); +}) ``` -### moveTo7+ - -moveTo(x: number, y: number): Promise<void> +### hide7+ -Moves this window. This API uses a promise to return the result. +hide(): Promise<void> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Hides this window. This API uses a promise to return the result. -**Parameters** +**System API**: This is a system API. -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------- | -| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| -| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** @@ -1160,59 +1241,72 @@ Moves this window. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js -let promise = windowClass.moveTo(300, 300); -promise.then((data)=> { - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); +let promise = windowClass.hide(); +promise.then(()=> { + console.info('Succeeded in hiding the window.'); }).catch((err)=>{ - console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); }) ``` -### resetSize7+ +### hideWithAnimation9+ -resetSize(width: number, height: number, callback: AsyncCallback<void>): void +hideWithAnimation(callback: AsyncCallback<void>): void -Changes the size of this window. This API uses an asynchronous callback to return the result. +Hides this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------------- | -| width | number | Yes | New width of the window, in px.| -| height | number | Yes | New height of the window, in px.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | **Example** ```js -windowClass.resetSize(500, 1000, (err, data) => { +windowClass.hideWithAnimation((err) => { if (err.code) { - console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); -}); + console.info('Succeeded in hiding the window with animation.'); +}) ``` -### resetSize7+ - -resetSize(width: number, height: number): Promise<void> +### hideWithAnimation9+ -Changes the size of this window. This API uses a promise to return the result. +hideWithAnimation(): Promise<void> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Hides this window and plays an animation during the process. This API uses a promise to return the result. -**Parameters** +**System API**: This is a system API. -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------- | -| width | number | Yes | New width of the window, in px.| -| height | number | Yes | New height of the window, in px.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** @@ -1220,323 +1314,660 @@ Changes the size of this window. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | + **Example** ```js -let promise = windowClass.resetSize(500, 1000); -promise.then((data)=> { - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); +let promise = windowClass.hideWithAnimation(); +promise.then(()=> { + console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); -}); + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); +}) ``` -### setWindowType(deprecated) - -setWindowType(type: WindowType, callback: AsyncCallback<void>): void - -Sets the type of this window. This API uses an asynchronous callback to return the result. +### showWindow9+ -**System API**: This is a system API. +showWindow(callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Shows this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| type | [WindowType](#windowtype) | Yes | Window type.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -let type = window.WindowType.TYPE_APP; -windowClass.setWindowType(type, (err, data) => { - if (err.code) { - console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); +windowClass.showWindow((err) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window.'); }); ``` -### setWindowType(deprecated) - -setWindowType(type: WindowType): Promise<void> - -Sets the type of this window. This API uses a promise to return the result. +### showWindow9+ -**System API**: This is a system API. +showWindow(): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Shows this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ---------- | -| type | [WindowType](#windowtype) | Yes | Window type.| - **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ----------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js -let type = window.WindowType.TYPE_APP; -let promise = windowClass.setWindowType(type); -promise.then((data)=> { - console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); +let promise = windowClass.showWindow(); +promise.then(()=> { + console.info('Succeeded in showing the window.'); }).catch((err)=>{ - console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); }); ``` -### getProperties +### showWithAnimation9+ -getProperties(callback: AsyncCallback<WindowProperties>): void +showWithAnimation(callback: AsyncCallback<void>): void -Obtains the properties of this window. This API uses an asynchronous callback to return the result. +Shows this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | **Example** ```js -windowClass.getProperties((err, data) => { +windowClass.showWithAnimation((err) => { if (err.code) { - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); -}); + console.info('Succeeded in showing the window with animation.'); +}) ``` -### getProperties +### showWithAnimation9+ + +showWithAnimation(): Promise<void> -getProperties(): Promise<WindowProperties> +Shows this window and plays an animation during the process. This API uses a promise to return the result. -Obtains the properties of this window. This API uses a promise to return the result. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ---------------------------------------------------- | ------------------------------- | -| Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | **Example** ```js -let promise = windowClass.getProperties(); -promise.then((data)=> { - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +let promise = windowClass.showWithAnimation(); +promise.then(()=> { + console.info('Succeeded in showing the window with animation.'); }).catch((err)=>{ - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); -}); + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); +}) ``` -### getAvoidArea7+ +### destroyWindow9+ -getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void +destroyWindow(callback: AsyncCallback<void>): void -Obtains the area where this window cannot be displayed, for example, the system bar area and notch. This API uses an asynchronous callback to return the result. +Destroys this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. `TYPE_SYSTEM_GESTURE` indicates the gesture area. `TYPE_KEYBOARD` indicates the soft keyboard area.| -| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -let type = window.AvoidAreaType.TYPE_SYSTEM; -windowClass.getAvoidArea(type, (err, data) => { +windowClass.destroyWindow((err) => { if (err.code) { - console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); -}); + console.info('Succeeded in destroying the window.'); +}) ``` -### getAvoidArea7+ +### destroyWindow9+ -getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#avoidarea7)> +destroyWindow(): Promise<void> -Obtains the area where this window cannot be displayed, for example, the system bar area and notch. This API uses a promise to return the result. +Destroys this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Parameters** +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| -| Name| Type | Mandatory| Description | -| ------ |----------------------------------| ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. `TYPE_SYSTEM_GESTURE` indicates the gesture area. `TYPE_KEYBOARD` indicates the soft keyboard area.| +**Error codes** -**Return value** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Type | Description | -|-----------------------------------------| ----------------------------------- | -| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area.| +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -let type = window.AvoidAreaType.TYPE_SYSTEM; -let promise = windowClass.getAvoidArea(type); -promise.then((data)=> { - console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +let promise = windowClass.destroyWindow(); +promise.then(()=> { + console.info('Succeeded in destroying the window.'); }).catch((err)=>{ - console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); -}); + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); +}) ``` -### setFullScreen +### moveWindowTo9+ -setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void +moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void -Sets whether to enable the full-screen mode for this window. This API uses an asynchronous callback to return the result. +Moves this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------------------------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------------------------------------------- | +| x | number | Yes| Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| +| y | number | Yes| Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -let isFullScreen = true; -windowClass.setFullScreen(isFullScreen, (err, data) => { - 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)); -}); +try { + windowClass.moveWindowTo(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.'); + }); +} catch (exception) { + console.error('Failed to move the window. Cause:' + JSON.stringify(exception)); +}; ``` -### setFullScreen +### moveWindowTo9+ -setFullScreen(isFullScreen: boolean): Promise<void> +moveWindowTo(x: number, y: number): Promise<void> -Sets whether to enable the full-screen mode for this window. This API uses a promise to return the result. +Moves this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden.| +| Name| Type| Mandatory| Description| +| -- | ----- | -- | --------------------------------------------- | +| x | number | Yes| Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| +| y | number | Yes| Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -let isFullScreen = true; -let promise = windowClass.setFullScreen(isFullScreen); -promise.then((data)=> { - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.moveWindowTo(300, 300); + promise.then(()=> { + console.info('Succeeded in moving the window.'); + }).catch((err)=>{ + console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to move the window. Cause:' + JSON.stringify(exception)); +}; ``` -### setLayoutFullScreen7+ +### resize9+ -setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void +resize(width: number, height: number, callback: AsyncCallback<void>): void -Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result. +Changes the size of this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------------ | ------------------------- | ---- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | ------------------------ | +| width | number | Yes| New width of the window, in px.| +| height | number | Yes| New height of the window, in px.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | -**Example** +**Error codes** -```js -let isLayoutFullScreen= true; -windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { - 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)); -}); -``` +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -### setLayoutFullScreen7+ +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | -setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> +**Example** -Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result. +```js +try { + windowClass.resize(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.'); + }); +} catch (exception) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(exception)); +}; +``` + +### resize9+ + +resize(width: number, height: number): Promise<void> + +Changes the size of this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------------ | ------- | ---- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed.| +| Name| Type| Mandatory| Description| +| ------ | ------ | -- | ------------------------ | +| width | number | Yes| New width of the window, in px.| +| height | number | Yes| New height of the window, in px.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +try { + let promise = windowClass.resize(500, 1000); + promise.then(()=> { + console.info('Succeeded in changing the window size.'); + }).catch((err)=>{ + console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to change the window size. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowMode9+ + +setWindowMode(mode: WindowMode, callback: AsyncCallback<void>): void + +Sets the mode of this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------------------------- | -- | --------- | +| mode | [WindowMode](#windowmode7) | Yes| Window mode to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let mode = window.WindowMode.FULLSCREEN; +try { + windowClass.setWindowMode(mode, (err) => { + if (err.code) { + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window mode.'); + }); +} catch (exception) { + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowMode9+ + +setWindowMode(mode: WindowMode): Promise<void> + +Sets the type of this window. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------------------------- | -- | --------- | +| mode | [WindowMode](#windowmode7) | Yes| Window mode to set.| + +**Return value** + +| Type| Description| +| ------------------- | ----------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let mode = window.WindowMode.FULLSCREEN; +try { + let promise = windowClass.setWindowMode(type); + promise.then(()=> { + console.info('Succeeded in setting the window mode.'); + }).catch((err)=>{ + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(exception)); +}; +``` + +### getWindowProperties9+ + +getWindowProperties(): WindowProperties + +Obtains the properties of this window. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type| Description| +| ------------------------------------- | ------------- | +| [WindowProperties](#windowproperties) | Window properties obtained.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +try { + let properties = windowClass.getWindowProperties(); +} catch (exception) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception)); +}; +``` + +### getWindowAvoidArea9+ + +getWindowAvoidArea(type: AvoidAreaType): AvoidArea + +Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---- |----------------------------------| -- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| + +**Return value** + +| Type| Description| +|--------------------------| ----------------- | +| [AvoidArea](#avoidarea7) | Area where the window cannot be displayed.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let type = window.AvoidAreaType.TYPE_SYSTEM; +try { + let avoidArea = windowClass.getWindowAvoidArea(type); +} catch (exception) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowLayoutFullScreen9+ + +setWindowLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void + +Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------------ | ------------------------- | -- | --------- | +| isLayoutFullScreen | boolean | Yes| Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isLayoutFullScreen= true; +try { + windowClass.setWindowLayoutFullScreen(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.'); + }); +} catch (exception) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowLayoutFullScreen9+ + +setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> + +Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------------ | ------- | -- | ------------------------------------------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes| Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let isLayoutFullScreen = true; -let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); -promise.then((data)=> { - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setWindowLayoutFullScreen(isLayoutFullScreen); + promise.then(()=> { + console.info('Succeeded in setting the window layout to full-screen mode.'); + }).catch((err)=>{ + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception)); +}; ``` -### setSystemBarEnable7+ +### setWindowSystemBarEnable9+ -setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void +setWindowSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void Sets whether to display the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. @@ -1544,28 +1975,41 @@ Sets whether to display the status bar and navigation bar in this window. This A **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to `['status', 'navigation']`. By default, they are not displayed.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------- | +| names | Array | Yes| Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js // In this example, the status bar and navigation bar are not displayed. let names = []; -windowClass.setSystemBarEnable(names, (err, data) => { - if (err.code) { - console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.setWindowSystemBarEnable(names, (err) => { + if (err.code) { + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be invisible.'); + }); +} catch (exception) { + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(exception)); +}; ``` -### setSystemBarEnable7+ +### setWindowSystemBarEnable9+ -setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> +setWindowSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> Sets whether to display the status bar and navigation bar in this window. This API uses a promise to return the result. @@ -1573,32 +2017,45 @@ Sets whether to display the status bar and navigation bar in this window. This A **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------------------------------------------------ | -| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to `['status', 'navigation']`. By default, they are not displayed.| +| Name| Type | Mandatory| Description| +| ----- | ----- | -- | ------------------------------------------------------------------------------------------------------------ | +| names | Array | Yes| Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js // In this example, the status bar and navigation bar are not displayed. let names = []; -let promise = windowClass.setSystemBarEnable(names); -promise.then((data)=> { - console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setWindowSystemBarEnable(names); + promise.then(()=> { + console.info('Succeeded in setting the system bar to be invisible.'); + }).catch((err)=>{ + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(exception)); +}; ``` -### setSystemBarProperties +### setWindowSystemBarProperties9+ -setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void +setWindowSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void Sets the properties of the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. @@ -1611,31 +2068,41 @@ Sets the properties of the status bar and navigation bar in this window. This AP | SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - // The following properties are supported since API version 7. - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, // The following properties are supported since API version 8. statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' }; -windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { - 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)); -}); +try { + windowClass.setWindowSystemBarProperties(SystemBarProperties, (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.'); + }); +} catch (exception) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(exception)); +}; ``` -### setSystemBarProperties +### setWindowSystemBarProperties9+ -setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void> +setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void> Sets the properties of the status bar and navigation bar in this window. This API uses a promise to return the result. @@ -1653,25 +2120,35 @@ Sets the properties of the status bar and navigation bar in this window. This AP | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - // The following properties are supported since API version 7. - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, // The following properties are supported since API version 8. statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' }; -let promise = windowClass.setSystemBarProperties(SystemBarProperties); -promise.then((data)=> { - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setWindowSystemBarProperties(SystemBarProperties); + promise.then(()=> { + console.info('Succeeded in setting the system bar properties.'); + }).catch((err)=>{ + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(exception)); +}; ``` ### setPreferredOrientation9+ @@ -1689,17 +2166,29 @@ Sets the preferred orientation for this window. This API uses an asynchronous ca | Orientation | [Orientation](#orientation9) | Yes | Orientation to set. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js let orientation = window.Orientation.AUTO_ROTATION; -windowClass.setPreferredOrientation(orientation, (err, data) => { - if (err.code) { - console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting window orientation. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.setPreferredOrientation(orientation, (err) => { + if (err.code) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window orientation.'); + }); +} catch (exception) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); +}; ``` ### setPreferredOrientation9+ @@ -1722,21 +2211,33 @@ Sets the preferred orientation for this window. This API uses a promise to retur | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js let orientation = window.Orientation.AUTO_ROTATION; -let promise = windowClass.setPreferredOrientation(orientation); -promise.then((data)=> { - console.info('Succeeded in setting the window orientation. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the window orientation. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setPreferredOrientation(orientation); + promise.then(()=> { + console.info('Succeeded in setting the window orientation.'); + }).catch((err)=>{ + console.error('Failed to set the window orientation. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); +}; ``` -### loadContent7+ +### setUIContent9+ -loadContent(path: string, callback: AsyncCallback<void>): void +setUIContent(path: string, callback: AsyncCallback<void>): void Loads content from a page to this window. This API uses an asynchronous callback to return the result. @@ -1744,26 +2245,39 @@ Loads content from a page to this window. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | -------------------- | +| path | string | Yes| Path of the page from which the content will be loaded.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -windowClass.loadContent('pages/page2/page2', (err, data) => { - 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)); -}); +try { + windowClass.setUIContent('pages/page2/page2', (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); +} catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); +}; ``` -### loadContent7+ +### setUIContent9+ -loadContent(path: string): Promise<void> +setUIContent(path: string): Promise<void> Loads content from a page to this window. This API uses a promise to return the result. @@ -1771,26 +2285,40 @@ Loads content from a page to this window. This API uses a promise to return the **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| +| Name| Type| Mandatory| Description| +| ---- | ------ | -- | ------------------ | +| path | string | Yes| Path of the page from which the content will be loaded.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -let promise = windowClass.loadContent('pages/page2/page2'); -promise.then((data)=> { - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setUIContent('pages/page2/page2'); + promise.then(()=> { + console.info('Succeeded in loading the content.'); + }).catch((err)=>{ + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to load the content. Cause: ' + JSON.stringify(exception)); +}; ``` + ### loadContent9+ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void @@ -1806,27 +2334,35 @@ Loads content from a page associated with a local storage to this window. This A | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```ts -class myAbility extends Ability { - storage : LocalStorage - onWindowStageCreate(windowStage) { - this.storage = new LocalStorage(); - this.storage.setOrCreate('storageSimpleProp',121); - console.log('onWindowStageCreate'); - windowStage.loadContent('pages/page2',this.storage,(err, data) => { - 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)); - }); - } -} +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +console.log('onWindowStageCreate'); +try { + windowClass.loadContent('pages/page2', storage, (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); +} catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); +}; ``` ### loadContent9+ @@ -1844,7 +2380,7 @@ Loads content from a page associated with a local storage to this window. This A | Name | Type | Mandatory| Description | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -1852,75 +2388,64 @@ Loads content from a page associated with a local storage to this window. This A | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| -**Example** - -```ts -class myAbility extends Ability { - storage : LocalStorage - onWindowStageCreate(windowStage) { - this.storage = new LocalStorage(); - this.storage.setOrCreate('storageSimpleProp',121); - console.log('onWindowStageCreate'); - let windowClass = null; - let promise = windowStage.loadContent('pages/page2',this.storage); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - }) - } -} -``` -### isShowing7+ - -isShowing(callback: AsyncCallback<boolean>): void - -Checks whether this window is displayed. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** -**Parameters** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** -```js -windowClass.isShowing((err, data) => { - if (err.code) { - console.error('Failed to check whether the window is showing. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); -}); +```ts +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +console.log('onWindowStageCreate'); +try { + let promise = windowClass.loadContent('pages/page2', storage); + promise.then(() => { + console.info('Succeeded in loading the content.'); + }).catch((err) => { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); +}; ``` -### isShowing7+ +### isWindowShowing9+ -isShowing(): Promise<boolean> +isWindowShowing(): boolean -Checks whether this window is displayed. This API uses a promise to return the result. +Checks whether this window is displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| +| Type| Description| +| ------- | ------------------------------------------------------------------ | +| boolean | Whether the window is displayed. The value **true** means that the window is displayed, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -let promise = windowClass.isShowing(); -promise.then((data)=> { +try { + let data = windowClass.isWindowShowing(); console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err)); -}); +} catch (exception) { + console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('windowSizeChange')7+ @@ -1935,20 +2460,24 @@ Enables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------ | ---- | -------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| | callback | Callback<[Size](#size7)> | Yes | Callback used to return the window size. | **Example** ```js -windowClass.on('windowSizeChange', (data) => { - console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.on('windowSizeChange', (data) => { + console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to enable the listener for window size changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('windowSizeChange')7+ -off(type: 'windowSizeChange', callback?: Callback<Size >): void +off(type: 'windowSizeChange', callback?: Callback<Size>): void Disables listening for window size changes. @@ -1958,69 +2487,22 @@ Disables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | -------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| | callback | Callback<[Size](#size)> | No | Callback used to return the window size. | **Example** ```js -windowClass.off('windowSizeChange'); -``` - -### on('systemAvoidAreaChange')(deprecated) - -on(type: 'systemAvoidAreaChange', callback: Callback<[AvoidArea](#avoidarea7)>): void - -Enables listening for changes to the area where the window cannot be displayed. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- |------------------------------------------| ---- | ------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | - -**Example** - -```js -windowClass.on('systemAvoidAreaChange', (data) => { - console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data)); -}); -``` - -### off('systemAvoidAreaChange')(deprecated) - -off(type: 'systemAvoidAreaChange', callback?: Callback<[AvoidArea](#avoidarea7)>): void - -Disables listening for changes to the area where the window cannot be displayed. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- |------------------------------------------| ---- | ------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | - -**Example** - -```js -windowClass.off('systemAvoidAreaChange'); +try { + windowClass.off('windowSizeChange'); +} catch (exception) { + console.error('Failed to disable the listener for window size changes. Cause: ' + JSON.stringify(exception)); +}; ``` - ### on('avoidAreaChange')9+ -on(type: 'avoidAreaChange', callback: Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}>): void +on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void Enables listening for changes to the area where the window cannot be displayed. @@ -2030,20 +2512,25 @@ Enables listening for changes to the area where the window cannot be displayed. | Name | Type | Mandatory| Description | | -------- |------------------------------------------------------------------| ---- |--------------------------------------| -| type | string | Yes | Event type. The value is fixed at `avoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| | callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | Yes | Callback used to return the area and area type.| **Example** ```js -windowClass.on('avoidAreaChange', (data) => { - console.info('Succeeded in enabling the listener for system avoid area changes. type:' + JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area)); -}); +try { + windowClass.on('avoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. type:' + + JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area)); + }); +} catch (exception) { + console.error('Failed to enable the listener for system avoid area changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback: Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}>): void +off(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void Disables listening for changes to the area where the window cannot be displayed. @@ -2053,13 +2540,17 @@ Disables listening for changes to the area where the window cannot be displayed. | Name | Type | Mandatory | Description | | -------- |-----------------------------------------------------------------------------|-----|------------------------------------| -| type | string | Yes | Event type. The value is fixed at `avoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| | callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type.| **Example** ```js -windowClass.off('avoidAreaChange'); +try { + windowClass.off('avoidAreaChange'); +} catch (exception) { + console.error('Failed to disable the listener for system avoid area changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('keyboardHeightChange')7+ @@ -2074,15 +2565,19 @@ Enables listening for keyboard height changes. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| -| callback | Callback { - console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.on('keyboardHeightChange', (data) => { + console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('keyboardHeightChange')7+ @@ -2097,13 +2592,17 @@ Disables listening for keyboard height changes. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| +| type | string | Yes | Event type. The value is fixed at **'keyboardHeightChange'**, indicating the keyboard height change event.| | callback | Callback<number> | No | Callback used to return the current keyboard height. | **Example** ```js -windowClass.off('keyboardHeightChange'); +try { + windowClass.off('keyboardHeightChange'); +} catch (exception) { + console.error('Failed to disable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('touchOutside')9+ @@ -2120,15 +2619,19 @@ Enables listening for click events outside this window. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `touchOutside`, indicating the click event outside this window.| -| callback | Callback { - console.info('touch outside'); -}); +try { + windowClass.on('touchOutside', () => { + console.info('touch outside'); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('touchOutside')9+ @@ -2145,13 +2648,17 @@ Disables listening for click events outside this window. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `touchOutside`, indicating the click event outside this window.| -| callback | Callback<number> | No | Callback used to Callback used to return the click event outside this window. | +| type | string | Yes | Event type. The value is fixed at **'touchOutside'**, indicating the click event outside this window.| +| callback | Callback<number> | No | Callback used to return the click event outside this window. | **Example** ```js -windowClass.off('touchOutside'); +try { + windowClass.off('touchOutside'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('screenshot')9+ @@ -2166,15 +2673,19 @@ Subscribes to screenshot events. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `screenshot`, indicating the screenshot event.| +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| | callback | Callback<void> | Yes | Callback invoked when a screenshot event occurs. | **Example** ```js -windowClass.on('screenshot', () => { - console.info('screenshot happened'); -}); +try { + windowClass.on('screenshot', () => { + console.info('screenshot happened'); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('screenshot')9+ @@ -2189,7 +2700,7 @@ Unsubscribes from screenshot events. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `screenshot`, indicating the screenshot event.| +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| | callback | Callback<void> | No | Callback invoked when a screenshot event occurs.| **Example** @@ -2197,12 +2708,19 @@ Unsubscribes from screenshot events. ```js let callback = ()=>{ console.info('screenshot happened'); -} -windowClass.on('screenshot', callback) -windowClass.off('screenshot', callback) - -// If multiple callbacks are enabled in on(), they will all be disabled. -windowClass.off('screenshot'); +}; +try { + windowClass.on('screenshot', callback); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; +try { + windowClass.off('screenshot', callback); + // If multiple callbacks are enabled in on(), they will all be disabled. + windowClass.off('screenshot'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('dialogTargetTouch')9+ @@ -2217,15 +2735,19 @@ Subscribes to click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `dialogTargetTouch`, indicating the click event of the target window in the modal window mode.| +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| | callback | Callback<void>| Yes | Callback invoked when the click event occurs in the target window of the modal window mode.| **Example** ```js -windowClass.on('dialogTargetTouch', () => { - console.info('touch dialog target'); -}); +try { + windowClass.on('dialogTargetTouch', () => { + console.info('touch dialog target'); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('dialogTargetTouch')9+ @@ -2240,13 +2762,17 @@ Unsubscribes from click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `dialogTargetTouch`, indicating the click event of the target window in the modal window mode.| +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| | callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode.| **Example** ```js -windowClass.off('dialogTargetTouch'); +try { + windowClass.off('dialogTargetTouch'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### bindDialogTarget9+ @@ -2267,6 +2793,15 @@ Binds the modal window to the target window, and adds a callback to listen for m | deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -2290,15 +2825,19 @@ class TestRemoteObject extends rpc.RemoteObject { } } let token = new TestRemoteObject('testObject'); -windowClass.bindDialogTarget(token, () => { - console.info('Dialog Window Need Destroy.'); -}, (err, data) => { - if (err.code) { - console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); -}); +try { + windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); + }, (err) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target.'); + }); +} catch (exception) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(exception)); +}; ``` ### bindDialogTarget9+ @@ -2324,6 +2863,15 @@ Binds the modal window to the target window, and adds a callback to listen for m | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -2347,1108 +2895,2950 @@ class TestRemoteObject extends rpc.RemoteObject { } } let token = new TestRemoteObject('testObject'); -let promise = windowClass.bindDialogTarget(token, () => { - console.info('Dialog Window Need Destroy.'); +try { + let promise = windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); + }); + promise.then(()=> { + console.info('Succeeded in binding dialog target.'); + }).catch((err)=>{ + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(exception)); +}; +``` + +### isWindowSupportWideGamut9+ + +isWindowSupportWideGamut(callback: AsyncCallback<boolean>): void + +Checks whether this window supports the wide-gamut color space. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ---------------------------- | -- | -------------------------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +windowClass.isWindowSupportWideGamut((err, data) => { + if (err.code) { + console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); }); +``` + +### isWindowSupportWideGamut9+ + +isWindowSupportWideGamut(): Promise<boolean> + +Checks whether this window supports the wide-gamut color space. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type| Description| +| ---------------------- | ------------------------------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let promise = windowClass.isWindowSupportWideGamut(); promise.then((data)=> { - console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); + console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); }); ``` -### isSupportWideGamut8+ +### setWindowColorSpace9+ -isSupportWideGamut(callback: AsyncCallback<boolean>): void +setWindowColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void -Checks whether this window supports the wide color gamut mode. This API uses an asynchronous callback to return the result. +Sets a color space for this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the wide color gamut mode is supported, and `false` means the opposite.| +| Name| Type| Mandatory| Description| +| ---------- | ------------------------- | -- | ----------- | +| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -windowClass.isSupportWideGamut((err, data) => { +try { + windowClass.setWindowColorSpace(window.ColorSpace.WIDE_GAMUT, (err) => { + if (err.code) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window colorspace.'); + }); +} catch (exception) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowColorSpace9+ + +setWindowColorSpace(colorSpace:ColorSpace): Promise<void> + +Sets a color space for this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | ------------------------- | -- | ------------- | +| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +try { + let promise = windowClass.setWindowColorSpace(window.ColorSpace.WIDE_GAMUT); + promise.then(()=> { + console.info('Succeeded in setting window colorspace.'); + }).catch((err)=>{ + console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(exception)); +}; +``` + +### getWindowColorSpace9+ + +getWindowColorSpace(): ColorSpace + +Obtains the color space of this window. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type| Description| +| ------------------------- | ------------- | +| [ColorSpace](#colorspace) | Color space obtained.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let colorSpace = windowClass.getWindowColorSpace(); +``` + +### setWindowBackgroundColor9+ + +setWindowBackgroundColor(color: string): void + +Sets the background color for this window. In the stage model, this API must be used after [loadContent](#loadcontent9). + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----- | ------ | -- | ----------------------------------------------------------------------- | +| color | string | Yes| Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let color = '#00ff33'; +try { + windowClass.setWindowBackgroundColor(color); +} catch (exception) { + console.error('Failed to set the background color. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowBrightness9+ + +setWindowBrightness(brightness: number, callback: AsyncCallback<void>): void + +Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | ------------------------- | -- | --------------------------------- | +| brightness | number | Yes| Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let brightness = 1; +try { + windowClass.setWindowBrightness(brightness, (err) => { + if (err.code) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the brightness.'); + }); +} catch (exception) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowBrightness9+ + +setWindowBrightness(brightness: number): Promise<void> + +Sets the screen brightness for this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | ------ | -- | --------------------------------- | +| brightness | number | Yes| Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let brightness = 1; +try { + let promise = windowClass.setWindowBrightness(brightness); + promise.then(()=> { + console.info('Succeeded in setting the brightness.'); + }).catch((err)=>{ + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowFocusable9+ + +setWindowFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void + +Sets whether this window can gain focus. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------------------------- | -- | ------------------------------------------------------- | +| isFocusable | boolean | Yes| Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isFocusable= true; +try { + windowClass.setWindowFocusable(isFocusable, (err) => { + if (err.code) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable.'); + }); +} catch (exception) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowFocusable9+ + +setWindowFocusable(isFocusable: boolean): Promise<void> + +Sets whether this window can gain focus. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------- | -- | -------------------------------------------------------- | +| isFocusable | boolean | Yes| Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isFocusable= true; +try { + let promise = windowClass.setWindowFocusable(isFocusable); + promise.then(()=> { + console.info('Succeeded in setting the window to be focusable.'); + }).catch((err)=>{ + console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowKeepScreenOn9+ + +setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void + +Sets whether to keep the screen always on. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------------- | ------------------------- | -- | ---------------------------------------------------- | +| isKeepScreenOn | boolean | Yes| Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isKeepScreenOn = true; +try { + windowClass.setWindowKeepScreenOn(isKeepScreenOn, (err) => { + if (err.code) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on.'); + }); +} catch (exception) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowKeepScreenOn9+ + +setWindowKeepScreenOn(isKeepScreenOn: boolean): Promise<void> + +Sets whether to keep the screen always on. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------------- | ------- | -- | --------------------------------------------------- | +| isKeepScreenOn | boolean | Yes| Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isKeepScreenOn = true; +try { + let promise = windowClass.setWindowKeepScreenOn(isKeepScreenOn); + promise.then(() => { + console.info('Succeeded in setting the screen to be always on.'); + }).catch((err)=>{ + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWakeUpScreen()9+ + +setWakeUpScreen(wakeUp: boolean): void + +Wakes up the screen. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ------- | ---- | ---------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let wakeUp = true; +try { + windowClass.setWakeUpScreen(wakeUp); +} catch (exception) { + console.error('Failed to wake up the screen. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowPrivacyMode9+ + +setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Required permissions**: ohos.permission.PRIVACY_WINDOW + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------- | ------------------------- | -- | ------------------------------------------------------ | +| isPrivacyMode | boolean | Yes| Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let isPrivacyMode = true; +try { + windowClass.setWindowPrivacyMode(isPrivacyMode, (err) => { + if (err.code) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode.'); + }); +} catch (exception) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowPrivacyMode9+ + +setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void> + +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Required permissions**: ohos.permission.PRIVACY_WINDOW + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------- | ------- | -- | ----------------------------------------------------- | +| isPrivacyMode | boolean | Yes| Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let isPrivacyMode = true; +try { + let promise = windowClass.setWindowPrivacyMode(isPrivacyMode); + promise.then(()=> { + console.info('Succeeded in setting the window to privacy mode.'); + }).catch((err)=>{ + console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setSnapshotSkip9+ +setSnapshotSkip(isSkip: boolean): void + +Sets whether to ignore this window during screen capturing or recording. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------- | ---- | -------------------- | +| isSkip | boolean | Yes | Whether to ignore the window. The default value is **false**.
The value **true** means that the window is ignored, and **false** means the opposite.
| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +```js +let isSkip = true; +try { + windowClass.setSnapshotSkip(isSkip); +} catch (exception) { + console.error('Failed to Skip. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowTouchable9+ + +setWindowTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is touchable. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------------------------- | -- | ----------------------------------------------- | +| isTouchable | boolean | Yes| Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isTouchable = true; +try { + windowClass.setWindowTouchable(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.'); + }); +} catch (exception) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowTouchable9+ + +setWindowTouchable(isTouchable: boolean): Promise<void> + +Sets whether this window is touchable. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------- | -- | ----------------------------------------------- | +| isTouchable | boolean | Yes| Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isTouchable = true; +try { + let promise = windowClass.setWindowTouchable(isTouchable); + promise.then(()=> { + console.info('Succeeded in setting the window to be touchable.'); + }).catch((err)=>{ + console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setForbidSplitMove9+ + +setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is forbidden to move in split-screen mode. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode. The value **true** means the window is forbidden to move in split-screen mode, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isForbidSplitMove = true; +try { + windowClass.setForbidSplitMove(isForbidSplitMove, (err) => { + if (err.code) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in forbidding window moving in split screen mode.'); + }); +} catch (exception) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setForbidSplitMove9+ + +setForbidSplitMove(isForbidSplitMove: boolean): Promise<void> + +Sets whether this window is forbidden to move in split-screen mode. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode. The value **true** means the window is forbidden to move in split-screen mode, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isForbidSplitMove = true; +try { + let promise = windowClass.setForbidSplitMove(isForbidSplitMove); + promise.then(()=> { + console.info('Succeeded in forbidding window moving in split screen mode.'); + }).catch((err)=>{ + console.error('Failed to forbid window moving in split screen mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### snapshot9+ + +snapshot(callback: AsyncCallback<image.PixelMap>): void + +Captures this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ----------------------------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +windowClass.snapshot((err, pixelMap) => { + if (err.code) { + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}); +``` + +### snapshot9+ + +snapshot(): Promise<image.PixelMap> + +Captures this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | --------------------------------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let promise = windowClass.snapshot(); +promise.then((pixelMap)=> { + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}).catch((err)=>{ + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); +}); +``` + +### opacity9+ + +opacity(opacity: number): void + +Sets the opacity for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | --------- | ------------------------------------------------- | +| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.opacity(0.5); +} catch (exception) { + console.error('Failed to opacity. Cause: ' + JSON.stringify(exception)); +}; +``` + +### scale9+ + +scale(scaleOptions: ScaleOptions): void + +Sets the scale parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------------------------------ | --------- | ------------------------ | +| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let obj : window.ScaleOptions = { + x : 2.0, + y : 1.0, + pivotX : 0.5, + pivotY : 0.5 +}; +try { + windowClass.scale(obj); +} catch (exception) { + console.error('Failed to scale. Cause: ' + JSON.stringify(exception)); +}; +``` + +### rotate9+ + +rotate(rotateOptions: RotateOptions): void + +Sets the rotation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------- | -------------------------------- | --------- | --------------------------- | +| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let obj : window.RotateOptions = { + x : 1.0, + y : 1.0, + z : 45.0, + pivotX : 0.5, + pivotY : 0.5 +}; +try { + windowClass.rotate(obj); +} catch (exception) { + console.error('Failed to rotate. Cause: ' + JSON.stringify(exception)); +}; +``` + +### translate9+ + +translate(translateOptions: TranslateOptions): void + +Sets the translation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | -------------------------------------- | --------- | ------------------------------ | +| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 +}; +try { + windowClass.translate(obj); +} catch (exception) { + console.error('Failed to translate. Cause: ' + JSON.stringify(exception)); +}; +``` + +### getTransitionController9+ + + getTransitionController(): TransitionController + +Obtains the transition animation controller. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | -------------------------------- | +| [TransitionController](#transitioncontroller9) | Transition animation controller. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let controller = windowClass.getTransitionController(); // Obtain the transition animation controller. +controller.animationForHidden = (context : window.TransitionContext) => { + let toWindow = context.toWindow; + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation playback mode. + onFinish: ()=> { + context.completeTransition(true) + } + }, () => { + let obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 + }; + toWindow.translate(obj); // Set the transition animation. + console.info('toWindow translate end'); + } + ) + console.info('complete transition end'); +} +windowClass.hideWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}) +``` + +### setBlur9+ + +setBlur(radius: number): void + +Blurs this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setBlur(4.0); +} catch (exception) { + console.error('Failed to set blur. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setBackdropBlur9+ + +setBackdropBlur(radius: number): void + +Blurs the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the background of the window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setBackdropBlur(4.0); +} catch (exception) { + console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setBackdropBlurStyle9+ + +setBackdropBlurStyle(blurStyle: BlurStyle): void + +Sets the blur style for the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------ | --------- | --------------------------------------------------- | +| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setBackdropBlurStyle(window.BlurStyle.THIN); +} catch (exception) { + console.error('Failed to set backdrop blur style. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setShadow9+ + +setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void + +Sets the shadow for the window borders. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value **0** means that the shadow is disabled for the window borders. | +| color | string | No | Color of the shadow. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | +| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +} catch (exception) { + console.error('Failed to set shadow. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setCornerRadius9+ + +setCornerRadius(cornerRadius: number): void + +Sets the radius of the rounded corners for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value **0** means that the window does not use rounded corners. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setCornerRadius(4.0); +} catch (exception) { + console.error('Failed to set corner radius. Cause: ' + JSON.stringify(exception)); +}; +``` + +### show(deprecated) + +show(callback: AsyncCallback<void>): void + +Shows this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [showWindow()](#showwindow9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +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.'); +}) +``` + +### show(deprecated) + +show(): Promise<void> + +Shows this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [showWindow()](#showwindow9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.show(); +promise.then(()=> { + console.info('Succeeded in showing the window.'); +}).catch((err)=>{ + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); +}) +``` + +### destroy(deprecated) + +destroy(callback: AsyncCallback<void>): void + +Destroys this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [destroyWindow()](#destroywindow9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +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.'); +}) +``` + +### destroy(deprecated) + +destroy(): Promise<void> + +Destroys this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [destroyWindow()](#destroywindow9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.destroy(); +promise.then(()=> { + console.info('Succeeded in destroying the window.'); +}).catch((err)=>{ + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); +}) +``` + +### moveTo(deprecated) + +moveTo(x: number, y: number, callback: AsyncCallback<void>): void + +Moves this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right. | +| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +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.'); + +}); +``` + +### moveTo(deprecated) + +moveTo(x: number, y: number): Promise<void> + +Moves this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------------------------------ | +| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right. | +| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.moveTo(300, 300); +promise.then(()=> { + console.info('Succeeded in moving the window.'); +}).catch((err)=>{ + console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); +}) +``` + +### resetSize(deprecated) + +resetSize(width: number, height: number, callback: AsyncCallback<void>): void + +Changes the size of this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| width | number | Yes | New width of the window, in px. | +| height | number | Yes | New height of the window, in px. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +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.'); +}); +``` + +### resetSize(deprecated) + +resetSize(width: number, height: number): Promise<void> + +Changes the size of this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | -------------------------------- | +| width | number | Yes | New width of the window, in px. | +| height | number | Yes | New height of the window, in px. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.resetSize(500, 1000); +promise.then(()=> { + console.info('Succeeded in changing the window size.'); +}).catch((err)=>{ + console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); +}); + +``` + +### setWindowType(deprecated) + +setWindowType(type: WindowType, callback: AsyncCallback<void>): void + +Sets the type of this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------- | --------- | ----------------------------------- | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let type = window.WindowType.TYPE_APP; +windowClass.setWindowType(type, (err) => { + if (err.code) { + console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window type.'); +}); +``` + +### setWindowType(deprecated) + +setWindowType(type: WindowType): Promise<void> + +Sets the type of this window. This API uses a promise to return the result. + +**System API**: This is a system API. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------- | --------- | ------------ | +| type | [WindowType](#windowtype7) | Yes | Window type. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let type = window.WindowType.TYPE_APP; +let promise = windowClass.setWindowType(type); +promise.then(()=> { + console.info('Succeeded in setting the window type.'); +}).catch((err)=>{ + console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); +}); +``` + +### getProperties(deprecated) + +getProperties(callback: AsyncCallback<WindowProperties>): void + +Obtains the properties of this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getWindowProperties()](#getwindowproperties9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties. | + +**Example** + +```js +windowClass.getProperties((err, data) => { + if (err.code) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +}); + +``` + +### getProperties(deprecated) + +getProperties(): Promise<WindowProperties> + +Obtains the properties of this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getWindowProperties()](#getwindowproperties9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------------- | +| Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties. | + +**Example** + +```js +let promise = windowClass.getProperties(); +promise.then((data)=> { + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); +}); + +``` + +### getAvoidArea(deprecated) + +getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void + +Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [[getWindowAvoidArea()](#getwindowavoidarea9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. | +| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | + +**Example** + +```js +let type = window.AvoidAreaType.TYPE_SYSTEM; +windowClass.getAvoidArea(type, (err, data) => { + if (err.code) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +}); +``` + +### getAvoidArea(deprecated) + +getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#avoidarea7)> + +Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getWindowProperties()](#getwindowavoidarea9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. | + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------------- | +| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area. | + +**Example** + +```js +let type = window.AvoidAreaType.TYPE_SYSTEM; +let promise = windowClass.getAvoidArea(type); +promise.then((data)=> { + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); +}); +``` + +### setFullScreen(deprecated) + +setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void + +Sets whether to enable the full-screen mode for this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarEnable()](#setwindowsystembarenable9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------------------------- | --------- | ------------------------------------------------------------ | +| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let isFullScreen = true; +windowClass.setFullScreen(isFullScreen, (err) => { if (err.code) { - console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); -}) + console.info('Succeeded in enabling the full-screen mode.'); +}); ``` -### isSupportWideGamut8+ +### setFullScreen(deprecated) -isSupportWideGamut(): Promise<boolean> +setFullScreen(isFullScreen: boolean): Promise<void> -Checks whether this window supports the wide color gamut mode. This API uses a promise to return the result. +Sets whether to enable the full-screen mode for this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarEnable()](#setwindowsystembarenable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------- | --------- | ------------------------------------------------------------ | +| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite. | + **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value `true` means that the wide color gamut mode is supported, and `false` means the opposite.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.isSupportWideGamut(); -promise.then((data)=> { - console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); +let isFullScreen = true; +let promise = windowClass.setFullScreen(isFullScreen); +promise.then(()=> { + console.info('Succeeded in enabling the full-screen mode.'); }).catch((err)=>{ - console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); }); + ``` -### setColorSpace8+ +### setLayoutFullScreen(deprecated) -setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void +setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void + +Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result. -Sets this window to the wide or default color gamut mode. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowLayoutFullScreen()](#setwindowlayoutfullscreen9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------ | -| colorSpace | [ColorSpace](#colorspace) | Yes | Color gamut mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------------------ | ------------------------- | --------- | ------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err, data) => { +let isLayoutFullScreen= true; +windowClass.setLayoutFullScreen(isLayoutFullScreen, (err) => { if (err.code) { - console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); -}) + console.info('Succeeded in setting the window layout to full-screen mode.'); +}); + ``` -### setColorSpace8+ +### setLayoutFullScreen(deprecated) -setColorSpace(colorSpace:ColorSpace): Promise<void> +setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> + +Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result. -Sets this window to the wide or default color gamut mode. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowLayoutFullScreen()](#setwindowlayoutfullscreen9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | -------------- | -| colorSpace | [ColorSpace](#colorspace) | Yes | Color gamut mode.| +| Name | Type | Mandatory | Description | +| ------------------ | ------- | --------- | ------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT); -promise.then((data)=> { - console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); +let isLayoutFullScreen = true; +let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); +promise.then(()=> { + console.info('Succeeded in setting the window layout to full-screen mode.'); }).catch((err)=>{ - console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); }); ``` -### getColorSpace8+ +### setSystemBarEnable(deprecated) -getColorSpace(callback: AsyncCallback<ColorSpace>): void +setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void + +Sets whether to display the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. -Obtains the color gamut mode of this window. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowSystemBarEnable()](#setwindowsystembarenable9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------- | ---- | ---------------------------------------------------------- | -| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the result. When the color gamut mode is obtained successfully, `err` is `undefined`, and `data` is the current color gamut mode.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.getColorSpace((err, data) => { +// In this example, the status bar and navigation bar are not displayed. +let names = []; +windowClass.setSystemBarEnable(names, (err) => { if (err.code) { - console.error('Failed to get window colorspace. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)); -}) + console.info('Succeeded in setting the system bar to be invisible.'); +}); + ``` -### getColorSpace8+ +### setSystemBarEnable(deprecated) -getColorSpace(): Promise<ColorSpace> +setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> -Obtains the color gamut mode of this window. This API uses a promise to return the result. +Sets whether to display the status bar and navigation bar in this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowSystemBarEnable()](#setwindowsystembarenable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----- | --------- | ------------------------------------------------------------ | +| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed. | + **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------------- | -| Promise<[ColorSpace](#colorspace)> | Promise used to return the current color gamut mode.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.getColorSpace(); -promise.then((data)=> { - console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data)); +// In this example, the status bar and navigation bar are not displayed. +let names = []; +let promise = windowClass.setSystemBarEnable(names); +promise.then(()=> { + console.info('Succeeded in setting the system bar to be invisible.'); }).catch((err)=>{ - console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); }); + ``` -### setBackgroundColor +### setSystemBarProperties(deprecated) -setBackgroundColor(color: string, callback: AsyncCallback<void>): void +setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void + +Sets the properties of the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. -Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9). +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarProperties()](#setwindowsystembarproperties9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------------------- | ------------------------------------------- | --------- | ------------------------------------------------ | +| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let color = '#00ff33'; -windowClass.setBackgroundColor(color, (err, data) => { +let SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 8. + statusBarContentColor:'#ffffff', + navigationBarContentColor:'#00ffff' +}; +windowClass.setSystemBarProperties(SystemBarProperties, (err) => { if (err.code) { - console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar properties.'); }); ``` -### setBackgroundColor +### setSystemBarProperties(deprecated) -setBackgroundColor(color: string): Promise<void> +setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void> + +Sets the properties of the status bar and navigation bar in this window. This API uses a promise to return the result. -Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9). +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarProperties()](#setwindowsystembarproperties9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| Name | Type | Mandatory | Description | +| ------------------- | ------------------------------------------- | --------- | ------------------------------------------------ | +| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let color = '#00ff33'; -let promise = windowClass.setBackgroundColor(color); -promise.then((data)=> { - console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); +let SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 8. + statusBarContentColor:'#ffffff', + navigationBarContentColor:'#00ffff' +}; +let promise = windowClass.setSystemBarProperties(SystemBarProperties); +promise.then(()=> { + console.info('Succeeded in setting the system bar properties.'); }).catch((err)=>{ - console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); }); -``` - -### setWakeUpScreen()9+ - -setWakeUpScreen(wakeUp: boolean): void; - -Wakes up the screen. -**System API**: This is a system API. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------------- | ------- | ---- | ---------------------------- | -| wakeUp | boolean | Yes | Whether to wake up the screen.| - -**Example** - -```js -let wakeUp = true; -windowClass.setWakeUpScreen(wakeUp); ``` -### setBrightness +### loadContent(deprecated) -setBrightness(brightness: number, callback: AsyncCallback<void>): void +loadContent(path: string, callback: AsyncCallback<void>): void -Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +Loads content from a page to this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setUIContent()](#setuicontent9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------- | +| path | string | Yes | Path of the page from which the content will be loaded. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let brightness = 1; -windowClass.setBrightness(brightness, (err, data) => { - if (err.code) { - console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); +windowClass.loadContent('pages/page2/page2', (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); }); + ``` -### setBrightness +### loadContent(deprecated) -setBrightness(brightness: number): Promise<void> +loadContent(path: string): Promise<void> -Sets the screen brightness for this window. This API uses a promise to return the result. +Loads content from a page to this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setUIContent()](#setuicontent9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------------------------- | +| path | string | Yes | Path of the page from which the content will be loaded. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let brightness = 1; -let promise = windowClass.setBrightness(brightness); -promise.then((data)=> { - console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); +let promise = windowClass.loadContent('pages/page2/page2'); +promise.then(()=> { + console.info('Succeeded in loading the content.'); }).catch((err)=>{ - console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); }); + ``` -### setDimBehind(deprecated) +### isShowing(deprecated) -setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void +isShowing(callback: AsyncCallback<boolean>): void -Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. +Checks whether this window is displayed. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isWindowShowing()](#iswindowshowing9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | -------------------------------------------------- | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value `1` indicates the dimmest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the window is displayed, and **false** means the opposite. | **Example** ```js -windowClass.setDimBehind(0.5, (err, data) => { +windowClass.isShowing((err, data) => { if (err.code) { - console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window is showing. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the dimness. Data:' + JSON.stringify(data)); + console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); }); ``` -### setDimBehind(deprecated) +### isShowing(deprecated) -setDimBehind(dimBehindValue: number): Promise<void> +isShowing(): Promise<boolean> -Sets the dimness of the window that is not on top. This API uses a promise to return the result. +Checks whether this window is displayed. This API uses a promise to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isWindowShowing()](#iswindowshowing9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | -------------------------------------------------- | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value `1` indicates the dimmest.| - **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the window is displayed, and **false** means the opposite. | **Example** ```js -let promise = windowClass.setDimBehind(0.5); +let promise = windowClass.isShowing(); promise.then((data)=> { - console.info('Succeeded in setting the dimness. Data: ' + JSON.stringify(data)); + console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err)); }); ``` -### setFocusable7+ +### on('systemAvoidAreaChange')(deprecated) + +on(type: 'systemAvoidAreaChange', callback: Callback<AvoidArea>): void -setFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void +Enables listening for changes to the area where the window cannot be displayed. -Sets whether this window can gain focus. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | ---------------------------- | -| isFocusable | boolean | Yes | Whether the window can gain focus.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed. | +| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** ```js -let isFocusable= true; -windowClass.setFocusable(isFocusable, (err, data) => { - if (err.code) { - console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); +windowClass.on('systemAvoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data)); }); ``` -### setFocusable7+ +### off('systemAvoidAreaChange')(deprecated) -setFocusable(isFocusable: boolean): Promise<void> +off(type: 'systemAvoidAreaChange', callback?: Callback<AvoidArea>): void -Sets whether this window can gain focus. This API uses a promise to return the result. +Disables listening for changes to the area where the window cannot be displayed. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | ---------------------------- | -| isFocusable | boolean | Yes | Whether the window can gain focus.| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed. | +| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | **Example** ```js -let isFocusable= true; -let promise = windowClass.setFocusable(isFocusable); -promise.then((data)=> { - console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); -}); +windowClass.off('systemAvoidAreaChange'); + ``` -### setKeepScreenOn +### isSupportWideGamut(deprecated) -setKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void +isSupportWideGamut(callback: AsyncCallback<boolean>): void -Sets whether to keep the screen always on. This API uses an asynchronous callback to return the result. +Checks whether this window supports the wide-gamut color space. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isWindowSupportWideGamut()](#iswindowsupportwidegamut9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | ------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite. | **Example** ```js -let isKeepScreenOn = true; -windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { +windowClass.isSupportWideGamut((err, data) => { if (err.code) { - console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); -}); -``` + console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); +}) -### setKeepScreenOn +``` -setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> +### isSupportWideGamut(deprecated) -Sets whether to keep the screen always on. This API uses a promise to return the result. +isSupportWideGamut(): Promise<boolean> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Checks whether this window supports the wide-gamut color space. This API uses a promise to return the result. -**Parameters** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isWindowSupportWideGamut()](#iswindowsupportwidegamut9-1) instead. -| Name | Type | Mandatory| Description | -| -------------- | ------- | ---- | ------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite. | **Example** ```js -let isKeepScreenOn = true; -let promise = windowClass.setKeepScreenOn(isKeepScreenOn); -promise.then((data) => { - console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); +let promise = windowClass.isSupportWideGamut(); +promise.then((data)=> { + console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); }); + ``` -### setOutsideTouchable(deprecated) +### setColorSpace(deprecated) -setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): void +setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void -Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. +Sets a color space for this window. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setWindowColorSpace()](#setwindowcolorspace9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ---------------- | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value `true` means that such an area is touchable, and `false` means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ----------------------------------- | +| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setOutsideTouchable(true, (err, data) => { +windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err) => { if (err.code) { - console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting window colorspace.'); }) ``` -### setOutsideTouchable(deprecated) +### setColorSpace(deprecated) -setOutsideTouchable(touchable: boolean): Promise<void> +setColorSpace(colorSpace:ColorSpace): Promise<void> -Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. +Sets a color space for this window. This API uses a promise to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setWindowColorSpace()](#setwindowcolorspace9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------- | ---- | ---------------- | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value `true` means that such an area is touchable, and `false` means the opposite.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ------------------- | +| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.setOutsideTouchable(true); -promise.then((data)=> { - console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)); +let promise = windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT); +promise.then(()=> { + console.info('Succeeded in setting window colorspace.'); }).catch((err)=>{ - console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); }); + ``` -### setPrivacyMode7+ +### getColorSpace(deprecated) -setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void +getColorSpace(callback: AsyncCallback<ColorSpace>): void -Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. +Obtains the color space of this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getWindowColorSpace()](#getwindowcolorspace9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------- | ---- | -------------------- | -| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. | **Example** ```js -let isPrivacyMode = true; -windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { +windowClass.getColorSpace((err, data) => { if (err.code) { - console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + console.error('Failed to get window colorspace. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the window to privacy mode. Data:' + JSON.stringify(data)); + console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)); +}) -}); ``` -### setPrivacyMode7+ - -setPrivacyMode(isPrivacyMode: boolean): Promise<void> +### getColorSpace(deprecated) -Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. +getColorSpace(): Promise<ColorSpace> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Obtains the color space of this window. This API uses a promise to return the result. -**Parameters** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getWindowColorSpace()](#getwindowcolorspace9) instead. -| Name | Type | Mandatory| Description | -| ------------- | ------- | ---- | -------------------- | -| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ---------------------------------------- | ----------------------------------------------- | +| Promise<[ColorSpace](#colorspace)> | Promise used to return the current color space. | **Example** ```js -let isPrivacyMode = true; -let promise = windowClass.setPrivacyMode(isPrivacyMode); +let promise = windowClass.getColorSpace(); promise.then((data)=> { - console.info('Succeeded in setting the window to privacy mode. Data: ' + JSON.stringify(data)); + console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); + console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err)); }); -``` - -### setSnapshotSkip9+ -setSnapshotSkip(isSkip: boolean): void - -Sets whether to ignore this window during screen capturing or recording. - -**System API**: This is a system API. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------- | ---- | -------------------- | -| isSkip | boolean | Yes | Whether to ignore the window. The default value is `false`.
The value `true` means that the window is ignored, and `false` means the opposite.
| -```js -let isSkip = true; -windowClass.setSnapshotSkip(isSkip); ``` -### setTouchable7+ +### setBackgroundColor(deprecated) -setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void +setBackgroundColor(color: string, callback: AsyncCallback<void>): void -Sets whether this window is touchable. This API uses an asynchronous callback to return the result. +Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBackgroundColor()](#setwindowbackgroundcolor9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------- | -| isTouchable | boolean | Yes | Whether the window is touchable.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let isTouchable = true; -windowClass.setTouchable(isTouchable, (err, data) => { +let color = '#00ff33'; +windowClass.setBackgroundColor(color, (err) => { if (err.code) { - console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + console.error('Failed to set the background color. 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 background color.'); }); ``` -### setTouchable7+ +### setBackgroundColor(deprecated) -setTouchable(isTouchable: boolean): Promise<void> +setBackgroundColor(color: string): Promise<void> -Sets whether this window is touchable. This API uses a promise to return the result. +Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBackgroundColor()](#setwindowbackgroundcolor9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | -------------------- | -| isTouchable | boolean | Yes | Whether the window is touchable.| +| Name | Type | Mandatory | Description | +| ----- | ------ | --------- | ------------------------------------------------------------ | +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let isTouchable = true; -let promise = windowClass.setTouchable(isTouchable); -promise.then((data)=> { - console.info('Succeeded in setting the window to be touchable. Data: ' + JSON.stringify(data)); +let color = '#00ff33'; +let promise = windowClass.setBackgroundColor(color); +promise.then(()=> { + console.info('Succeeded in setting the background color.'); }).catch((err)=>{ - console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); }); + ``` -### setForbidSplitMove9+ +### setBrightness(deprecated) -setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void>): void +setBrightness(brightness: number, callback: AsyncCallback<void>): void -Sets whether this window is forbidden to move in split-screen mode. This API uses an asynchronous callback to return the result. +Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------- | -| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ------------------------------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let isForbidSplitMove = true; -windowClass.setForbidSplitMove(isForbidSplitMove, (err, data) => { +let brightness = 1; +windowClass.setBrightness(brightness, (err) => { if (err.code) { - console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err)); + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in forbidding window moving in split screen mode. Data:' + JSON.stringify(data)); - + console.info('Succeeded in setting the brightness.'); }); + ``` -### setForbidSplitMove9+ +### setBrightness(deprecated) -setForbidSplitMove(isForbidSplitMove: boolean): Promise<void> +setBrightness(brightness: number): Promise<void> -Sets whether this window is forbidden to move in split-screen mode. This API uses a promise to return the result. +Sets the screen brightness for this window. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | -------------------- | -| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ------------------------------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let isForbidSplitMove = true; -let promise = windowClass.setForbidSplitMove(isForbidSplitMove); -promise.then((data)=> { - console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data)); +let brightness = 1; +let promise = windowClass.setBrightness(brightness); +promise.then(()=> { + console.info('Succeeded in setting the brightness.'); }).catch((err)=>{ - console.error('Failed to forbid window moving in split screen mode. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); }); + ``` -### snapshot9+ +### setDimBehind(deprecated) -snapshot(callback: AsyncCallback<image.PixelMap>): void +setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void -Captures this window. This API uses an asynchronous callback to return the result. +Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------- | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | --------- | ------------------------------------------------------------ | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.snapshot((err, data) => { +windowClass.setDimBehind(0.5, (err) => { if (err.code) { - console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - data.release(); // Release the memory in time after the PixelMap is used. + console.info('Succeeded in setting the dimness.'); }); ``` -### snapshot9+ +### setDimBehind(deprecated) -snapshot(): Promise<image.PixelMap> +setDimBehind(dimBehindValue: number): Promise<void> -Captures this window. This API uses a promise to return the result. +Sets the dimness of the window that is not on top. This API uses a promise to return the result. + +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | --------- | ------------------------------------------------------------ | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest. | + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.snapshot(); -promise.then((pixelMap)=> { - console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. +let promise = windowClass.setDimBehind(0.5); +promise.then(()=> { + console.info('Succeeded in setting the dimness.'); }).catch((err)=>{ - console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); }); + ``` -### setBlur9+ +### setFocusable(deprecated) -setBlur(radius: number): void +setFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void -Blurs this window. +Sets whether this window can gain focus. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowFocusable()](#setwindowfocusable9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the window.| +| Name | Type | Mandatory | Description | +| ----------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setBlur(4.0); +let isFocusable= true; +windowClass.setFocusable(isFocusable, (err) => { + if (err.code) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable.'); +}); + ``` -### setBackdropBlur9+ +### setFocusable(deprecated) -setBackdropBlur(radius: number): void +setFocusable(isFocusable: boolean): Promise<void> -Blurs the background of this window. +Sets whether this window can gain focus. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowFocusable()](#setwindowfocusable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the background of the window.| +| Name | Type | Mandatory | Description | +| ----------- | ------- | --------- | ------------------------------------------------------------ | +| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -windowClass.setBackdropBlur(4.0); +let isFocusable= true; +let promise = windowClass.setFocusable(isFocusable); +promise.then(()=> { + console.info('Succeeded in setting the window to be focusable.'); +}).catch((err)=>{ + console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); +}); ``` -### setBackdropBlurStyle9+ +### setKeepScreenOn(deprecated) -setBackdropBlurStyle(blurStyle: BlurStyle): void +setKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void -Sets the blur style for the background of this window. +Sets whether to keep the screen always on. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowKeepScreenOn()](#setwindowkeepscreenon9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | --------- | ---- | ---------------------- | -| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setBackdropBlurStyle(window.BlurType.THIN); +let isKeepScreenOn = true; +windowClass.setKeepScreenOn(isKeepScreenOn, (err) => { + if (err.code) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on.'); +}); ``` -### setShadow9+ +### setKeepScreenOn(deprecated) -setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void +setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> -Sets the shadow for the window borders. +Sets whether to keep the screen always on. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowKeepScreenOn()](#setwindowkeepscreenon9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value `0` means that the shadow is disabled for the window borders.| -| color | string | No | Color of the shadow. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | -| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | +| Name | Type | Mandatory | Description | +| -------------- | ------- | --------- | ------------------------------------------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +let isKeepScreenOn = true; +let promise = windowClass.setKeepScreenOn(isKeepScreenOn); +promise.then(() => { + console.info('Succeeded in setting the screen to be always on.'); +}).catch((err)=>{ + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); +}); ``` -### setCornerRadius9+ +### setOutsideTouchable(deprecated) -setCornerRadius(cornerRadius: number): void +setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): void -Sets the radius of the rounded corners for this window. +Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | -------------------- | -| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value `0` means that the window does not use rounded corners.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | --------- | ------------------------------------------------------------ | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setCornerRadius(4.0); +windowClass.setOutsideTouchable(true, (err) => { + if (err.code) { + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the area to be touchable.'); +}) ``` -### opacity9+ +### setOutsideTouchable(deprecated) -opacity(opacity: number): void +setOutsideTouchable(touchable: boolean): Promise<void> -Sets the opacity for this window. +Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------- | -| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0.| +| Name | Type | Mandatory | Description | +| --------- | ------- | --------- | ------------------------------------------------------------ | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -windowClass.opacity(0.5); +let promise = windowClass.setOutsideTouchable(true); +promise.then(()=> { + console.info('Succeeded in setting the area to be touchable.'); +}).catch((err)=>{ + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); +}); ``` -### scale9+ +### setPrivacyMode(deprecated) -scale(scaleOptions: ScaleOptions): void +setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void -Sets the scale parameters for this window. +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowPrivacyMode()](#setwindowprivacymode9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------------------------------ | ---- | ---------- | -| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set.| +| Name | Type | Mandatory | Description | +| ------------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let obj : window.ScaleOptions = { - x : 2.0, - y : 1.0, - pivotX = 0.5; - pivotY = 0.5; -} -windowClass.scale(obj); +let isPrivacyMode = true; +windowClass.setPrivacyMode(isPrivacyMode, (err) => { + if (err.code) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode.'); + +}); + ``` -### rotate9+ +### setPrivacyMode(deprecated) -rotate(rotateOptions: RotateOptions): void +setPrivacyMode(isPrivacyMode: boolean): Promise<void> -Sets the rotation parameters for this window. +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowPrivacyMode()](#setwindowprivacymode9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | -------------------------------- | ---- | ---------- | -| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set.| +| Name | Type | Mandatory | Description | +| ------------- | ------- | --------- | ------------------------------------------------------------ | +| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let obj : window.RotateOptions = { - x : 1.0, - y : 1.0, - z : 45.0, - pivotX = 0.5; - pivotY = 0.5; -} -windowClass.rotate(obj); +let isPrivacyMode = true; +let promise = windowClass.setPrivacyMode(isPrivacyMode); +promise.then(()=> { + console.info('Succeeded in setting the window to privacy mode.'); +}).catch((err)=>{ + console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); +}); ``` -### translate9+ +### setTouchable(deprecated) -translate(translateOptions: TranslateOptions): void +setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void -Sets the translation parameters for this window. +Sets whether this window is touchable. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowTouchable()](#setwindowtouchable9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | -------------------------------------- | ---- | ---------- | -| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set.| +| Name | Type | Mandatory | Description | +| ----------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let obj : window.TranslateOptions = { - x : 100.0, - y : 0.0, - z : 0.0 -} -windowClass.translate(obj); +let isTouchable = true; +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.'); + +}); ``` -### getTransitionController9+ +### setTouchable(deprecated) - getTransitionController(): TransitionController +setTouchable(isTouchable: boolean): Promise<void> -Obtains the transition animation controller. +Sets whether this window is touchable. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowTouchable()](#setwindowtouchable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------- | --------- | ------------------------------------------------------------ | +| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite. | + **Return value** -| Type | Description | -| ---------------------------------------------- | ---------------- | -| [TransitionController](#transitioncontroller9) | Transition animation controller.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let controller = windowClass.getTransitionController(); // Obtain the transition animation controller. -controller.animationForHidden = (context : window.TransitionContext) => { - let toWindow = context.toWindow - animateTo({ - duration: 1000, // Animation duration. - tempo: 0.5, // Playback speed. - curve: Curve.EaseInOut, // Animation curve. - delay: 0, // Animation delay. - iterations: 1, // Number of playback times. - playMode: PlayMode.Normal // Animation playback mode. - onFinish: ()=> { - context.completeTransition(true) - } - }, () => { - let obj : window.TranslateOptions = { - x : 100.0, - y : 0.0, - z : 0.0 - } - toWindow.translate(obj); // Set the transition animation. - console.info('toWindow translate end'); - } - ) - console.info('complete transition end'); -} -windowClass.hideWithAnimation((err, data) => { - if (err.code) { - console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); -}) +let isTouchable = true; +let promise = windowClass.setTouchable(isTouchable); +promise.then(()=> { + console.info('Succeeded in setting the window to be touchable.'); +}).catch((err)=>{ + console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); +}); ``` ## WindowStageEventType9+ @@ -3459,18 +5849,18 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value | Description | -| ---------- | ------ | ---------- | -| FOREGROUND | 1 | The window stage is running in the foreground.| -| ACTIVE | 2 | The window stage gains focus.| -| INACTIVE | 3 | The window stage loses focus.| -| BACKGROUND | 4 | The window stage is running in the background.| +| Name | Default Value | Description | +| ---------- | ------------- | ---------------------------------------------- | +| FOREGROUND | 1 | The window stage is running in the foreground. | +| ACTIVE | 2 | The window stage gains focus. | +| INACTIVE | 3 | The window stage loses focus. | +| BACKGROUND | 4 | The window stage is running in the background. | ## WindowStage9+ Implements a window manager, which manages each basic window unit, that is, [Window](#window) instance. -Before calling any of the following APIs, you must use `[onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate)` to create a `WindowStage` instance. +Before calling any of the following APIs, you must use [onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate) to create a **WindowStage** instance. ### getMainWindow9+ @@ -3484,9 +5874,18 @@ Obtains the main window of this window stage. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3507,6 +5906,7 @@ class myAbility extends Ability { } } ``` + ### getMainWindow9+ getMainWindow(): Promise<Window> @@ -3519,9 +5919,18 @@ Obtains the main window of this window stage. This API uses a promise to return **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the main window.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the main window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3541,6 +5950,48 @@ class myAbility extends Ability { } } ``` + +### getMainWindowSync9+ + +getMainWindowSync(): Window + +Obtains the main window of this window stage. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ----------------- | ----------------------- | +| [Window](#window) | return the main window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | + +**Example** + +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + try { + let windowClass = windowStage.getMainWindowSync(); + } catch (exception) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(exception)); + }; + } +} +``` + ### createSubWindow9+ createSubWindow(name: string, callback: AsyncCallback<Window>): void @@ -3553,10 +6004,19 @@ Creates a subwindow for this window stage. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------------- | -| name | String | Yes | Name of the subwindow. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | --------- | -------------------------------------- | +| name | String | Yes | Name of the subwindow. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3566,18 +6026,23 @@ class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; - windowStage.createSubWindow('mySubWindow', (err, data) => { - if (err.code) { - console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - windowClass.resetSize(500, 1000); - }); + try { + windowStage.createSubWindow('mySubWindow', (err, data) => { + if (err.code) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); + }); + } catch (exception) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(exception)); + }; } } ``` + ### createSubWindow9+ createSubWindow(name: string): Promise<Window> @@ -3590,15 +6055,24 @@ Creates a subwindow for this window stage. This API uses a promise to return the **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | String | Yes | Name of the subwindow.| +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ---------------------- | +| name | String | Yes | Name of the subwindow. | **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the subwindow.| +| Type | Description | +| -------------------------------- | ------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the subwindow. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3608,16 +6082,21 @@ class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; - let promise = windowStage.createSubWindow('mySubWindow'); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); - }) + try { + let promise = windowStage.createSubWindow('mySubWindow'); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(exception)); + }; } } ``` + ### getSubWindow9+ getSubWindow(callback: AsyncCallback<Array<Window>>): void @@ -3630,9 +6109,17 @@ Obtains all the subwindows of this window stage. This API uses an asynchronous c **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------------- | -| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------- | +| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300005 | This window stage is abnormal. | **Example** @@ -3653,6 +6140,7 @@ class myAbility extends Ability { } } ``` + ### getSubWindow9+ getSubWindow(): Promise<Array<Window>> @@ -3665,9 +6153,17 @@ Obtains all the subwindows of this window stage. This API uses a promise to retu **Return value** -| Type | Description | -| --------------------------------------------- | ---------------------------------------------------- | -| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows.| +| Type | Description | +| --------------------------------------------- | ------------------------------------------ | +| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300005 | This window stage is abnormal. | **Example** @@ -3687,6 +6183,7 @@ class myAbility extends Ability { } } ``` + ### loadContent9+ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void @@ -3699,11 +6196,20 @@ Loads content from a page associated with a local storage to the main window in **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3715,13 +6221,17 @@ class myAbility extends Ability { this.storage = new LocalStorage(); this.storage.setOrCreate('storageSimpleProp',121); console.log('onWindowStageCreate'); - windowStage.loadContent('pages/page2',this.storage,(err, data) => { - 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)); - }); + try { + windowStage.loadContent('pages/page2',this.storage,(err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); + } catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); + }; } } ``` @@ -3738,16 +6248,25 @@ Loads content from a page associated with a local storage to the main window in **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3759,14 +6278,16 @@ class myAbility extends Ability { this.storage = new LocalStorage(); this.storage.setOrCreate('storageSimpleProp',121); console.log('onWindowStageCreate'); - let windowClass = null; - let promise = windowStage.loadContent('pages/page2',this.storage); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - }) + try { + let promise = windowStage.loadContent('pages/page2',this.storage); + promise.then(()=> { + console.info('Succeeded in loading the content.'); + }).catch((err)=>{ + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); + }; } } ``` @@ -3783,10 +6304,19 @@ Loads content from a page to this window stage. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------- | +| path | string | Yes | Path of the page from which the content will be loaded. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3795,13 +6325,17 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.loadContent('pages/page2', (err, data) => { - 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)); - }); + try { + 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.'); + }); + } catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); + }; } } ``` @@ -3818,10 +6352,19 @@ Enables listening for window stage lifecycle changes. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event. | +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3830,9 +6373,15 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.on('windowStageEvent', (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + JSON.stringify(data)); - }); + try { + windowStage.on('windowStageEvent', (data) => { + console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + + JSON.stringify(data)); + }); + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; } } ``` @@ -3849,10 +6398,19 @@ Disables listening for window stage lifecycle changes. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event. | +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3861,7 +6419,12 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.off('windowStageEvent'); + try { + windowStage.off('windowStageEvent'); + } catch (exception) { + console.error('Failed to disable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; } } ``` @@ -3878,6 +6441,15 @@ Disables window decorators. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | + **Example** ```ts @@ -3904,9 +6476,18 @@ Sets whether to display the window of the application on the lock screen. **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ------- | ---- | ---------------------------- | -| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen.| +| Name | Type | Mandatory | Description | +| ---------------- | ------- | --------- | ------------------------------------------------------------ | +| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen. The value **true** means to display the window on the lock screen, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3915,10 +6496,15 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.setShowOnLockScreen(true); + try { + windowStage.setShowOnLockScreen(true); + } catch (exception) { + console.error('Failed to show on lockscreen. Cause:' + JSON.stringify(exception)); + }; } } ``` + ## TransitionContext9+ Provides the context for the transition animation. @@ -3929,9 +6515,9 @@ Provides the context for the transition animation. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| --------------------- | ----------------- | ---- | ---- | ---------------- | -| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation.| +| Name | Type | Readable | Writable | Description | +| --------------------- | ----------------- | -------- | -------- | --------------------------------------- | +| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation. | ### completeTransition9+ @@ -3945,16 +6531,16 @@ Completes the transition. This API can be called only after [animateTo()](../ark **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | ------------------------------------------------------------ | -| isCompleted | boolean | Yes | Whether the transition is complete. The value `true` means that the transition is complete, and `false` means the opposite.| +| Name | Type | Mandatory | Description | +| ----------- | ------- | --------- | ------------------------------------------------------------ | +| isCompleted | boolean | Yes | Whether the transition is complete. The value **true** means that the transition is complete, and **false** means the opposite. | **Example** ```js let controller = windowClass.getTransitionController(); controller.animationForShown = (context : window.TransitionContext) => { - let toWindow = context.toWindow + let toWindow = context.toWindow; animateTo({ duration: 1000, // Animation duration. tempo: 0.5, // Playback speed. @@ -3967,14 +6553,18 @@ controller.animationForShown = (context : window.TransitionContext) => { x : 100.0, y : 0.0, z : 0.0 - } + }; toWindow.translate(obj); console.info('toWindow translate end'); } ) - context.completeTransition(true) + try { + context.completeTransition(true) + } catch (exception) { + console.info('toWindow translate fail. Cause: ' + JSON.stringify(exception)); + } console.info('complete transition end'); -} +}; ``` ## TransitionController9+ @@ -3993,16 +6583,16 @@ Customizes the animation for the scenario when the window is shown. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------------- | ---- | -------------------- | -| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | --------- | ------------------------------------ | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation. | **Example** ```js let controller = windowClass.getTransitionController(); controller.animationForShown = (context : window.TransitionContext) => { - let toWindow = context.toWindow + let toWindow = context.toWindow; animateTo({ duration: 1000, // Animation duration. tempo: 0.5, // Playback speed. @@ -4018,7 +6608,7 @@ controller.animationForShown = (context : window.TransitionContext) => { x : 100.0, y : 0.0, z : 0.0 - } + }; toWindow.translate(obj); console.info('toWindow translate end'); } @@ -4039,16 +6629,16 @@ Customizes the animation for the scenario when the window is hidden. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------------- | ---- | -------------------- | -| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | --------- | ------------------------------------ | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation. | **Example** ```js let controller = windowClass.getTransitionController(); controller.animationForHidden = (context : window.TransitionContext) => { - let toWindow = context.toWindow + let toWindow = context.toWindow; animateTo({ duration: 1000, // Animation duration. tempo: 0.5, // Playback speed. @@ -4064,7 +6654,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { x : 100.0, y : 0.0, z : 0.0 - } + }; toWindow.translate(obj); console.info('toWindow translate end'); } @@ -4072,3 +6662,4 @@ controller.animationForHidden = (context : window.TransitionContext) => { console.info('complete transition end'); } ``` + diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 322a8000a525eef6e32174a2a099f04573570edc..945c5219bedb22f5efdd6f53b5d55d4cdd97f260 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -59,7 +59,9 @@ Sets an attribute. let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setAttributes("importance", "high"); +thatSer.startElement("note"); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index aaaad457f25d19f50735576c44f13aa011cbef58..75ac7f144e75fd9ed1068f161854fb185c0d6210 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,7 +1,7 @@ # Zip > **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 @@ -30,9 +30,9 @@ Zips a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------------------------- | -| Promise\ | Returns **ERROR_CODE_OK** if the operation is successful; returns **ERROR_CODE_ERRNO** otherwise.| +| Type | Description | +| -------------- | ------------------------------------------------------------ | +| Promise\ | Returns [ERROR_CODE_OK](#ziperrorcode) if the operation is successful.
Returns [ERROR_CODE_ERRNO](#ziperrorcode) if the operation fails.| **Example 1** @@ -96,7 +96,7 @@ Unzips a file. This API uses a promise to return the result. | Type | Description | | -------------- | ------------------------------------------------------------ | -| Promise\ | Returns **ERROR_CODE_OK** if the operation is successful; returns **ERROR_CODE_ERRNO** otherwise.| +| Promise\ | Returns [ERROR_CODE_OK](#ziperrorcode) if the operation is successful.
Returns [ERROR_CODE_ERRNO](#ziperrorcode) if the operation fails.| **Example** 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-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index f1bce5a8cc619c0e72e1bff539b311d355c23755..d7b27a661400b2557de5cf6c710f26b0d00e05a5 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -137,9 +137,9 @@ | Name | Description | | -------- | ---------------------- | | Top | Top edge in the vertical direction. | -| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | +| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | | Bottom | Bottom edge in the vertical direction. | -| Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9.| +| Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9. | | Start | Start position in the horizontal direction. | | Middle(deprecated) | Center position in the horizontal direction.
This API is deprecated since API version 9. | | End | End position in the horizontal direction. | @@ -249,7 +249,7 @@ | End | The child components are aligned with the end edge of the main axis. The last component is aligned with the main-end, and other components are aligned with the next one.| | SpaceBetween | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, the last component is aligned with the main-end, and the remaining components are distributed so that the space between any two adjacent components is the same.| | SpaceAround | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components.| -| SpaceEvenly | The child components are equally distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between two adjacent components are the same.| +| SpaceEvenly | The child components are evenly distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between any two adjacent components are the same. | ## ItemAlign @@ -355,9 +355,9 @@ | Name | Description | | -------- | -------------------------------------- | -| Clip | Extra-long text is truncated. | +| Clip | Extra-long text is clipped. | | Ellipsis | An ellipsis (...) is used to represent clipped text.| -| None | No truncation or ellipsis is used for extra-long text. | +| None | No clipping or ellipsis is used for extra-long text. | ## TextDecorationType @@ -413,9 +413,9 @@ | Name | Description | | ----------- | -------------------- | -| None | Copy and paste is not allowed. | -| InApp | Intra-application copy and paste is allowed.| -| LocalDevice | Intra-device copy and paste is allowed.| +| None | Copy is not allowed. | +| InApp | Intra-application copy is allowed.| +| LocalDevice | Intra-device copy is allowed.| ## HitTestMode9+ 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/errorcode-display.md b/en/application-dev/reference/errorcodes/errorcode-display.md new file mode 100644 index 0000000000000000000000000000000000000000..f86b0b10736c407cefb288e317288c66a9fd5a07 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-display.md @@ -0,0 +1,43 @@ +# Display Error Codes + +## 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** +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** +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. 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..7518de5a3f5a1202ece256f2c231039fa0b49542 --- /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. + +**Procedure** + +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..0f99a215923ac8bfe1aee4ff3aac64ded07fd6ea --- /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. + +**Procedure** + +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. + +**Procedure** + +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. + +**Procedure** + +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. + +**Procedure** + +Ensure that the URI is correct. diff --git a/en/application-dev/reference/errorcodes/errorcode-window.md b/en/application-dev/reference/errorcodes/errorcode-window.md new file mode 100644 index 0000000000000000000000000000000000000000..9e61c92b592c2e155ac6757f8e1dee4a01d762e9 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-window.md @@ -0,0 +1,79 @@ +# Window Error Codes + +## 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** +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** +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** +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** +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. diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index c7c051cfe4cc83e8c1b59f8517401e2a4207d59f..4a2fc6dd307645d4bb529ed9a15172c552b2b440 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -2,8 +2,9 @@ - Access Control - [Access Control (Permission) Overview](accesstoken-overview.md) - - [Guide for Requesting Permissions from User](accesstoken-guidelines.md) - - [Application Permission List](permission-list.md) + - [Permission Application Guide](accesstoken-guidelines.md) + - [Permission Verification Guide](permission-verify-guidelines.md) + - [App Permission List](permission-list.md) - User Authentication - [User Authentication Overview](userauth-overview.md) - [User Authentication Development](userauth-guidelines.md) diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index 71caf0a817d7115f6ce59359ff7d979a975f2406..c46c8fc8283271764986d20659276cf9f64aa555 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -1,4 +1,4 @@ -# Guide for Requesting Permissions from User +# Permission Application Guide ## When to Use @@ -115,7 +115,7 @@ The permission level of **ohos.permission.PERMISSION2** is **system_basic**, whi In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher that the app's APL in the app's profile. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). -In this example, declare the permission under the **acls** field: +For example, declare the required permission in the **acls** field: ```json { diff --git a/en/application-dev/security/accesstoken-overview.md b/en/application-dev/security/accesstoken-overview.md index e6e764eb45b63c9d7f09b2636d6ad26eae2d2e7d..9e8aa2a655ecdfbd3ebc4133230f12fb9cf46d67 100644 --- a/en/application-dev/security/accesstoken-overview.md +++ b/en/application-dev/security/accesstoken-overview.md @@ -1,8 +1,8 @@ # Access Control (Permission) Overview -AccessTokenManager (ATM) implements unified app permission management based on access tokens on OpenHarmony. +OpenHarmony AccessTokenManager (ATM) implements unified app permission management based on access tokens. -By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also share their data or functions through interfaces in an explicit manner. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. +By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also explicitly share their data or functions through APIs. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. App permissions are used to protect the following objects: @@ -11,7 +11,7 @@ App permissions are used to protect the following objects: Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions. -Currently, ATM verifies app permissions based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID. +Currently, ATM verifies app permissions based on the token identity (token ID). A token ID identifies an app. ATM manages app permissions based on the app's token ID. ## Basic Principles for Permission Management @@ -19,37 +19,52 @@ Observe the following principles for permission management: - Provide clear description about the app functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are required. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app. - Use the principle of least authority for user permissions. Allow only necessary permissions for service functions. -- When an app is started for the first time, avoid frequently displaying dialog boxes to request permissions. Allow the app to apply for permissions only when it needs to use the corresponding service functions. -- If a user rejects to authorize a permission, the user can still use functions irrelevant to this permission and can register and access the app. +- When an app is started for the first time, avoid frequently displaying dialog boxes to request multiple permissions. Allow the app to apply for the permission only when it needs to use the corresponding service function. +- If a user rejects to grant a permission, the user can still use functions irrelevant to this permission and can register and access the app. - Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to grant the permission in **Settings** if the user triggers this function again or needs to use this function. -- All the permissions granted to apps must come from the [Permission List](permission-list.md). Custom permissions are not allowed for apps currently. +- All the permissions granted to apps must come from the [App Permission List](permission-list.md). Custom permissions are not allowed for apps currently. -## Permission Workflow +## Permission Workflows -Determine the permissions required for an app to access data or perform an operation. Declare the required permissions in the app installation package. +### Permission Application and Use -Determine whether the required permissions need to be authorized by users. If yes, provide a dialog box dynamically to request user authorization. +Determine the permissions required by an app, and declare the required permissions in the app installation package. -After the user grants permissions to the app, the app can access the data or perform the operation. +Determine whether the required permissions need user authorization. If yes, display a dialog box dynamically to request user authorization. -The figure below shows the permission workflow. +After the user grants the permissions, the app can access the data or perform the operation. + +The figure below illustrates the process. ![](figures/permission-workflow.png) -1. You can refer to the figure below to determine whether an app can apply for a permission. +1. Refer to the figure below to determine whether an app can apply for a permission. ![](figures/permission-application-process.png) 1. See [Permission Levels](#permission-levels) for details about the mapping between the application Ability Privilege Level (APL) and permission level. -2. The permission authorization modes include user_grant (permission granted by the user) and system_grant (permission granted by the system). For details, see [Permission Authorization Modes](#permission-authorization-mode). +2. The permission authorization modes include user_grant (permission granted by the user) and system_grant (permission granted by the system). For details, see [Permission Types](#permission-types). + +3. A low-APL app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl). + +### Permission Verification +To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. The API can be called only after the permission verification is successful. + +The figure below shows the permission verification process. + +![](figures/permission-verify-process.png) -3. A low-level app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl). +1: An app permission can be used to control the access to an API that has sensitive data involved or security threats on the core abilities. + +2: Select the permission from the [App Permission List](permission-list.md). For example, if contact information is involved in an API provided by an app, you can use the contact-related permissions to protect the API. + +3: Use **verifyAccessToken()** to check whether the caller has the required permission. For details, see [Permission Verification Guide](permission-verify-guidelines.md). ## Permission Levels -To protect user privacy, ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability. +ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability to protect user privacy. ### App APLs @@ -59,21 +74,21 @@ The table below describes the APLs. | APL | Description | | ---------------- | -------------------------------------- | -| system_core | The apps of this level provide core abilities of the operating system.| +| system_core | The apps of this level provide core abilities of the operating system (OS). | | system_basic| The apps of this level provide basic system services. | | Normal | The apps of this level are normal apps. | -By default, apps are of the normal APL. +The default APL of apps is **normal**. -For the app of the system_basic or system_core APL, declare the APL in the **apl** field of **bundle-info** in the app's profile when developing the application installation package. +To set an app's APL to **system_basic** or **system_core**, declare the APL in the **apl** field of **bundle-info** in the app's profile when developing the app's installation package. Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificate or use DevEco Studio to [have your app automatically signed](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465#section161281722111). -> **CAUTION**
The method of declaring the app's APL in its profile applies only to the application or service in debug phase. For a commercial app, apply for a release certificate and profile in the corresponding app market. +> **CAUTION**
The method of changing the app's APL in its profile applies only to the app or service in debug mode. For a commercial app, apply for a release certificate and profile in the corresponding app market. The following is an example. -This example shows only the modification of the **apl** field. Set other fields based on service requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). +This example shows only the modification of the **apl** field. Set other fields based on your requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). ```json { @@ -100,17 +115,17 @@ The permissions open to apps vary with the permission level. The permission leve - **system_basic** - The system_basic permission allows access to resources related to basic operating system services. The basic services are basic functions provided or preconfigured by the system, such as system setting and identity authentication. Access to these resources may have considerable risks to user privacy and other apps. + The system_basic permission allows access to resources related to basic OS services. The basic services are basic functions provided or preconfigured by the system, such as system settings and identity authentication. Access to these resources may have considerable risks to user privacy and other apps. The permissions of this level are available only to apps of the system_basic or system_core APL. - **system_core** - The system_core permission allows access to core resources of the operating system. These resources are the underlying core services of the system. If these resources are corrupted, the OS cannot run properly. + The system_core permission allows access to core resources of the OS. These resources are underlying core services of the system. If these resources are corrupted, the OS cannot run properly. - The permissions of this type are not open to third-party apps currently. + The system_core permissions are not open to third-party apps currently. -## Permission Authorization Modes +## Permission Types Permissions can be classified into the following types based on the authorization mode: @@ -126,65 +141,70 @@ Permissions can be classified into the following types based on the authorizatio This type of permissions must be declared in the app installation package and authorized by users dynamically during the running of the app. The app has the permission only after user authorization. - For example, in the [Permission List](permission-list.md), the permissions for the microphone and camera are user_grant. The list provides reasons for using the permissions. + For example, in the [App Permission List](permission-list.md), the permissions for microphones and cameras are user_grant. The list provides reasons for using the permissions. The user_grant permission list must also be presented on the details page of the app in the app store. ### Authorization Processes -The process for an app obtaining the required permissions varies depending on the permission authorization mode. +As described in [Permission Workflows](permission-workflows), you need to first apply for the required permissions for the app. + +- Applying for permissions + + You need to [declare the required permissions](accesstoken-guidelines.md#declaring-permissions) in the configuration file. -- For a system_grant permission, you need to [declare the permission](accesstoken-guidelines.md#declaring-permissions) in the configuration file. The permission will be pre-granted when the app is installed. +- Authorizing permissions -- For a user_grant permission, you need to [declare the permission](accesstoken-guidelines.md#declaring-permissions) in the configuration file and trigger user authorization through a dialog box during the running of the app. + - The system_grant permission will be pre-granted when the app is installed. + - For a user_grant permission, you need to trigger user authorization through a dialog box during the running of the app. For details, see [Requesting User Authorization](#requesting-user-authorization). -### Permission Authorization Process (user_grant) +### Requesting User Authorization The procedure is as follows: 1. In the configuration file, declare the permissions required by the app. For details, see [Access Control Development](accesstoken-guidelines.md). -2. Associate the object that requires the permissions in the app with the target permissions. In this way, the user knows the operations to be granted with the specified permissions. +2. Associate the target objects in the app with the related permissions. This allows the users to know the operations that need user authorization. -3. Check whether the user has granted the required permissions to the app when the app is running. If yes, the app can access the data or perform the operation. If the user has not granted the permissions to the app, display a dialog box requesting the user authorization when the app attempts to access the data. +3. Use an API to dynamically trigger a dialog box requesting user authorization when the target object is accessed. The API first checks whether the user has granted the required permissions to the app. If yes, the app can access the data or perform the operation. Otherwise, a dialog box will be displayed to request user authorization. -4. Check the user authorization result. Allow the next step only after the user has granted the permissions to the app. +4. Check the user authorization result. Allow the subsequent operation only after the user has granted the permissions to the app. **Precautions** - Check the app's permission each time before the operation requiring the permission is performed. -- To check whether a user has granted specific permissions to your app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). -- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call the API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the requested permission. The user will determine whether to grant the permission based on the running context of the app. +- To check whether a user has granted specific permissions to an app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). +- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call an API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the permission. The user will determine whether to grant the permission based on the running context of the app. - The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission. ## ACL As described above, permission levels and app APLs are in one-to-one correspondence. In principle, **an app with a lower APL cannot apply for higher permissions by default**. -The ACL makes low-level apps have high-level permissions. +The ACL makes low-APL apps have high-level permissions. **Example** -The APL of app A is normal. App A needs to have permission B (system_basic level) and permission C (normal level). +The APL of app A is **normal**. App A needs to have permission B (system_basic level) and permission C (normal level). In this case, you can use the ACL to grant permission B to app A. For details, see [Using the ACL](#using-the-acl). -For details about whether a permission can be enabled through the ACL, see the [Permission List](permission-list.md). +For details about whether a permission can be enabled through the ACL, see the [App Permission List](permission-list.md). ### Using the ACL -If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permissions required. +If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permission required. In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL. -In other words, in addition to declaring the required permissions in the app's configuration file, you must [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same. +That is, you need to declare the required permissions in the app's configuration file, and [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same. **NOTICE** -When developing an app installation package, you must declare the allowed ACLs in the **acls** field in the app's profile. Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificate. +When developing an app installation package, you must declare the ACL in the **acls** field in the app's profile. Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificate. -> **CAUTION**
The method of declaring the app's APL in its profile applies only to the application or service in debug phase. For a commercial app, apply for a release certificate and profile in the corresponding app market. +> **CAUTION**
The method of changing the app's APL in its profile applies only to the app or service in debug mode. For a commercial app, apply for a release certificate and profile in the corresponding app market. ```json { diff --git a/en/application-dev/security/figures/permission-verify-process.png b/en/application-dev/security/figures/permission-verify-process.png new file mode 100644 index 0000000000000000000000000000000000000000..8fdfadcc5f42486273e6150d302ab9525113756f Binary files /dev/null and b/en/application-dev/security/figures/permission-verify-process.png differ diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 0f572b206d792df3e373d0468a10bb36690646ed..396f7d7eae1bb1058f615c3663e46be9eb574628 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1,8 +1,8 @@ -# Application Permission List +# App Permission List -Before applying for required permissions, read and understand the [permission workflow](accesstoken-overview.md#permission-workflow). Then, determine whether the app can apply for the target permissions based on the table below. +Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine whether the app can apply for the target permissions based on the table below. -For details about permission usage examples, see [Access Control Development](accesstoken-guidelines.md). +For details about permission usage examples, see [Permission Application Guide](accesstoken-guidelines.md). | Permission | APL | Authorization Mode | Enable ACL| Description | | -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------- | diff --git a/en/application-dev/security/permission-verify-guidelines.md b/en/application-dev/security/permission-verify-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..cca11b49b4f02be2631b354adf47c83d4d57e2c1 --- /dev/null +++ b/en/application-dev/security/permission-verify-guidelines.md @@ -0,0 +1,46 @@ +# Permission Verification Guide + +## When to Use + +To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. + +## Available APIs + +The table below lists only the API used in this guide. For more information, see [AbilityContext](../reference/apis/js-apis-ability-context.md). + +| API | Description | +| ------------------------------------------------------------ | --------------------------------------------------- | +| verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> | Checks whether an application process has the specified permission.| + + +## Example + +The procedure is as follows: + +1. Obtain the caller's identity (**tokenId**). +2. Determine the permission to verify, which is **ohos.permission.PERMISSION** in this example. +3. Call **verifyAccessToken()** to perform a permission verification of the caller. +4. Proceed based on the permission verification result. + +```js + import abilityAccessCtrl from '@ohos.abilityAccessCtrl' + import rpc from '@ohos.rpc' + + class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); + console.log("RpcServer: getCallingTokenId result: " + callerTokenId); + var atManager = abilityAccessCtrl.createAtManager(); + var result = await atManager.verifyAccessToken(tokenID, "ohos.permission.PERMISSION"); + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + // Allow the caller to invoke the API provided by the app. + } else { + // Deny the caller's access to the API. + } + return true; + } + } + +``` +> **NOTE**
+> You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md#getcallingtokenid8). 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..9e40170495e5cb4ee971f98227e0f837af053c8b 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-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. @@ -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-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,11 +156,11 @@ 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 @@ -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-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. 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 a0b35543246aff22d2d6ad693f1553add5932457..3fd15c24b6df07403b77eff0e71d71cb2dea6414 100644 --- a/en/contribute/introducing-third-party-open-source-software.md +++ b/en/contribute/introducing-third-party-open-source-software.md @@ -12,7 +12,7 @@ This guide applies to all third-party open-source software to be introduced to t ## Improvements and Revisions 1. This document is drafted and maintained by the OpenHarmony SIG QA. What you are reading now is the latest version of this document. - + 2. Any addition, modification, or deletion of the principles mentioned in this document can be traced in the tracing system. 3. The PMC reviews and finalizes the principles after thorough discussion in the community. @@ -37,9 +37,25 @@ 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 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 + device/board/$(BOARD_COMPANY)/third_party + vendor/$(PRODUCT_COMPANY)/third_party + ``` + +14. Precompiled binary or toolchain used in the OpenHarmony, the following information needs to be provided. + - 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 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 @@ -64,10 +80,10 @@ Follow the process described in the [SIG Management Regulations](https://gitee.c | Check Item| Description| Self-Check Result Example| | :----- | :----- | :----- | | Software name| Provide the official name of the software and the repository name to which the software is introduced. The repository name is in the format of **third_party**_**softwareName**.| third_party_**softwareName**| -| Official website| Provide the official website link of the software.| https://softwaresite | +| Official website| Provide the official website link of the software.| | | Software version| Provide the version number of the software to be introduced. The version number must be an official version number released by the community. Do not modify the version number or introduce a version that is not officially released.| 1.0.0 | | Software version release date| Provide the official release date of the software version.| 2021.01.01 | -| Software version address| Provide the official download URL of the version. Note that the URL must be able to locate the release package of the specific version.| https://gitee.com/softwarecodesite/v1.0.0.zip | +| Software version address| Provide the official download URL of the version. Note that the URL must be able to locate the release package of the specific version.| | | Software license| Provide the official license name of the version and the relative path of the license file. If there are multiple licenses, list them all and describe their relationship, for example, And, Or, or different licenses for different directories.| Apache-2.0 | | Software lifecycle| Describe whether the software has an LTS version, how frequent a version is released, code submitted to the community in the last year, issue resolution status, and whether end of maintenance or evolution is notified.| No LTS version; one version released every six months; 10 code submissions in the last six months| | Security vulnerabilities| List disclosed security vulnerabilities in the software, including the vulnerability number, severity, link, and whether patches or solutions are available.| No disclosed vulnerabilities.| @@ -121,9 +137,9 @@ Confirm the issues found by the OAT tool and configure the **OAT.xml** file. For ] ``` -#### PMC Review +#### Open source software introduction Review -Refer to the [SIG Management Regulations](https://gitee.com/openharmony/community/tree/master/sig). The PMC will arrange the SIG request review and repository construction based on the received PR. +Refer to the [SIG-Architecture](https://gitee.com/openharmony/community/blob/master/sig/sig-architecture/sig-architecture_cn.md). The SIG-Architecture will arrange the review of the applying of creating new repository. ### License Requirements for Third-Party Open-Source Software @@ -131,66 +147,66 @@ Refer to the [SIG Management Regulations](https://gitee.com/openharmony/communit 2. The software license must be compatible with the license for the code repository. 3. The following licenses for third-party open-source software are recommended in the OpenHarmony project: -* Apache License 2.0 -* Mulan Permissive Software License, Version 2 -* BSD 2-clause -* BSD 3-clause -* DOM4J License -* PostgreSQL License -* Eclipse Distribution License 1.0 -* MIT -* ISC -* ICU -* University of Illinois/NCSA -* W3C Software License -* zlib/libpng -* Academic Free License 3.0 -* Python Software Foundation License -* Python Imaging Library Software License -* Boost Software License Version 1.0 -* WTF Public License -* UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE -* Zope Public License 2.0 +- Apache License 2.0 +- Mulan Permissive Software License, Version 2 +- BSD 2-clause +- BSD 3-clause +- DOM4J License +- PostgreSQL License +- Eclipse Distribution License 1.0 +- MIT +- ISC +- ICU +- University of Illinois/NCSA +- W3C Software License +- zlib/libpng +- Academic Free License 3.0 +- Python Software Foundation License +- Python Imaging Library Software License +- Boost Software License Version 1.0 +- WTF Public License +- UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE +- Zope Public License 2.0 4. The following licenses for third-party open-source software are not recommended in the OpenHarmony project: -* GNU GPL 1, 2, 3 -* GNU Affero GPL 3 -* GNU LGPL 2, 2.1, 3 -* QPL -* Sleepycat License -* Server Side Public License (SSPL) version 1 -* Code Project Open License (CPOL) -* BSD-4-Clause/BSD-4-Clause (University of California-Specific) -* Facebook BSD+Patents license -* NPL 1.0/NPL 1.1 -* The Solipsistic Eclipse Public License -* The "Don't Be A Dick" Public License -* JSON License -* Binary Code License (BCL) -* Intel Simplified Software License -* JSR-275 License -* Microsoft Limited Public License -* Amazon Software License (ASL) -* Java SDK for Satori RTM license -* Redis Source Available License (RSAL) -* Booz Allen Public License -* Creative Commons Non-Commercial -* Sun Community Source License 3.0 -* Common Development and Distribution Licenses: CDDL 1.0 and CDDL 1.1 -* Common Public License: CPL 1.0 -* Eclipse Public License: EPL 1.0 -* IBM Public License: IPL 1.0 -* Mozilla Public Licenses: MPL 1.0, MPL 1.1, and MPL 2.0 -* Sun Public License: SPL 1.0 -* Open Software License 3.0 -* Erlang Public License -* UnRAR License -* SIL Open Font License -* Ubuntu Font License Version 1.0 -* IPA Font License Agreement v1.0 -* Ruby License -* Eclipse Public License 2.0: EPL 2.0 +- GNU GPL 1, 2, 3 +- GNU Affero GPL 3 +- GNU LGPL 2, 2.1, 3 +- QPL +- Sleepycat License +- Server Side Public License (SSPL) version 1 +- Code Project Open License (CPOL) +- BSD-4-Clause/BSD-4-Clause (University of California-Specific) +- Facebook BSD+Patents license +- NPL 1.0/NPL 1.1 +- The Solipsistic Eclipse Public License +- The "Don't Be A Dick" Public License +- JSON License +- Binary Code License (BCL) +- Intel Simplified Software License +- JSR-275 License +- Microsoft Limited Public License +- Amazon Software License (ASL) +- Java SDK for Satori RTM license +- Redis Source Available License (RSAL) +- Booz Allen Public License +- Creative Commons Non-Commercial +- Sun Community Source License 3.0 +- Common Development and Distribution Licenses: CDDL 1.0 and CDDL 1.1 +- Common Public License: CPL 1.0 +- Eclipse Public License: EPL 1.0 +- IBM Public License: IPL 1.0 +- Mozilla Public Licenses: MPL 1.0, MPL 1.1, and MPL 2.0 +- Sun Public License: SPL 1.0 +- Open Software License 3.0 +- Erlang Public License +- UnRAR License +- SIL Open Font License +- Ubuntu Font License Version 1.0 +- IPA Font License Agreement v1.0 +- Ruby License +- Eclipse Public License 2.0: EPL 2.0 If you want to introduce the software that complies with the unrecommended licenses listed in **4** or other licenses that are not mentioned, send an email to oh-legal@openatom.io. 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 new file mode 100644 index 0000000000000000000000000000000000000000..41cf5c40377d63290703eae2b5fa48d886a5d6ca --- /dev/null +++ b/en/contribute/prebuilts-readme-template.md @@ -0,0 +1,28 @@ +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 +------------------ + +``` +# Get source code +repo init -u https://gitee.com/openharmony/manifest.git -b llvm_toolchain-dev +repo sync -c +repo forall -c 'git lfs pull' +cp -r toolchain/llvm-project/llvm-build toolchain + +# Build Clang/LLVM-based prebuilts tool +./toolchain/llvm-project/llvm-build/env_prepare.sh +python3 ./toolchain/llvm-build/build.py +``` + +3. Update prebuilts +---------------- +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/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 e1ffba36672d0470e45a38331c33b11991811d0d..369f272c6ec8d1af651f9b69ae4db2d893df464e 100644 --- a/en/readme/location.md +++ b/en/readme/location.md @@ -116,27 +116,7 @@ The following table describes APIs available for obtaining device location infor If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background. - To allow your application to access device location information, you can declare the required permissions in the **config.json** file of your application. The sample code is as follows: - - - ``` - { - "module": { - "reqPermissions": [{ - "name": "ohos.permission.LOCATION", - "reason": "$string:reason_description", - "usedScene": { - "ability": ["com.myapplication.LocationAbility"], - "when": "inuse" - }, { - ... - } - ] - } - } - ``` - - For details about the configuration fields, see [Application Package Structure Configuration File](../application-dev/quick-start/stage-structure.md). + You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../application-dev/quick-start/stage-structure.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. diff --git a/zh-cn/application-dev/ability/stage-call.md b/zh-cn/application-dev/ability/stage-call.md index 7aa9769c0a56c39bc9d93772c5a1e0cd7d4ba2f3..781cdee7fa99ea7233d166edd67984b9c52f47f6 100644 --- a/zh-cn/application-dev/ability/stage-call.md +++ b/zh-cn/application-dev/ability/stage-call.md @@ -40,7 +40,7 @@ Caller及Callee功能如下:具体的API详见[接口文档](../reference/apis |call(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据。| |callWithResult(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。| |release(): void|释放通用组件的Caller通信接口。| -|onRelease(callback: OnReleaseCallBack): void|注册通用组件通信断开监听通知。| +|on(type: "release", callback: OnReleaseCallback): void|注册通用组件通信断开监听通知。| ## 开发步骤 Call调用的开发步骤: @@ -72,7 +72,7 @@ Ability配置标签示例如下: ``` **2. 导入Ability模块** ```ts -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.app.ability.UIAbility' ``` **3. 定义约定的序列化数据** @@ -142,7 +142,7 @@ export default class CalleeAbility extends Ability { ### 访问Callee被调用端 **1. 导入Ability模块** ```ts -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.app.ability.UIAbility' ``` **2. 获取Caller通信接口** @@ -151,7 +151,7 @@ import Ability from '@ohos.application.Ability' // 注册caller的release监听 private regOnRelease(caller) { try { - caller.onRelease((msg) => { + caller.on("release", (msg) => { console.log(`caller onRelease is called ${msg}`) }) console.log('caller register OnRelease succeed') @@ -192,7 +192,7 @@ async onButtonGetRemoteCaller() { caller = data console.log('get remote caller success') // 注册caller的release监听 - caller.onRelease((msg) => { + caller.on("release", (msg) => { console.log(`remote caller onRelease is called ${msg}`) }) console.log('remote caller register OnRelease succeed') diff --git a/zh-cn/application-dev/device/Readme-CN.md b/zh-cn/application-dev/device/Readme-CN.md index e104eb19bee15a03d98dfcc88c52fd908648dfd0..9d211b929513eb5638f71e1ff0a98a115c8bb727 100644 --- a/zh-cn/application-dev/device/Readme-CN.md +++ b/zh-cn/application-dev/device/Readme-CN.md @@ -13,6 +13,9 @@ - 振动 - [振动开发概述](vibrator-overview.md) - [振动开发指导](vibrator-guidelines.md) +- 设备管理 + - [输入设备开发指导](inputdevice-guidelines.md) + - [鼠标光标开发指导](pointerstyle-guidelines.md) - 升级服务 - [示例服务器开发概述](sample-server-overview.md) - [示例服务器开发指导](sample-server-guidelines.md) diff --git a/zh-cn/application-dev/device/inputdevice-guidelines.md b/zh-cn/application-dev/device/inputdevice-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..166f085cc394b7f20c6773ec9c6f8ec2b80ad5c6 --- /dev/null +++ b/zh-cn/application-dev/device/inputdevice-guidelines.md @@ -0,0 +1,70 @@ +# 输入设备开发指导 + +## 场景介绍 + +输入设备管理提供设备热插拔监听、查询指定设备的键盘类型等能力。使用场景例如:当用户需要输入文本时,输入法会根据当前是否插入了物理键盘来决定是否弹出虚拟键盘,开发者可以通过监听设备热插拔判断是否有物理键盘插入。 + +## 导入模块 + +```js +import inputDevice from '@ohos.multimodalInput.inputDevice'; +``` + +## 接口说明 + +输入设备管理常用接口如下表所示,接口详细介绍请参考[ohos.multimodalInput.inputDevice文档](../reference/apis/js-apis-inputdevice.md)。 + +| 实例名 | 接口名 | 说明 | +| ----------- | ------------------------------------------------------------ | -------------------------- | +| inputDevice | **function** getDeviceList(callback: AsyncCallback>): **void**; | 获取输入设备列表。 | +| inputDevice | **function** getKeyboardType(deviceId: **number**, callback: AsyncCallback): **void**; | 获取输入设备的键盘类型。 | +| inputDevice | **function** on(**type**: "change", listener: Callback): **void**; | 监听输入设备的热插拔事件。 | +| inputDevice | **function** off(**type**: "change", listener?: Callback): **void**; | 取消监听输入设备的热插拔事件。 | + +## 虚拟键盘弹出检测 + +当用户需要输入文本时,输入法会根据当前是否插入了物理键盘来决定是否弹出虚拟键盘,开发者可以通过监听设备热插拔,判断是否有物理键盘插入。 + +## 开发步骤 + +1. 调用getDeviceList方法查询所有连接的输入设备,调用getKeyboardType方法遍历所有连接的设备,判断是否有物理键盘,若有则标记已有物理键盘连接,该步骤确保监听设备热插拔之前,检测所有插入的输入设备。 +2. 调用on接口监听输入设备热插拔事件,若监听到有物理键盘插入,则标记已有物理键盘连接;若监听到有物理键盘拔掉,则标记没有物理键盘连接。 +3. 文本框进行输入时,判断是否有物理键盘连接,如果有物理键盘则不弹出虚拟键盘,如果没有物理键盘则弹出虚拟键盘。 + + +```js +import inputDevice from '@ohos.multimodalInput.inputDevice'; + +let isPhysicalKeyboardExist = true; +try { + // 1.获取设备列表,判断是否有物理键盘连接 + inputDevice.getDeviceList().then(data => { + for (let i = 0; i < data.length; ++i) { + inputDevice.getKeyboardType(data[i]).then(res => { + if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) { + // 物理键盘已连接 + isPhysicalKeyboardExist = true; + } + }); + } + }); + // 2.监听设备热插拔 + inputDevice.on("change", (data) => { + console.log(`Device event info: ${JSON.stringify(data)}`); + inputDevice.getKeyboardType(data.deviceId, (error, type) => { + console.log("The keyboard type is: " + type); + if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { + // 物理键盘已插入 + isPhysicalKeyboardExist = true; + } else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { + // 物理键盘已拔掉 + isPhysicalKeyboardExist = false; + } + }); + }); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} + // 3.根据isPhysicalKeyboardExist的值决定虚拟键盘是否弹出 + // TODO +``` diff --git a/zh-cn/application-dev/device/pointerstyle-guidelines.md b/zh-cn/application-dev/device/pointerstyle-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..a2bf27e017bab128a56cb2f1af4213490e0e6c63 --- /dev/null +++ b/zh-cn/application-dev/device/pointerstyle-guidelines.md @@ -0,0 +1,119 @@ +# 鼠标光标开发指导 + +## 场景介绍 + +鼠标光标控制提供对鼠标光标显示隐藏、光标样式查询设置的能力。使用场景例如:用户在全屏观看视频时,开发者可以控制鼠标光标的显示隐藏;当用户执行取色时,开发者可以将鼠标光标样式切换为取色器样式。 + +## 导入模块 + +```js +import inputDevice from '@ohos.multimodalInput.pointer'; +``` + +## 接口说明 + +鼠标光标控制常用接口如下表所示,接口详细介绍请参见[ohos.multimodalInput.pointer文档](../reference/apis/js-apis-pointer.md) + +| 实例名 | 接口名 | 说明 | +| ------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| pointer | **function** isPointerVisible(callback: AsyncCallback): **void**; | 获取鼠标指针显示或隐藏状态。 | +| pointer | **function** setPointerVisible(visible: boolean, callback: AsyncCallback<**void**>): **void**; | 设置鼠标指针显示或隐藏状态,改接口会影响全局鼠标光标的显示状态。 | +| pointer | **function** setPointerStyle(windowId: **number**, pointerStyle: PointerStyle, callback: AsyncCallback<**void**>): **void**; | 设置鼠标光标样式,改接口会影响指定窗口鼠标光标样式。 | +| pointer | **function** getPointerStyle(windowId: **number**, callback: AsyncCallback): **void**; | 查询鼠标光标样式。 | + +## 设置鼠标光标隐藏 + +用户在全屏观看视频时,可以调用鼠标光标的隐藏接口设置鼠标光标不可见,提升用户体验。 + +## 开发步骤 + +1. 应用切换到全屏播放。 +2. 在应用中调用鼠标光标隐藏接口隐藏光标。 +3. 应用退出全屏播放。 +4. 在应用中调用鼠标光标显示接口显示光标。 + +```js +import pointer from '@ohos.multimodalInput.pointer'; + +// 1.应用切换到全屏播放 +// 2.调用鼠标光标隐藏接口隐藏光标 +try { + pointer.setPointerVisible(false, (error) => { + if (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set pointer visible success.`); + }); +} catch (error) { + console.log(`The mouse pointer hide attributes is failed. ${JSON.stringify(error, [`code`, `message`])}`); +} + +// 3.应用退出全屏播放 +// 4.调用鼠标光标显示接口显示光标 +try { + pointer.setPointerVisible(true, (error) => { + if (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set pointer visible success.`); + }); +} catch (error) { + console.log(`Set pointer visible failed, ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## 设置鼠标光标样式 + +当开发者设计取色器特性时,可以将鼠标光标样式切换为取色器样式,完成取色后,设置鼠标光标样式为默认样式,该接口设置和查询当前应用内指定窗口的光标样式,总共可设置39种光标样式,具体参考[光标样式](../reference/apis/js-apis-pointer.md#pointerstyle9)。 + +### 开发步骤 + +1. 开发者使能取色功能。 +2. 调用窗口实例获取对应的窗口id。 +3. 设置鼠标光标样式为取色器样式。 +4. 取色结束。 +5. 设置鼠标光标样式为默认样式。 + +```js +import window from '@ohos.window'; + +// 1.开发者使能取色功能 +// 2.调用窗口实例获取对应的窗口id +window.getTopWindow((error, windowClass) => { + windowClass.getProperties((error, data) => { + var windowId = data.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 3.设置鼠标光标样式为取色器样式 + pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { + console.log(`Successfully set mouse pointer style`); + }); + } catch (error) { + console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); + } + }); +}); +// 4.取色结束 +window.getTopWindow((error, windowClass) => { + windowClass.getProperties((error, data) => { + var windowId = data.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 5.设置鼠标光标样式为默认样式 + pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { + console.log(`Successfully set mouse pointer style`); + }); + } catch (error) { + console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); + } + }); +}); +``` diff --git a/zh-cn/application-dev/faqs/Readme-CN.md b/zh-cn/application-dev/faqs/Readme-CN.md index 549b7bc2a8f3880a58b91e6e81bb5fa3ced80c50..8e60a76b28e1270a53e044fbddc5b403499e03e8 100644 --- a/zh-cn/application-dev/faqs/Readme-CN.md +++ b/zh-cn/application-dev/faqs/Readme-CN.md @@ -1,13 +1,20 @@ # 常见问题 +- [开发语言常见问题](faqs-language.md) - [Ability框架开发常见问题](faqs-ability.md) +- [应用程序包管理开发常见问题](faqs-bundle.md) +- [ArkUI组件(ArkTS)开发常见问题](faqs-ui-ets.md) +- [ArkUI Web组件(ArkTS)开发常见问题](faqs-web-arkts.md) - [UI框架(JS)开发常见问题](faqs-ui-js.md) -- [UI框架(ArkTS)开发常见问题](faqs-ui-ets.md) +- [公共事件与通知开发常见问题](faqs-event-notification.md) - [图形图像开发常见问题](faqs-graphics.md) - [文件管理开发常见问题](faqs-file-management.md) +- [媒体开发常见问题](faqs-media.md) - [网络与连接开发常见问题](faqs-connectivity.md) - [数据管理开发常见问题](faqs-data-management.md) - [设备管理开发常见问题](faqs-device-management.md) +- [DFX开发常见问题](faqs-dfx.md) +- [国际化开发常见问题](faqs-international.md) - [Native API使用常见问题](faqs-native.md) - [三四方库使用常见问题](faqs-third-party-library.md) - [IDE使用常见问题](faqs-ide.md) diff --git a/zh-cn/application-dev/faqs/faqs-ability.md b/zh-cn/application-dev/faqs/faqs-ability.md index ffc4e0123da0ff228305bee962807bd279193acd..e47016338696cda908002b817ed81ef2a2732f2d 100644 --- a/zh-cn/application-dev/faqs/faqs-ability.md +++ b/zh-cn/application-dev/faqs/faqs-ability.md @@ -1,16 +1,14 @@ # Ability框架开发常见问题 - - ## Stage模型中是否有类似FA模型的DataAbility的开发指导文档 适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 Stage模型中DataShareExtensionAbility提供了向其他应用共享以及管理其数据的方法。 -参考文档:[数据共享开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-datashare-guidelines.md) +参考文档:[数据共享开发指导](../database/database-datashare-guidelines.md) -## 拉起Ability为什么在界面上没反应? +## 拉起Ability在界面上没反应 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -22,11 +20,37 @@ Stage模型中DataShareExtensionAbility提供了向其他应用共享以及管 参考文档:[OpenHarmony版本转测试信息](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md) -## 调用方法的时候,如何解决方法内部的this变成undefined? +## 如何将Ability的UI界面设置成透明 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +将最上层容器组件背景色设置为透明,然后通过设置XComponent组件的opacity属性值为0.01来实现。 + + 示例: + +``` +build() { + Stack() { + XComponent({ + id: 'componentId', + type: 'surface', + }) + .width('100%') + .height('100%') + .opacity(0.01) + // 页面内容 + } + .width('100%') + .height('100%') + .backgroundColor('rgba(255,255,255, 0)') +} +``` + +## 调用方法的时候,如何解决方法内部的this变成undefined 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 -方式一:在调用方法的时候加上.bind(this); +方式一:在调用方法的时候加上.bind(this)。 方式二:使用箭头函数。 @@ -36,10 +60,10 @@ Stage模型中DataShareExtensionAbility提供了向其他应用共享以及管 Ability配置中缺少startWindowIcon属性配置,需要在module.json5中abilities中配置startWindowIcon。 -参考文档:[Stage模型配置文件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/stage-structure.md) +参考文档:[Stage模型配置文件](../quick-start/stage-structure.md) + +示例: - 示例: - ``` { "module": { @@ -59,4 +83,134 @@ Ability配置中缺少startWindowIcon属性配置,需要在module.json5中abil 使用Ability的onConfigurationUpdated回调实现,系统语言、颜色模式以及Display相关的参数,比如方向、Density,发生变化时触发该回调。 -参考文档:[Ability开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ability/stage-ability.md) +参考文档:[Ability开发指导](../ability/stage-ability.md) + +## Stage模型是否推荐用globalThis去获取Context + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +不推荐,Stage模型使用globalThis去获取Context是错误的使用方式。在Stage模型中,整个应用进程共用一个js虚拟机实例,其中可以运行多个Ability实例,共用一个global对象。在同一个js虚拟机内的不同的Ability中使用globalThis获取Context,存在被覆盖从而发生错误的风险。 + +推荐使用方式参考:[Stage模型的Context详细介绍](../ability/context-userguide.md#stage模型的context详细介绍)。 + +## 如何在应用A中去获取应用B的Hap包的安装路径 + +适用于:OpenHarmony SDK 3..0以上版本, API9 Stage模型 + +首先需要申请系统权限,具体参看文档:[自动化签名](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465)。导入bundle模块,通过调用bundle.getApplicationInfo()接口,通过包名获取应用信息。然后通过application.moduleSourceDirs获取应用存储路径。 + +## 调用方使用startAbilityForResult,被调用方如何返回数据 + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +被调用方使用AbilityContext.terminateSelfWithResult方法,销毁被调用方ability,传递参数给startAbilityForResult回调函数,具体用法请参考[AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextterminateselfwithresult) + +## FA卡片上架后在用户的服务中心展示时可否触发生命周期,从而实现用户没有打开过FA应用的情况下获取到用户的登录信息? + +适用于:OpenHarmony SDK 3.2.5.5版本, API8 FA模型 + +服务卡片在添加卡片后就触发了oncreat()生命周期,在不启用app的情况下也可以显示相关的用户信息-静默登录,但服务卡片目前要在app安装之后手动添加。 + +## 如何获取context + +适用于:OpenHarmony SDK 3.2.7.5版本, API9 Stage模型 + +在MainAbility.ts文件中可以直接使用this.context获取context,在组件页面中可以使用getContext(this)获取context。 + +## 访问控制管理模块abilityAccessCtrl中grantUserGrantedPermission方法在API8语法校验提示未定义 + +适用于:OpenHarmony SDK 3.0版本, API8 FA模型 + +当前SDK有fullSDK和publicSDK两个版本,IDE默认下载的是publicSDK。其中,publicSDK版本不会包含系统API,如果要用系统API,需要使用fullSDK。具体参考[full-SDK替换指南](../quick-start/full-sdk-switch-guide.md)。 + +## public sdk支持哪几种ExtensionAbility(ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility) + +适用于:OpenHarmony SDK 3.2.5.6版本, API9 Stage模型 + +上述ExtensionAbility 中,public sdk 仅可以使用FormExtensionAbility。ServiceExtensionAbility和DataShareExtensionAbility 为系统接口,需要使用full sdk。 + +Public SDK : 面向应用开发者提供,不包含需要使用系统权限的系统接口。 + +Full SDK : 面向OEM厂商提供,包含了需要使用系统权限的系统接口。 + +## 服务卡片无法循环播放gif图 + +适用于:OpenHarmony SDK 3.2.5.6版本, API9 Stage模型 + +目前暂不支持播放GIF图片。 + +## 如何通过卡片点击实现业务登录场景 + +适用于:OpenHarmony SDK 3.2.5.5版本, API9 Stage模型 + +可以通过点击卡片拉起响应的Ability后,通过Ability来实现业务登录场景。 + +## 如何跳转到设置中应用详情页面 + +使用于:OpenHarmony SDK 3.2.6.5版本 + +参考如下代码实现,示例: + +``` +this.context.startAbility( +{ + action: "action.settings.app.info", + parameters: { "settingsParamBundleName": "your app bundlename" } +}) +``` + +## 如何监听屏幕旋转 + +使用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +参考如下代码实现,示例: + +``` +let listener = mediaquery.matchMediaSync('(orientation: landscape)') +onPortrait(mediaQueryResult) { +if (mediaQueryResult.matches) { +// do something here + } else { +// do something here + } +} +listener.on('change', onPortrait) +``` + +## 如何控制checkbox选中切换过程中阴影背景的大小 + +使用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +设置checkbox组件padding属性,可控制阴影大小 + +## 如何设置卡片背景为透明 + +适用:OpenHarmony SDK 3.2.5.5版本 + +1. 在卡片根目录widget新建widget/resources/styles/default.json文件 + +2. 在default.json中书写如下代码: + +``` +{ + "style": { + "app_background": "#00000000" + } +} +``` + +## FA卡片如何的传参和接参 + +适用:OpenHarmony SDK 3.2.5.5版本 + +使用featureAbility.getWant()和featureAbility.getContext()在json文件中router跳转发送数据,在js文件中用featureAblity方法接收 + +## router.disableAlertBeforeBackPage和router.enableAlertBeforeBackPage怎么触发 + +适用:OpenHarmony SDK 3.2.5.5版本 + +需要满足两个条件 + +1. router.disableAlertBeforeBackPage和router.enableAlertBeforeBackPage类似一个开关,disableAlertBeforeBackPage是返回上一级页面时关闭弹窗提示,enableAlertBeforeBackPage是打开弹窗提示,默认是关闭的,当你需要使用时,首先要在一个函数里面开启功能,然后再执行跳转 + +2. 必须要使用系统的返回按键才能触发效果。 diff --git a/zh-cn/application-dev/faqs/faqs-bundle.md b/zh-cn/application-dev/faqs/faqs-bundle.md new file mode 100644 index 0000000000000000000000000000000000000000..2a3672e8ccb4a50f9a99d7ec669d5bb04bbb8bf7 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-bundle.md @@ -0,0 +1,31 @@ +# 应用程序包管理开发常见问题 + +## 如何获取应用配置的versionCode和versionName + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +通过\@ohos.bundle模块buniple.getBundleInfo()接口获取包信息bundleInfo,然后分别通过bundleInfo.versionCode、bundleInfo.versionName + +参考文档:[Bundle模块](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo) + +## 如何获取应用自身的bundleName + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +通过可以context.abilityInfo.bundleName获取。 + +参考文档:[AbilityContext](../reference/apis/js-apis-ability-context.md)、[AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) + +## 如何获取应用图标 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +通过\@ohos.bundle模块 getAbilityIcon 接口获取,需要配置权限:ohos.permission.GET_BUNDLE_INFO。 + +参考文档:[Bundle模块](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo) + +## 如何判断某个应用是否为系统应用 + +使用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +使用bundle模块的getApplicationInfo接口获取待检验的应用的ApplicaitonInfo,根据ApplicaitonInfo中systemApp字段判断,若为true,则是系统应用,否则为非系统应用。 diff --git a/zh-cn/application-dev/faqs/faqs-connectivity.md b/zh-cn/application-dev/faqs/faqs-connectivity.md index baa3514733cb5f61627b7b90362bafac9fa9f16d..c50e44cc0fae760cb9f2b3cc6cba87d541dece44 100644 --- a/zh-cn/application-dev/faqs/faqs-connectivity.md +++ b/zh-cn/application-dev/faqs/faqs-connectivity.md @@ -1,8 +1,6 @@ # 网络与连接开发常见问题 - - -## Post请求时,extraData支持哪几种的数据格式? +## 网络请求中extraData支持哪几种的数据格式 适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 @@ -14,13 +12,13 @@ extraData代表发送请求的额外数据,支持如下数据: 3. 开发者传入string对象,开发者需要自行编码,将编码后的string传入。 -## 如何理解http请求的错误码28? +## 如何理解http请求的错误码28 适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 错误码28代表CURLE_OPERATION_TIMEDOUT,操作超时。网络请求底层使用libcurl库,更多错误码可以查看相应文档。 -参考文档:[开发指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-http.md#response%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) +参考文档:[Response常用错误码](../reference/apis/js-apis-http.md#response常用错误码)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) ## \@ohos.net.http.d.ts的response错误码返回6是什么意思? @@ -28,4 +26,79 @@ extraData代表发送请求的额外数据,支持如下数据: 6表示地址无法解析主机,可以尝试ping一下request中的url,确认是否可以ping通。 -更多错误码参考[Response常用错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-http.md#response%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) +更多错误码参考[Response常用错误码](../reference/apis/js-apis-http.md#response常用错误码)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) + +## 调用camera拍摄的照片怎么上传到服务器 + +适用于:所有版本 + +具体开发参考文档:[上传下载](https://gitee.com/openharmony/app_samples/tree/master/Network/UploadDownload) + +## OpenHarmony的http接口如何设置cookie + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +HttpRequestOptions中的header是一个Object类型,可以直接在header里设置cookie,具体开发参考文档:[数据请求](../reference/apis/js-apis-http.md#request)。 + +## http请求的官方示例代码里的extra data部分怎么写 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +1. 鼠标移到extraData, ctrl+鼠标左键,跳转到sdk中,里面有关于extraData的传参说明。可以发现文档中对extraData的定义是这样的 extraData?: string | Object,也就是extraData支持string 和 Object两种类型。 + +2. 这两种写法都可以实现: + a.extraData:"data to send"; + b. extraData:{ data:"data to send", }, + +## 设备连接wifi后,如何获取当前设备的IP地址 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +使用wifi模块获取ipInfo,然后转换为IP常用格式,注意wifi.getIpInfo()接口需要权限 ohos.permission.GET_WIFI_INFO。 + +示例: + + +``` +import wifi from '@ohos.wifi' +@Entry +@Component +struct Page { + @State ip: string = '点击获取ip' + + resolveIP(ip) { + if (ip < 0 || ip > 0xFFFFFFFF) { + throw ("The number is not normal!"); + } + return (ip >>> 24) + "." + (ip >> 16 & 0xFF) + "." + (ip >> 8 & 0xFF) + "." + (ip & 0xFF); + } + + build() { + Row() { + Column() { + Text(this.ip) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + this.ip = this.resolveIP(wifi.getIpInfo().ipAddress) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +## 如何判断当前是否有网络 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +通过如下hasDefaultNet接口判断是否有网络,注意需要申请 ohos.permission.GET_NETWORK_INFO 权限 + + +``` +connection.hasDefaultNet().then((has)=> { + console.log("hasDefaultNet " + JSON.stringify(has)) +}) +``` diff --git a/zh-cn/application-dev/faqs/faqs-data-management.md b/zh-cn/application-dev/faqs/faqs-data-management.md index 99893fe1a8388fe32310b17dea4561e162b3e754..fe93fd317d45da13a673fc7ea798f604ecf59ba6 100644 --- a/zh-cn/application-dev/faqs/faqs-data-management.md +++ b/zh-cn/application-dev/faqs/faqs-data-management.md @@ -16,6 +16,58 @@ PixelMap应该被转换成相应的ArrayBuffer再放进数据库。 示例: -```shell + +``` hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db ``` + +## 数据库在系统层面是否有锁机制,开发过程中是否需要关系数据库加锁问题 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +系统提供的分布式数据服务、关系型数据库和首选项均有锁机制,开发者无需关注。 + +## 数据库中加事务与不加事务的区别? + +适用于:所有版本 + +在rdb中进行数据操作时,有可能会导致操作失败,出现意料之外的情况。当对数据库进行大量操作时,此种情况会导致部分数据操作失败,部分操作成功,导致部分数据丢失,可能会导致应用程序发生异常甚至崩溃。加事务后,则会将某一批操作组合成一个整体,要么同时成功,要么同时失败,则不会导致强关联的数据部分缺失的情况出现。 + +## 关系型数据库rdb支持哪些数据类型? + +适用于:OpenHarmony SDK 3.0版本以上,API9 Stage模型 + +关系型数据库rdb支持的数据类型有:number、string、boolean。其中number为数组类型,支持Double,Long,Float,Int,Int64,最大精度为十进制17位数字。 + +## 如何查看数据库db文件 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +1. 执行 hdc_std shell 命令进入系统 + +2. 找到绝对路径:/data/app/el2/<userId默认是100>/database/<bundleName> + 或找到沙箱路径: + + a. 执行 ps -ef | grep hapName 命令找到对应应用的进程ID, + + b. 数据库沙箱路径为:/proc/<应用进程ID>/root/data/storage/el2/database/。 + +3. 在数据库的绝对路径或者沙箱路径下执行 find ./ -name "\*.db" 即可找到数据库文件。 + +## 如何存储长文本数据 + +适用于:OpenHarmony SDK 3.2.5.5版本,API 9 + +- 首选项Preferences数据中的Value为string类型时最大支持8192字节。 + +- 分布式数据管理KV数据模型Value最大支持4M。 + +参考文档:[首选项概述](../database/database-preference-overview.md)、[分布式数据服务概述](../database/database-mdds-overview.md) + +## Stage模型数据共享DataShare开发 + +适用于:OpenHarmony SDK 3.2.5.5版本,API 9 + +Stage模型DataShare不可与FA模型DataAbility混用,连接的服务端应用需使用DataShareExtensionAbility实现。 + +参考文档:[数据共享开发指导](../database/database-datashare-guidelines.md) diff --git a/zh-cn/application-dev/faqs/faqs-development-board.md b/zh-cn/application-dev/faqs/faqs-development-board.md index 3ab491c0dc6b42b0ca2e91e7a55965f51f9d34ad..d6965edfbca602392190f3518925b9eb2238fc08 100644 --- a/zh-cn/application-dev/faqs/faqs-development-board.md +++ b/zh-cn/application-dev/faqs/faqs-development-board.md @@ -1,6 +1,4 @@ -# 开发板 - - +# 开发板使用常见问题 ## 如何获取开发板上截屏图片? @@ -27,6 +25,7 @@ 适用于:IDE 3.0.0.991 1. 给预览器新建Profile + ![zh-cn_image_0000001361254285](figures/zh-cn_image_0000001361254285.png) 2. 新建Profile的具体参数可参考如下配置: diff --git a/zh-cn/application-dev/faqs/faqs-device-management.md b/zh-cn/application-dev/faqs/faqs-device-management.md index 7a1ca35602e3be567b3afeceb91054f86cf9f0cb..bb4bb7d211450089c05f9bb09d6669b0c6fe5747 100644 --- a/zh-cn/application-dev/faqs/faqs-device-management.md +++ b/zh-cn/application-dev/faqs/faqs-device-management.md @@ -1,16 +1,14 @@ # 设备管理开发常见问题 - - ## 如何获取设备的dpi值 适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 -导入@ohos.display包,通过getDefaultDisplay方法获取。 +导入\@ohos.display包,通过getDefaultDisplay方法获取。 示例: - + ``` import display from '@ohos.display'; display.getDefaultDisplay((err, data) => { @@ -22,3 +20,31 @@ display.getDefaultDisplay((err, data) => { console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); }); ``` + +## 如何获取当前运行设备类型(穿戴、平板等) + +适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 + +导入\@ohos.deviceInfo包,然后通过deviceInfo.deviceType获取设备类型。 + +参考文档:[设备信息](../reference/apis/js-apis-device-info.md) + +## 如何获取设备系统版本 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过[deviceInfo](../reference/apis/js-apis-device-info.md)对象的osFullName属性获取设备系统版本。 + +## OpenHarmony设备如何获取UDID? + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +1、如果想获取连接设备的udid,可使用 hdc shell bm get --udid命令; + +2、如果想在代码中获得,参考文档 [udid](../reference/apis/js-apis-device-info.md) 。 + +## 开发快捷键功能 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +快捷键功能开发请使用组合按键api,具体可参考[组合按键(InputConsumer)](../reference/apis/js-apis-inputconsumer.md) diff --git a/zh-cn/application-dev/faqs/faqs-dfx.md b/zh-cn/application-dev/faqs/faqs-dfx.md new file mode 100644 index 0000000000000000000000000000000000000000..a3554754afbb91ddd6a4acaaf094eae06105375e --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-dfx.md @@ -0,0 +1,54 @@ +# DFX开发常见问题 + +## 程序打开直接崩溃了,如何定位问题 + +使用于:OpenHarmony SDK 3.2.5.5版本 + +1.通过业务日志打印,定位崩溃的代码位置。 + +2.通过Crash文件查看报错信息,Crash文件路径是:/data/log/faultlog/faultlogger/。 + +## UiTest测试框架无法获取控件问题 + +使用于:OpenHarmony SDK 3.2.5.5版本 + +检查系统配置项 persist.ace.testmode.enabled 是开启。 + +通过hdc_std shell param get persist.ace.testmode.enabled 查看,若配置项为0, + +可通过命令hdc_std shell param set persist.ace.testmode.enabled 1 开启配置。 + + +## C++代码中hilog的格式参数类型为%d或者%s时,日志打印为何显示private + +直接使用%d、%s等格式化参数时,标准系统默认使用private替换真实数据进行打印,防止数据泄露。如果需要打印出真实数据,需要使用%{public}d替换%d或者%{public}s替换%s。 + +## 如何解决hilog.debug日志无法打印 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过hdc_std命令 hdc_std shell hilog -b D开启调试开关 + +## 应用如何打印日志是使用hilog还是console,hilog接口参数domain的设置范围是什么 + +适用于:OpenHarmony SDK 3.2.2.5版本 + +推荐使用[hilog日志系统](../reference/apis/js-apis-hilog.md)进行日志打印,接口参数domain的设置范围可以参考[开发指南](../reference/apis/js-apis-hilog.md#hilogisloggable)。 + +## hilog日志打印长度限制是多少,是否可以配置 + +适用于:OpenHarmony SDK 3.2.2.5版本 + +日志打印的长度限制为1024个字符,该长度不能配置。 + +## hilog接口的tag参数是否支持用空格隔开的多个字符串 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +不支持。 + +## hilog中没有使用{public}标识的数据,如何打印真实数据 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +使用命令:hdc_std shell hilog -p off diff --git a/zh-cn/application-dev/faqs/faqs-event-notification.md b/zh-cn/application-dev/faqs/faqs-event-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..a035a5890812c27cd910dd44cea913b3f7abc0c2 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-event-notification.md @@ -0,0 +1,48 @@ +# 公共事件与通知开发常见问题 + +## emitter数据大小限制 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +emitter数据大小限制不超过10240。 + +## 如何实现点击Notification通知打开对应App + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过配置Notification.publish发布通知接口的参数NotificationRequest中wantAgent属性实现 + +参考文档:[Notification](../reference/apis/js-apis-notification.md#notificationpublish)、[WantAgent](../reference/apis/js-apis-wantAgent.md) + +示例: + +``` +import WantAgent from '@ohos.wantAgent'; + +async function publishNotification() { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.notification", + abilityName: "MainAbility", + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + } + const wantAgent = await WantAgent.getWantAgent(wantAgentInfo) + let contentType = Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; + await Notification.publish({ + content: { + contentType: contentType, + normal: { + title: "测试标题", + text: "测试内容", + } + }, + id: 1, + wantAgent: wantAgent + }) + prompt.showToast({ message: "发送成功" }) +} +``` diff --git a/zh-cn/application-dev/faqs/faqs-file-management.md b/zh-cn/application-dev/faqs/faqs-file-management.md index a6caa4a7064430e4b0c2a2fb49523a8a433ec564..67e62ffbed453a16247afdc5314a979764f278ba 100644 --- a/zh-cn/application-dev/faqs/faqs-file-management.md +++ b/zh-cn/application-dev/faqs/faqs-file-management.md @@ -1,6 +1,63 @@ # 文件管理开发常见问题 +## fileio.rmdir是递归删除吗? +适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 + +是递归删除。 + + +## 如何实现如果文件不存在则创建文件 + +适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 + +可以通过调用函数fileio.open(filePath, 0o100, 0o666)来实现,第二个参数0o100表示若文件不存在,则创建文件。使用该选项时必须指定第三个参数 mode。 + +## 使用fileio进行文件复制,传入沙箱路径报错call fail callback fail, code: 202, data: json arguments illegal) + +适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 + +使用fileio模块进行文件复制时,文件路径前缀中不能以“file:///”开头。 + +## fileIo将数据写入流文件writeSync接口,length传参问题 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +一个中文字符length为3,英文字符为1,当前buffer为string类型时,length项需要开发者手动换算;如果要写入全部内容,可直接忽略length项,length长度超长时会导致接口报错。 + +## 如何读取应用沙箱之外的文件 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +fileio中接口入参为path时只能是从context获取到的本应用沙箱路径,若要访问其他路径的数据,如公共数据图片视频等,需要通过数据所有者打开文件返回fd进行操作。 + +比如向mediaLibrary请求读取/写入某文件,然后通过打开代表特定文件的URI后返回的fd进行操作,操作步骤如下: + +1. 通过媒体查询获取文件fileAsset对象; + +2. 通过fileAsset.open方法返回的fd; + +3. 将fd作为fileIo接口参数进行文件读写操作; + +## 如何解决文件的中文内容乱码 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +读取文件内容的buffer数据后,通过util.TextDecoder对文件内容进行解码。 + +示例: + +``` +import util from '@ohos.util' +async function readFile(path) { + let stream = fileio.createStreamSync(path, "r+"); + let readOut = await stream.read(new ArrayBuffer(4096)); + let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true }); + let buffer = new Uint8Array(readOut.buffer) + let readString = textDecoder.decode(buffer, { stream: false }); + console.log("[Demo] 读取的文件内容:" + readString); +} +``` ## 调用媒体库getAlbums方法,没有收到返回,也没有捕获到异常是为什么 @@ -34,3 +91,21 @@ getAlbums方法需要权限:ohos.permission.READ_MEDIA,从[OpenHarmony权限 }) } ``` + +## 如何解决多次通过媒体库FetchFileResult获取文件应用崩溃 + +适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 + +通过FetchFileResult.close()方法,在FetchFileResult对象每次调用完,释放并使其失效。 + +## 在Stage模型下调用mediaLibrary.getMediaLibrary()接口,IDE报错 + +适用于:OpenHarmonySDK 3.25.5版本,API9 Stage模型 + +Stage模型下,获取媒体库实例应该调用mediaLibrary.getMediaLibrary(context: Context)。 + +## 调用mediaLibrary.getFileAssets()接口返回的内容如何排序 + +适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 + +通过[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)对象参数里面的order属性进行排序。 diff --git a/zh-cn/application-dev/faqs/faqs-graphics.md b/zh-cn/application-dev/faqs/faqs-graphics.md index f72711aefb13db79150b749d9a3e6ed470597d0c..61d9981d2befa6ee795700da926e13a84cdec0a6 100644 --- a/zh-cn/application-dev/faqs/faqs-graphics.md +++ b/zh-cn/application-dev/faqs/faqs-graphics.md @@ -1,8 +1,6 @@ # 图形图像开发常见问题 - - -## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 +## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -13,3 +11,80 @@ 适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 导入\@ohos.window模块,开发者可以使用window.setSystemBarProperties()接口设置状态栏样式属性,达到自定义样式的效果。 + +## 如何隐藏状态栏,实现沉浸式效果 + +适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 + +1. 可以在onWindowStageCreate方法获取windowClass对象。 + + ``` + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[Demo] MainAbility onWindowStageCreate") + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window.') + return; + } + // 获取到窗口对象 + globalThis.windowClass = data; + }) + } + ``` + +2. 设置窗口全屏,隐藏状态栏。 + + ``` + globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { + 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)); + }); + ``` + +## 如何获取窗口的宽高信息 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +通过\@ohos.window模块,可以使用getProperties()接口获取窗口属性,然后通过窗口属性的windowRect获取窗口宽高信息 + +示例: + + +``` +let promise = windowClass.getProperties(); +promise.then((data)=> { + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data.windowRect)); +}).catch((err)=>{ + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); +}); +``` + +## 如何设置系统状态栏颜色 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +参考如下方式实现,示例: + + +``` +window.getTopWindow(globalThis.mainContext).then(win => { + var systemBarProperties = { + statusBarColor: '#19B6FF', // 状态栏背景颜色 + navigationBarColor: '#19B6FF', // 导航栏背景颜色 + isStatusBarLightIcon: false, // 状态栏图标是否为高亮状态。 + isNavigationBarLightIcon: true, // 导航栏图标是否为高亮状态。 + statusBarContentColor: '#0D0500', // 状态栏文字颜色 + navigationBarContentColor: '#FFA500' // 导航栏文字颜色 + }; + win.setSystemBarProperties(systemBarProperties).catch(err => { + INDEX_LOGGER.info(`set System Bar Properties failed:${err}`) + }) +}) +.catch(err => { + INDEX_LOGGER.info(`get top window failed:${err}`) +}) +``` diff --git a/zh-cn/application-dev/faqs/faqs-hdc-std.md b/zh-cn/application-dev/faqs/faqs-hdc-std.md index 5caf5db008a993bca4cbeb8e49f0e0495d716f05..3690a4d9c69c27514f233c00d8bd62640241d563 100644 --- a/zh-cn/application-dev/faqs/faqs-hdc-std.md +++ b/zh-cn/application-dev/faqs/faqs-hdc-std.md @@ -1,8 +1,6 @@ # hdc_std命令使用常见问题 - - -## 日志的常用命令 +## 日志的常用命令 适用于:OpenHarmony SDK 3.2.2.5版本 @@ -12,7 +10,7 @@ 抓取日志:hdc_std shell hilog > log.txt -## 日志限流怎么规避 +## 日志限流怎么规避 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -26,38 +24,64 @@ 执行完命令后重启DevEco Studio。 -## 应用如何打印日志是使用hilog还是console,hilog接口参数domain的设置范围是什么? +## 用IDE安装HAP包到开发板上无法打开 -适用于:OpenHarmony SDK 3.2.2.5版本 +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 -推荐使用[hilog日志系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-hilog.md)进行日志打印,接口参数domain的设置范围可以参考[开发指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-hilog.md#hilogisloggable)。 +请检查sdk和开发板烧录的系统版本是否一致,推荐取同一天的sdk和系统版本。 -## hilog日志打印长度限制是多少,是否可以配置 +## 如何通过hdc命令上传文件 适用于:OpenHarmony SDK 3.2.2.5版本 -日志打印的长度限制为1024个字符,该长度不能配置。 +可以使用hdc_std file send上传文件。 -## 为什么有时候直接用IDE安装HAP包到开发板上无法打开? +## 如何让RK3568开发板不熄屏 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 -请检查sdk和开发板烧录的系统版本是否一致,推荐取同一天的sdk和系统版本。 +输入命令hdc_std shell "power-shell setmode 602" + +## 如何通过命令启动Ability + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +输入命令hdc_std shell aa start -a AbilityName -b bundleName -m moduleName + +## 如何修改开发板中文件目录为可读写权限 -## 如何通过hdc命令上传文件 +适用于:OpenHarmony SDK 3.2.5.6版本,API9 Stage模型 + +输入命令 hdc_std shell mount -o remount,rw / + +## 如何解决hdc_std file recv 使用报错:Unkonw file option -r + +适用于:OpenHarmony SDK 3.2.5.6版本,API9 Stage模型 + +1. 使用设备镜像或者同版本SDK中配套的hdc工具进行使用。 + +2. hdc工具指定的路径不要包含中文和空格。 + +## 如何使用命令卸载应用 适用于:OpenHarmony SDK 3.2.2.5版本 -可以使用hdc_std file send上传文件。 +输入命令hdc_std uninstall [-k] [package_name] -## 如何让RK3568开发板不熄屏? +## 如何查看系统是32位还是64位 -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 +适用于:OpenHarmony SDK 3.2.5.5版本 -输入命令hdc_std shell "power-shell setmode 602" +使用命令:hdc_std shell getconf LONG_BIT -## 如何通过命令启动Ability? +若返回64则为64位系统,否则为32位系统。 -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 +## 如何查看组件树结构 -输入命令hdc_std shell aa start -a AbilityName -b bundleName -m moduleName +适用于:OpenHarmony SDK 3.2.5.5版本 + +1. 使用命令hdc_std shell 进入命令行界面。 + +2. 输入 aa dump -a 找到abilityID。 + +3. aa dump -i [abilityID] -c -render 查看组件树。 diff --git a/zh-cn/application-dev/faqs/faqs-ide.md b/zh-cn/application-dev/faqs/faqs-ide.md index c9b32df07511cccbb9c1607d5bb121b635372457..9d2cd9b7db09275aeedd988525bf663e7440d6b0 100644 --- a/zh-cn/application-dev/faqs/faqs-ide.md +++ b/zh-cn/application-dev/faqs/faqs-ide.md @@ -1,8 +1,6 @@ # IDE使用常见问题 - - -## 如何解决报错“npm ERR! code SELF_SIGNED_CERT_IN_CHAIN”? +## 如何解决报错“npm ERR! code SELF_SIGNED_CERT_IN_CHAIN” 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -10,10 +8,73 @@ 2. 在Dev Eco Studio terminal中执行npm install。 -## 手工更新DevEco的SDK后,编译HAP报错“Cannot find module 'xxx\ets\x.x.x.x\build-tools\ets-loader\node_modules\webpack\bin\webpack.js'” +## 手工更新DevEco的SDK后,编译HAP报错“Cannot find module 'xxx\ets\x.x.x.x\build-tools\ArkTS-loader\node_modules\webpack\bin\webpack.js'” 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 1. 到SDK的ets\x.x.x.x\build-tools\ets-loader目录下执行npm install; -2. 到SDK的js\x.x.x.x\build-tools\ace-loader目录下执行npm install。 完成步骤后重新编辑既可。 +2. 到SDK的js\x.x.x.x\build-tools\ace-loader目录下执行npm install。 完成步骤后重新编辑。 + +## 如何通过命令行打包HAP + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +方式一:运行hvigor assembleHap。 + +方式二:在工程的package.json的scripts中,定义构建任务脚本后,运行npm buildOhosHaps。“buildOhosHaps”字段可以自定义。 + + +``` +"scripts": { + "buildOhosHaps": "hvigor assembleHap" +}, +``` + +## DevEco创建新工程为什么选不到API9 + +适用于:DevEco Studio 3.0 Beta4 3.0.0.993(B06)版本 + +创建新工程的时候,首先要选择OpenHarmony页签再创建工程就可以选到API9。 + +## 下载时收不到回调且无法返回错误码 + +适用于:OpenHarmony所有版本 + +1. 重装hdc命令: hdc_std重裝 拉起 设备连接 + +2. 关闭日志限流 :hdc_std shell hilog -Q pidoff 打开" + +## IDE点击run按钮后,报错:error: unknow option. usage: aa start <options> + +适用于:OpenHarmony SDK 3.2.5.6版本,API9 Stage模型 + +报错原因:aa命令参数错误,执行打开应用操作报错。 + +有2种处理方法: + +1. 检查SDK版本和OS版本,确保SDK版本和OS版本一致。 + +2. 点击设备上app图标,手动启动app进行使用。 + +## IDE运行app报错:The hdc_std version of the SDK does not match the hdcd version of the device. + +适用于:OpenHarmony SDK 3.2.5.6版本,API9 Stage模型 + +hdc 和 hdcd版本不匹配 ,请更新IDE至Dev Eco 3.0.1.993及以上版本。 + +旧版本IDE检测不匹配会拦截安装,新版本IDE仅提醒不影响正常使用。 + +## 如何在OpenHarmony 的SDK中加入自定义的\*.d.ts文件 + +适用于:OpenHarmony SDK 3.1.7.7版本 , API8 FA模型 + +将dts文件命名为\@ohos.xxxx.d.ts , 放入SDK的路径中,重启IDE。 + +引入时会有代码提醒。 + +## 如何替换full-SDK + +适用于:OpenHarmony SDK 3.2.7.5版本 + +参考文档[full-SDK替换指南](../quick-start/full-sdk-switch-guide.md) diff --git a/zh-cn/application-dev/faqs/faqs-international.md b/zh-cn/application-dev/faqs/faqs-international.md new file mode 100644 index 0000000000000000000000000000000000000000..bbef24399ad9dfd0c33389edf7b4a66827b87b60 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-international.md @@ -0,0 +1,19 @@ +# 国际化开发常见问题 + +## AppScope中的资源如图片,文字等的引用方式是什么 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过$r('app.type.name')的形式来引用,type代表资源类型,如color,string,media等,name代表资源命名 + +## Resource类型转为string + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +Resource为string支持限定词目录使用this.context.resourceManager.getStringSync(\\$r('app.string.test').id),可以同步转换,不支持\$r('app.string.test', 2)方式。更多用法请参考[ResourceManager(资源管理)](../reference/apis/js-apis-resource-manager.md#getstringsync9) + +## form_config.json文件中使用$引用常量为什么不生效 + +适用于:OpenHarmony SDK 3.2.6.5, API9 Stage模型 + +form_config.json文件中不支持使用$引用常量。 diff --git a/zh-cn/application-dev/faqs/faqs-language.md b/zh-cn/application-dev/faqs/faqs-language.md new file mode 100644 index 0000000000000000000000000000000000000000..bbbdae095eea938dc6fc139263fda25b5545c940 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-language.md @@ -0,0 +1,287 @@ +# 开发语言常见问题 + +## TS语言在生成器函数中编译失败,有哪些使用限制 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +TS语言的使用在生成器函数中存在以下限制: + +- 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用; + +- 这些表达式中的任何一个都不能导致任何应用程序状态变量(\@State、\@Link、\@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为; + +- 生成器函数内部不能有局部变量。 + +上述限制都不适用于事件处理函数(例如onClick)的匿名函数实现。 + +错误示例: + + +``` +build() { + let a: number = 1 // invalid: variable declaration not allowed + Column() { + Text('Hello ${this.myName.toUpperCase()}') // ok. + ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place + } + buildSpecial() // invalid: no function calls + Text(this.calcTextValue()) // this function call is ok. +} +``` + +## 如何动态替换掉资源文件中的“%s”占位符 + +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +在应用中,通过"$r('app.string.xx')"的形式引用应用资源,$r的第二个参数可用于替换%s占位符。 + + 示例: + +``` +build() { + //do something + //引用的string资源,$r的第二个参数用于替换%s + Text($r('app.string.entry_desc','aaa')) + .fontSize(100) + .fontColor(Color.Black) + //do something +} +``` + +## 如何读取Resource中的xml文件并转化为String类型 + +适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 + +1. 通过resourceManager的RawFile接口获取Uint8Array格式数据。 + +2. 通过String.fromCharCode将Uint8Array格式数据转化为String类型。快快快 + +参考文档:[资源管理](../reference/apis/js-apis-resource-manager.md) + +示例: + + +``` +resourceManager.getRawFile(path, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + let xml = String.fromCharCode.apply(null, rawFile) + } +}); +``` + +## 如何将Resource资源对象转成string类型 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +通过\@ohos.resourceManager模块 resourceManager.getString()方法获取字符串。 + +参考文档:[资源管理](../reference/apis/js-apis-resource-manager.md#getstring) + +## class全局静态变量无法使用的问题 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +Page和Ability打包后会对import的对象分别形成两个不同的闭包,即打包出两个Global对象。因此,所引用的静态变量并不是同一对象,所以无法通过class静态变量方式定义全局变量。建议使用AppStorage进行全局变量管理。 + +参考文档:[应用程序的数据存储](../quick-start/arkts-state-mgmt-application-level.md) + +## Stage模型下如何获取资源 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包,此方式FA模型不适用。 + +示例: + + +``` +const context = getContext(this) as any +context + .resourceManager + .getString($r('app.string.entry_desc').id) + .then(value => { + this.message = value.toString() +}) +``` + +## 如何实现页面加载前从接口获取数据 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +aboutToAppear函数中使用异步接口获取页面数据,使用\@State修饰变量,数据获取完成后根据变量自动刷新页面。 + + +``` +@Entry +@Component +struct Test6Page { + // 数据获取成功,会自动刷新页面 + @State message: string = 'loading.....' + aboutToAppear(){ + // 模拟异步接口获取数据 + setTimeout(()=>{ + this.message = 'new msg' + },3000) + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +## worker线程与主线程是否运行在相同的全局上下文中 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +worker线程与主线程不在同一个上下文中,它们使用数据通信的方式交互。 + +## OpenHarmony上url编码使用哪个接口 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +使用全局函数encodeURI进行编码,使用decodeURI进行解码。例如空格字符,编码后为%20。 + +## OpenHarmony有解析xml的接口吗 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +使用ConvertXML的convert接口可以将xml文本解析为JavaScript对象。参考文档:[convertxml API文档](../reference/apis/js-apis-convertxml.md) + +## 应用图标一多设置 + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +借助资源限定词能力,实现应用图标的一多配置,具体使用参考[资源使用](../key-features/multi-device-app-dev/resource-usage.md) + +## Stage模型资源配置文件string.json文件中支持配置占位符吗 + +适用于:OpenHarmony SDK3.2.6.3, API9 Stage模型 + +资源配置文件string.json文件本身不支持配置占位符,可以在对应的页面中通过定义变量,在实际组件使用Resources和变量拼接的方式达到实现占位符的同等效果。 + +## OpenHarmony的systemTime.getCurrentTime()接口和JS的new Date().getTime()有区别吗 + +适用于:OpenHarmony SDK3.2.6.3, API9 Stage模型 + +systemTime.getCurrentTime(false)和new Date().getTime()一样,都是返回1970年1月1日至今的毫秒数;systemTime.getCurrentTime(true)返回1970年1月1日至今的纳秒数。两种方式都是系统时间。 + +## \@BuilderParam装饰器,组件传参问题 + +适用于:OpenHarmony SDK3.2.6.5, API9 Stage模型 + +对\@BuilderParam修饰的属性进行赋值时不带参数(如:content: this.specificParam),则此属性的类型需定义成无返回值的函数(如:\@BuilderParam content: () => void);若带参数(如:callContent: this.specificParam1("111")),则此属性的类型需定义成any(如:\@BuilderParam callContent: any;),具体用法请参考[BuilderParam](../ui/ts-component-based-builder.md)。 + +## ArkTS如何把string转成byte数组 + +适用于:所有版本 + +参考如下代码实现,示例: + + +``` +function stringToByte(str) { + var bytes = new Array(); + var len,c; + len = str.length; + for(var i = 0;i= 0x010000 && c<= 0x10FFFF) { + bytes.push(((c>>18) & 0x07) | 0xf0); + bytes.push(((c>>12) & 0x3F) | 0x80); + bytes.push(((c>>6) & 0x3f) | 0x80); + bytes.push((c & 0x3F) | 0x80); + } else if(c >= 0x000800 && c<= 0x00FFF){ + bytes.push(((c>>12) & 0x07) | 0xf0); + bytes.push(((c>>6) & 0x3F) | 0x80); + bytes.push((c & 0x3F) | 0x80); + } else if(c >= 0x000800 && c<= 0x0007FF) { + bytes.push(((c>>6) & 0x3F) | 0x80); + bytes.push((c & 0x3F) | 0x80); + } else { + bytes.push(c & 0xFF) + } + } + return bytes; +} +``` + +## 创建woker时报错“Too many wokers,the number of worker exceeds the maximum”如何处理 + +使用于:OpenHarmony SDK 3.2.6.5版本 + +这是因为每个应用的worker上限为7个,因此在worker使用完成后需要通过termiate方法释放worker。参考[worker开发指南](../reference/apis/js-apis-worker.md#terminate)。 + +## OpenHarmony推荐的多线程解决方案是什么 + +使用于:OpenHarmony SDK 3.2.6.5版本 API9 Stage模型 + +OpenHarmony推荐使用worker来处理多线程场景。 + +参考文档:[启动一个worker](../reference/apis/js-apis-worker.md) + +## 使用\@Builder装饰包含自定义组件的方法与普通方法的区别是什么 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +\@Builder装饰的方法中使用了自定义组件,那么该方法每次被调用时,对应的自定义组件均会重新创建。 + +## 状态管理中\@Watch监听,数组内对象属性变化无法触发watch回调函数 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +使用\@Watch监听的对象,只能监听一层数据变化,多层次数据变更无法监听,同\@State状态管理机制一致 + +## 如何监听\@State深层数据变化 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过\@Observed配合\@ObjectLink装饰符实现。 + +参考文档:[Observed和ObjectLink数据管理](../quick-start/arkts-state-mgmt-page-level.md#observed和objectlink数据管理) + +## 如何实现字符串编解码 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过util工具函数模块中的TextEncoder和TextDecoder进行解码。 + +参考文档:[TextEncoder](../reference/apis/js-apis-util.md#textencoder)、[TextDecoder](../reference/apis/js-apis-util.md#textdecoder) + +## 如何导入和导出namespace命名空间 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +- namespace导出 + + ``` + namespace Util{ + export function getTime(){ + return Date.now() + } + } + export default Util + ``` + +- namespace导入 + + ``` + import Util from './util' + Util.getTime() + ``` + +## worker线程中能进行关系型数据库的操作吗 + +适用于:OpenHarmony SDK 3.2.5.5版本, API9 Stage模型 + +不支持。 diff --git a/zh-cn/application-dev/faqs/faqs-media.md b/zh-cn/application-dev/faqs/faqs-media.md new file mode 100644 index 0000000000000000000000000000000000000000..7ced8a1d5ab3c80f6a9401565c410e84f18ad5d6 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-media.md @@ -0,0 +1,128 @@ +# 媒体开发常见问题 + +## 如何设置前置拍照 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +1. 设置相机位置camera.CameraPosition.CAMERA_POSITION_FRONT + +2. 根据相机位置和类型创建CameraInput实例 + +参考文档:[相机管理](../reference/apis/js-apis-camera.md) + +示例: + +``` +//默认设置后置相机,通过设置isFrontCamera来切换相机 +let cameraId +let cameraInput +for(let cameraIndex = 0; cameraIndex < this.cameraArray.length; cameraIndex++) { + let faceType = this.cameraArray[cameraIndex].cameraPosition + switch(faceType) { + case camera.CameraPosition.CAMERA_POSITION_FRONT://前置相机 + if(this.isFrontCamera){ + cameraId = this.cameraArray[cameraIndex].cameraId + } + break + case camera.CameraPosition.CAMERA_POSITION_BACK://后置相机 + if(!this.isFrontCamera){ + cameraId = this.cameraArray[cameraIndex].cameraId + } + break + case camera.CameraPosition.CAMERA_POSITION_UNSPECIFIED: + default: + break + } +} +cameraInput = await this.cameraManager.createCameraInput(cameraId)熊文帅 +``` + +## 如何进行图片剪切 + +适用于:OpenHarmony 3.2.5.6版本,API9 Stage模型 + +1. **通过传入的uri创建图片源实例ImageSource对象。** + + ``` + let path = this.context.getApplicationContext().fileDirs + "test.jpg"; + const imageSourceApi = image.createImageSource(path); + ``` + +2. **设置解码参数,通过图片解码获取PixelMap图像对象,解码过程中同时支持图像处理操作。** + - 设置desiredSize支持按尺寸缩放,如果设置为全0,则不进行缩放。 + - 设置desiredRegion支持按矩形区域裁剪,如果设置为全0,则不进行裁剪。 + - 设置rotateDegrees支持旋转角度,以图像中心点顺时针旋转。 + + ``` + const decodingOptions = { + desiredSize: { + height:0, + width:0 + }, + //按矩形区域裁剪 + desiredRegion: { + size: { + height:100, + width:100 + }, + x:0, + y:0 + }, + //旋转90度 + rotate:90 + } + imageSourceApi.createPixelMap(decodingOptions).then(pixelMap => { + this.handlePixelMap(pixelMap) + }) + ``` + +3. 解码完成获取到PixelMap对象后,可以进行后续处理,比如渲染显示等。 + +## 如何申请设备上的媒体读写权限 + +适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 + +1. 在module.json5配置文件中配置媒体读写权限ohos.permission.READ_MEDIA和ohos.permission.WRITE_MEDIA。 + 示例: + + + ``` + { + "module" : { + "requestPermissions":[ + { + "name" : "ohos.permission.READ_MEDIA", + "reason": "$string:reason" + }, + { + "name" : "ohos.permission.WRITE_MEDIA", + "reason": "$string:reason" + } + ] + } + } + ``` + +2. 这两个权限的授权方式均为user_grant,因此需要调用requestPermissionsFromUser接口,以动态弹窗的方式向用户申请授权。 + + ``` + let permissions: Array = ['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] + context.requestPermissionsFromUser(permissions).then((data) => { + console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) + }).catch((error) => { + console.log("Failed to request permission from user with error: " + JSON.stringify(error)) + }) + ``` + +## MP4格式的视频为什么播放不了 + +适用于:OpenHarmonySDK 3.2.7.5版本,API9 Stage模型 + +暂不支持h.265编码格式的MP4视频播放。 + + +## 为什么视频创建至十几个时新创建的视频无法播放甚至崩溃 + +适用于:OpenHarmonySDK 3.2.7.5版本,API9 Stage模型 + +当前限制最多创建13个媒体播放实例。 diff --git a/zh-cn/application-dev/faqs/faqs-native.md b/zh-cn/application-dev/faqs/faqs-native.md index c71a09dc54f5d04d2bae295c17fe5e1e9af62dba..c0a05db2c35d6b5a4bfb885715def72b0b204edf 100644 --- a/zh-cn/application-dev/faqs/faqs-native.md +++ b/zh-cn/application-dev/faqs/faqs-native.md @@ -1,6 +1,10 @@ # Native API使用常见问题 +## Native API是否有类似Canvas绘制接口 +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +Native API中的[Drawing](../reference/native-apis/_drawing.md)接口可以提供2D绘制功能。 ## 运行Native HAP的时候,导入的命名空间报错Obj is not a valid object @@ -8,7 +12,19 @@ 检查模块根目录(注意不是工程根目录)下的build-profile.json5文件,如果设备是32位,需要在abiFilters参数中配置armeabi-v7a,如果设备是64位,需要在abiFilters参数中配置arm64-v8a。 -## NAPI开发的C++代码中,如何获取到模块 package.json 文件中的 “version” 值? +## 运行Native HAP的时候,报错install parse profile prop check error + +适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 + +检查模块根目录(注意不是工程根目录)下的build-profile.json5文件,如果设备是32位,需要在abiFilters参数中配置armeabi-v7a,如果设备是64位,需要在abiFilters参数中配置arm64-v8a。 + +## 在Native代码中使用OH_LOG_Print打印日志,报错undefined symbol: OH_LOG_Print + +适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 + +需要修改CMakeLists.txt文件,在target_link_libraries最后追加libhilog_ndk.z.so。 + +## 如何获取到模块 package.json 文件中的 “version” 值 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -55,3 +71,9 @@ static napi_value Add(napi_env env, napi_callback_info info) return fixed_version_value; } ``` + +## 如何遍历rawfiles中的文件 + +适用于:OpenHarmony SDK 3.2版本以上,API9 Stage模型 + +使用Native API中的OH_ResourceManager_OpenRawDir()方法获取到rawfile的根目录,然后对其进行遍历。可参考文档:[Native开发指导](../reference/native-apis/rawfile.md) diff --git a/zh-cn/application-dev/faqs/faqs-third-party-library.md b/zh-cn/application-dev/faqs/faqs-third-party-library.md index 758305d4aca128e8d39001b2176c3f820f2302e2..a15136dfb734e626c50c6fb7875c842a3f9d0764 100644 --- a/zh-cn/application-dev/faqs/faqs-third-party-library.md +++ b/zh-cn/application-dev/faqs/faqs-third-party-library.md @@ -1,9 +1,74 @@ # 三四方库使用常见问题 +## 报错“Stage model module … does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed. ”如何解决 +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 + +三四方件未适配API9 Stage模型,无法使用。 -## 报错“Stage model module … does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed. ”是什么意思? +## 项目是否支持传递依赖 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 -三四方件未适配API9 Stage模型,无法使用。 +比如项目A依赖项目B,项目B依赖项目C,那项目A是否能直接使用项目C提供的接口? + +不支持。由于项目打包使用npm工具,npm不支持传递依赖。可以在项目A增加项目C的依赖来解决问题。 + +## 如何获取可用的三方库 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +参见:[OpenHarmony上可直接使用的三方组件汇总](https://gitee.com/openharmony-sig/third_party_app_libs)。 + +## 网络相关的三方库有哪些 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +网络相关的三方库有[Axios](https://gitee.com/openharmony-sig/axios)。 + +## 如何使用npm引入三四方库 + + 适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 +- 方法一: + 1. 打开Terminal窗口,通过如下指令进入到entry目录。 + + ``` + cd entry + ``` + 2. 以引入“dayjs”为例,执行以下指令进行安装。 + + ``` + npm install dayjs --save + ``` + 3. 在对应的js文件中直接引用。 + + ``` + import dayjs from 'dayjs'; + ``` + +- 方法二: + 1. 打开工程目录下的entry目录,找到该目录下的package.json文件。 + 2. 在package.json文件中写入想要安装的三方npm,以“dayjs”为例,示例如下: + + ``` + { + "dependencies": { + "dayjs": "^1.10.4", + } + } + ``` + 3. 打开Terminal窗口,通过如下指令进入到entry目录。 + + ``` + cd entry + ``` + 4. 执行指令进行安装。 + + ``` + npm install + ``` + 5. 在对应的js文件中直接引用。 + + ``` + import dayjs from 'dayjs'; + ``` diff --git a/zh-cn/application-dev/faqs/faqs-ui-ets.md b/zh-cn/application-dev/faqs/faqs-ui-ets.md index 46cbe5907ec7734d20b6a37719ca49e7bbd014a3..b4645777a29e8e4e89935dce05a29c3f8cf3aaa8 100644 --- a/zh-cn/application-dev/faqs/faqs-ui-ets.md +++ b/zh-cn/application-dev/faqs/faqs-ui-ets.md @@ -1,35 +1,4 @@ -# UI框架(ArkTS)开发常见问题 - - - -## ArkTS语言在生成器函数中编译失败,有哪些使用限制? - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -ArkTS语言的使用在生成器函数中存在以下限制: - -- 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用; - -- 这些表达式中的任何一个都不能导致任何应用程序状态变量(\@State、\@Link、\@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为; - -- 生成器函数内部不能有局部变量。 - -上述限制都不适用于事件处理函数(例如onClick)的匿名函数实现。 - -错误示例: - - -``` -build() { - let a: number = 1 // invalid: variable declaration not allowed - Column() { - Text('Hello ${this.myName.toUpperCase()}') // ok. - ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place - } - buildSpecial() // invalid: no function calls - Text(this.calcTextValue()) // this function call is ok. -} -``` +# ArkUI组件(ArkTS)开发常见问题 ## 在Stage模型下,如何通过router实现页面跳转 @@ -39,90 +8,14 @@ build() { 2. 页面路由需要在页面渲染完成之后才能调用,在onInit和onReady生命周期中页面还处于渲染阶段,禁止调用页面路由方法。 +参考文档:[页面路由](../reference/apis/js-apis-router.md) + ## router通过调用push方法进堆栈的page是否会被回收 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 调用push进入堆栈的page不回收,调用back方法出栈后可以被回收。 -## 如何动态替换掉资源文件中的“%s”占位符 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -在应用中,通过"$r('app.string.xx')"的形式引用应用资源,$r的第二个参数可用于替换%s占位符。 - - 示例: - -``` -build() { - //do something - //引用的string资源,$r的第二个参数用于替换%s - Text($r('app.string.entry_desc','aaa')) - .fontSize(100) - .fontColor(Color.Black) - //do something -} -``` - -## 如何读取Resource中的xml文件并转化为String类型 - -适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 - -1. 通过resourceManager的RawFile接口获取Uint8Array格式数据。 - -2. 通过String.fromCharCode将Uint8Array格式数据转化为String类型。 - -参考文档:[资源管理](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md) - -示例: - - -``` -resourceManager.getRawFile(path, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - let xml = String.fromCharCode.apply(null, rawFile) - } -}); -``` - -## 如何将Resource资源对象转成string类型 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -通过\@ohos.resourceManager模块 resourceManager.getString()方法获取字符串。 - -参考文档:[资源管理](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md#getstring) - -## class全局静态变量无法使用的问题 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -Page和Ability打包后会对import的对象分别形成两个不同的闭包,即打包出两个Global对象。因此,所引用的静态变量并不是同一对象,所以无法通过class静态变量方式定义全局变量。建议使用AppStorage进行全局变量管理。 - -参考文档:[应用程序的数据存储](https://docs.openharmony.cn/pages/v3.2Beta/zh-cn/application-dev/ui/ts-application-states-appstorage.md/) - -## Stage模型下如何获取资源 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包,此方式FA模型不适用。 - -示例: - - -``` -const context = getContext(this) as any -context - .resourceManager - .getString($r('app.string.entry_desc').id) - .then(value => { - this.message = value.toString() -}) -``` - ## 如何将容器定位到屏幕的最底部? 适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 @@ -130,7 +23,7 @@ context 可以使用Stack堆叠容器,设置子组件在容器内的最底部。 示例: - + ``` build() { Stack({alignContent : Alignment.Bottom}) { @@ -150,15 +43,15 @@ build() { } ``` -## CustomDialog是否支持在TS文件中使用? +## CustomDialog是否支持在TS文件中使用 适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 -不支持,CustomDialog当前只支持在eTS的Page中使用。 +不支持,CustomDialog当前只支持在ArkTS的Page中使用。 -参考文档:[自定义弹窗](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md) +参考文档:[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) -## 如何将CustomDialog中的变量传递给Page页面中的变量? +## 如何将CustomDialog中的变量传递给Page页面中的变量 适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 @@ -166,34 +59,72 @@ build() { 示例: - + ``` -// CustomDialog 组件 +// 弹窗组件 @CustomDialog struct MyDialog { controller: CustomDialogController title: string - data: string - cancel: () => void confirm: (data: string) => void - Button('confirm') - .onClick(() => { - this.controller.close() - this.data = 'test' - this.confirm(this.data) - }).backgroundColor(0xffffff).fontColor(Color.Red) -// Page页面 + data: string = '' + + build() { + Row() { + Column({ space: 10 }) { + Text(this.title) + .fontSize(30) + .fontColor(Color.Blue) + TextInput({ placeholder: "输入内容", text: this.data }) + .onChange((data) => { + this.data = data // 获取输入框数据 + }) + Button('confirm') + .onClick(() => { + this.confirm(this.data) // 将输入框数据通过回调函数传给主页面 + this.controller.close() + }).backgroundColor(0xffffff).fontColor(Color.Red) + }.width("50%") + }.height("50%") + } +} + +// main页面 @Entry @Component struct DialogTest { + @State dialogTitle: string = '' + @State dialogData: string = '' dialogController: CustomDialogController = new CustomDialogController({ - builder: MyDialog({ title:'标题自定义',cancel: this.onCancel, - confirm: this.onAccept.bind(this) }), // 绑定自定义的回调函数 - cancel: this.existApp, - autoCancel: true + builder: MyDialog({ + title: this.dialogTitle, // 绑定数据 + data: this.dialogData, + confirm: this.confirm.bind(this) // 绑定自定义的回调函数,这里要修改this的指向 + }) }) - onAccept(data:string) { - console.info('Callback when the second button is clicked ' + data) + + confirm(data: string) { + this.dialogData = data + console.info(`recv dialog data: ${data}`) // 获取弹窗输入的信息 + } + + build() { + Row() { + Column({ space: 10 }) { + Button('点击打开弹窗') + .onClick(() => { + this.dialogTitle = '弹窗' + this.dialogController.open() + }) + Text(`接受弹窗的数据:`) + .fontSize(20) + TextInput({ placeholder: "输入内容", text: this.dialogData }) + .width("50%") + .onChange((data) => { + this.dialogData = data // 获取输入框数据 + }) + }.width("100%") + }.height("100%") } } ``` @@ -210,10 +141,10 @@ struct DialogTest { GridContainer内子组件默认水平左对齐,居中显示可以参考以下处理方式: -内部嵌套布局组件Row,设置Row属性justifyContent(FlexAlign.Center),内部嵌套子组件可保持居中显示,参考[栅格布局](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md)文档。 +内部嵌套布局组件Row,设置Row属性justifyContent(FlexAlign.Center),内部嵌套子组件可保持居中显示,参考[栅格布局](../reference/arkui-ts/ts-container-gridcontainer.md)文档。 示例: - + ``` GridContainer({ sizeType: SizeType.SM, columns: 12 }) { Row() { @@ -233,7 +164,7 @@ GridContainer({ sizeType: SizeType.SM, columns: 12 }) { 在加载窗口内容之前,采用systemAvoidAreaChange事件监听。 示例: - + ``` // MainAbility.ts import window from '@ohos.window'; @@ -249,7 +180,7 @@ async function enterImmersion(mainWindow: window.Window) { }) await mainWindow.setFullScreen(true) await mainWindow.setSystemBarEnable(["status", "navigation"]) - await mainWindow.setSystemBarProperties({ + await mainWindow.sArkTSystemBarProperties({ navigationBarColor: "#00000000", statusBarColor: "#00000000", navigationBarContentColor: "#FF0000", @@ -267,16 +198,451 @@ export default class MainAbility extends Ability { } ``` -## 如何在eTS代码中执行Web组件内的JS函数? +## 在容器组件嵌套的场景下,如何解决手势拖拽事件出现错乱的问题 -适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 +适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 -通过WebController中runJavaScript方法异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果。注意:runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 +gesture的属性distance默认值是5,把gesture的属性distance设成1就可以解决。 -参考文档:[Web](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md) +## 如何获取组件的高度 -## 在容器组件嵌套的场景下,如何解决手势拖拽事件出现错乱的问题? +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 +组件宽高变化可通过onAreaChange组件区域变化事件获取。 -gesture的属性distance默认值是5,把gesture的属性distance设成1就可以解决。 +示例: + + +``` +Column() { + Text(this.value) + .backgroundColor(Color.Green).margin(30).fontSize(20) + .onClick(() => { + this.value = this.value + 'Text' + }) + .onAreaChange((oldValue: Area, newValue: Area) => { + console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`) + this.size = JSON.stringify(newValue) + }) +``` + +## 如何获取List组件的偏移量 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +List组件绑定Scoller控制器,通过currentOffset方式获取当前的滚动偏移量。 + +示例: + + +``` +Column() { + List({ space: 20, initialIndex: 0,scroller: this.scroller}) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%').height(100).fontSize(16) + .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) + }.editable(true) + }, item => item) + } + .listDirection(Axis.Vertical) // 排列方向 + .editMode(this.editFlag) + .onScroll((xOffset: number, yOffset: number) => { + console.info("yOffset======="+this.scroller.currentOffset().yOffset) + }) +}.width('100%') +``` + +## 页面使用router携带param跳转后,下一个页面如何获取param + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + + +``` +// 3.1.5.5版本之前,取值方式为:router.getParams().key +private value: string = router.getParams().value; +// 从3.1.6.5版本起,取值方式为:router.getParams()['key'] +private value: string = router.getParams()['value']; +``` + +## RichText组件是否支持跳转到本地page页面 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +不支持。 + +## 使用router或Navigator实现页面跳转时,如何关闭页面间转场动效 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +1. 参考[页面间转场示例](../reference/arkui-ts/ts-page-transition-animation.md#示例)在当前页面和目标页面中定义pageTransition方法。 + +2. 将页面入场组件PageTransitionEnter和页面退场组件PageTransitionExit的动效参数duration都设置为0。 + +## UI开发中,像素单位如何选择 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +Vp保证了不同分辨率下 视觉效果的等价性,比如一个图标,在不同分辨率下都是视觉效果是等价。 + +lpx相当于百分比视图,按比例扩大或者缩小。 + +如果关注Item等效性的,比如按钮、文字、列表基本上都是VP;比如关注布局,比如1/2之类的网格,lpx更好。 + +## ArkTS中颜色的格式说明 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +颜色可以使用两种格式,例如 0x7F000000 或者 '\#7F000000' ,其中前两位是透明度,后六位是RGB。 + + +``` +fontColor(0x7F000000) +fontColor( '#7F000000' ) +``` + +## 如何在Page页面中监听返回操作 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +在Page页面返回时,系统会调用\@Entry修饰的自定义组件的onBackPress()回调,可以在回调函数中实现相关业务诉求。参考[自定义组件生命周期回调函数](../ui/ui-ts-custom-component-lifecycle-callbacks.md) + +## TextInput组件密码模式下,右边的眼睛图标是否支持自定义? + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +TextInput组件设置type为InputType.Password时,右侧出现眼睛图标,showPasswordIcon控制图标显示隐藏,不支持自定义。更多信息可参考文档:[TextInput组件](../reference/arkui-ts/ts-basic-components-textinput.md) + +## Image图片加载目前只能加载https的 不能加载http的 + +适用于:OpenHarmony SDK3.2.5.5, API9 Stage模型 + +htpp是不安全的,会被白名单过滤掉,建议使用https。 + +## TextView布局设置间距与显示界面不符合 + +适用于:OpenHarmony SDK3.2.5.5, API9 Stage模型 + +TextView默认设置align属性为居中,文本从左到右显示,需要设置align属性为Start。 + +## constraintSize尺寸设置不生效 + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +constraintSize约束组件尺寸时,子组件内设置百分比宽度,例如width('100%')会采用constraintSize约束中的最大宽乘百分比,导致撑开组件,看起来constraintSize设置没生效 + +## 如何将背景颜色设置为透明 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +将backgroundColor设置为 '\#00000000' 。 + +## Scroll组件滚动到达不了最底部 + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +Scroll组件在未设置高度情况下,默认为窗口高度,当滚动区域外存在其他组件时,滚动底部区域会出现遮挡,需要设置Scroll高度,或者使用Flex布局限制Scroll高度 + +## 输入框组件TextInput回车事件onSubmit使用 + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +onSubmit事件在回车键或软键盘回车触发该回调,参数为当前软键盘回车键类型,通过enterKeyType属性可以设置输入法回车键类型,软键盘回车键样式需要输入法的支持,具体文档参考[Textinput组件](../reference/arkui-ts/ts-basic-components-textinput.md) + +## 页面路由时,页面栈内的数量限制是多少 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +页面路由栈支持的最大页面数量是32,当超出此限制时,使用router.push接口页面无法完成跳转 。 + +## ArkUI是否支持通过代码动态创建组件 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +支持使用[条件渲染](../quick-start/arkts-rendering-control.md#条件渲染)和[循环渲染](../quick-start/arkts-rendering-control.md#循环渲染)等方式进行动态创建组件。 + +## 页面路由携带PixelMap对象参数,跳转页面无法获取 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +页面路由只支持普通对象类型,普通JSON数据结构,可以采用localStorage存储PixelMap对象,在跳转页面获取 + +## TextInput组件在onEditChange激活的时候通过.caretPosition(0)让光标回到起点 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +onEditChange事件在输入框聚焦时触发,这时光标位置和手势触发位置有关,在使用caretPosition同步处理无法改变光标位置,需要使用异步处理,在setTimeout中执行可以进行 + +## TextInput是否有方法设置内容为全部选中 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +TextInput组件暂不支持设置内容全选。 + +## input的输入框的type属性是date,但无法选择时间 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +input 组件的 type 设置为 date,只是会有相关格式提示,本质上还是输入控件,如果需要实现日期选择效果,需要使用 picker 组件。 + +## ArkTS TextInput输入时,弹出的输入法框把页面布局挤压变形 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +用Flex布局就会有挤压变形情况,改成Column布局就不会产生挤压 + +## 子组件使用\@Link修饰成员变量时,父组件传值如何传值 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +子组件使用\@Link修饰时,父组件传值需要添加"$" + +示例: + + +``` +@Component +struct FoodImageDisplay { + @Link imageSrc: Resource + + build() { + Stack({ alignContent: Alignment.BottomStart }) { + Image(this.imageSrc) + .objectFit(ImageFit.Contain) + Text('Tomato') + .fontSize(26) + .fontWeight(500) + .margin({ left: 26, bottom: 17.4 }) + } + .backgroundColor('#FFedf2f5') + .height(357) + } +} + +@Entry +@Component +struct FoodDetail { + + @State imageSrc: Resource = $r('app.media.Tomato') + + build() { + Column() { + FoodImageDisplay({imageSrc:$imageSrc}) + } + .alignItems(HorizontalAlign.Center) + } +} +``` + +## 如何多个pageAbility之间共享变量 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +1. 可以使用轻量级数据库 + +2. 可以使用持久化数据管理 + +3. 可以使用emitter事件通信 + + +## 如何自定义Video组件控制栏样式 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +1. 通过设置属性controls为false关闭默认控制栏 + +2. 设置Video组件的controller + +3. 通过ArkTS实现自定义的控制栏,并通过VideoController控制视频播放 + +## 对ArkTS组件多次更新时如何优化性能 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过将需要更新的ArkTS组件抽离成自定义组件,并更新该自定义组件内\@State绑定的变量,以此实现组件的局部刷新。 + +## 如何优化Tab组件性能 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +Tab组件处于某一页签时。其他页签并不会被系统卸载,所以会占用部分内存。可以通过if渲染控制判断当前页签是否是需要显示的页签,若不是则不加载,以此来实现卸载其他不显示的页签并释放这部分内存。 + +## 如何设置组件不同状态下的样式 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过设置组件的多态样式,实现组件不同状态(无状态、按下、禁用、聚焦、点击)的样式 + +参考文档:[多态样式](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) + +## 焦点事件onBlur/onFocus回调无法触发 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +焦点事件默认情况下需要外接键盘的Tab键,或方向键触发,点击触发焦点事件需要添加焦点控制属性focusOnTouch + +参考文档:[焦点控制](../reference/arkui-ts/ts-universal-attributes-focus.md) + +## Scroll内Flex加宽高与滑动冲突 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +Scroll支持单个子组件,子组件高度应由内容高度决定,当内容中存在异步加载的图片组件导致滚动布局异常时,可约束子组件最小高度constraintSize({ minHeight: '100%' }) + +## 页面路由跳转后如何阻止其返回原页面 + +适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 + +通过router.clear()接口清空页面栈中的所有历史页面,保留当前页面作为栈顶页面。 + +参考文档:[页面路由](../reference/apis/js-apis-router.md) + +## 如何实现将TextInput组件内容进行一次性清空 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +可以参考如下实现: + + +``` +struct Index { +@State text: string = 'Hello World' +controller: TextInputController = new TextInputController() + build() { + Row() { + Column() { + TextInput({ placeholder: 'Please input your words.', text: this.text, + controller:this.controller}).onChange((value) => { + this.text = value + }) + Button("Clear TextInput").onClick(() => { + this.text = ""; + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +## Tabs组件在点击Tab项时是否支持禁止切换 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +不支持。 + +## 使用 \@state修饰成员变量“id”会报错,报错原因:TypeError: cannot read property 'get' of undefined + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +id添加为唯一值,成为关键字。 + +## 基于OpenHarmony开发的应用,是否支持使用fontFamily属性设置不同的字体 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +基于OpenHarmony开发的应用,默认字体'HarmonyOS Sans',且当前只支持这种字体。 + +## Ability与UI页面推荐的数据交互方式是什么 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +推荐使用[LocalStorage](../quick-start/arkts-state-mgmt-application-level.md#localstorage)。 + +## 父组件如何与其孙子组件进行状态同步 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +- 方式一(推荐):使用\@Provide和\@Consume装饰器。在父组件使用\@Provide,在孙子组件使用\@Consume,可以实现父组件和孙子组件进行双向数据绑定。 + +- 方式二:使用\@State和\@Link装饰器。在父组件使用\@State,在每一层子组件(子组件和孙子组件)都使用\@Link。 + +## 字符超长中间显示省略号 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +代码示例 + + +``` +beautySub(str,len) { + var reg = /[\u4e00-\u9fa5]/g; + //减少字符,达到优化 + var slice = str.substring(0,len) + var charNum = (~~(slice.match(reg) && slice.match(reg).length)) + //减1是为了处理万一超过字符串,不显示多一个不是汉字的字符, + var realen = slice.length*2 - charNum-1 + return str.substr(0,realen) + (realen < str.length ? "..." : "") +str.substr(str.length-realen,str.length) +} +``` + +## richText 组件怎么加上滚动条 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +RichText底层是web,可以参考html的语法,在div上加上的overflow:auto的滚动样式。 + +## scroll里面套一个grid,怎么禁用grid的滑动事件? + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +可以通过onScrollBegin事件和scrollBy方法实现容器嵌套滚动。 + +参考:[容器嵌套滚动样例](../reference/arkui-ts/ts-container-scroll.md#示例2) + +## 能否去除自定义弹窗组件的白色背景 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +当前不支持。原因是当前的UI样式在框架后端写死了,无法更改。 + +## 组件背景图片设置backgroundImage方法是否支持svg图片格式 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +当前不支持。 + +## 自定义弹窗组件如何设置弹窗位置 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +自定义弹窗组件中参数alignment可以指定弹窗的位置。比如设置弹窗在底部:alignment : DialogAlignment.Bottom。 + +参考文档:[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## scroller如何判断回弹动画的结束误差 + +适用于:OpenHarmony SDK 3.2.5.3版本,API8 FA模型 + +目前可以在触摸结束之后,计算同方向的变化,如果变化方向相反,说明出现回弹了,就规避不处理了。 + + +## 如何实现应用数据持久化存储 + +通过PersistentStorage类实现管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据。 + +参考文档:[持久化数据管理](../quick-start/arkts-state-mgmt-application-level.md#persistentstorage) + +示例: + + +``` +AppStorage.Link('varA') +PersistentStorage.PersistProp("varA", "111"); +@Entry +@Componentstruct Index { + @StorageLink('varA') varA: string = '' + build() { + Column() { + Text('varA: ' + this.varA).fontSize(20) + Button('Set').width(100).height(100).onClick(() => { + this.varA += '333' + }) + } + .width('100%') + .height('100%') + } +} +``` diff --git a/zh-cn/application-dev/faqs/faqs-ui-js.md b/zh-cn/application-dev/faqs/faqs-ui-js.md index 90ec607864c46ecfbeba21b7ac327ffe8c3e3ae1..f2e540c747a7ccecfd7623469beec8a87205875a 100644 --- a/zh-cn/application-dev/faqs/faqs-ui-js.md +++ b/zh-cn/application-dev/faqs/faqs-ui-js.md @@ -1,7 +1,5 @@ # UI框架(JS)开发常见问题 - - ## 如何取出xml文件中对应的字段 适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 @@ -39,20 +37,11 @@ let options = { } let result: any = conv.convert(xml, options) // 将xml文本转为JS对象 console.log('Test: ' + JSON.stringify(result)) -console.log('Test: ' + result._declaration._attributes.version) // xml字符串中version字段信息console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml字符串中title字段内容 +console.log('Test: ' + result._declaration._attributes.version) // xml字符串中version字段信息 +console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml字符串中title字段内容 ``` -参考文档:[xml转换JavaScript](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-convertxml.md) - -## JS、TS和eTS的区别 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -- JS:Web 的编程语言。具有轻量级,弱类型等特点。 - -- TS:TS是JS的超集,拓展了JS的语法。有明确的类型与更多面向对象的内容如接口,枚举等。 - -- eTS:OpenHarmony UI开发框架语言,是对TS的扩展,通过声明式开发范式实现UI界面。 +参考文档:[xml转换JavaScript](../reference/apis/js-apis-convertxml.md) ## 如何将时间转为时分秒格式 @@ -101,4 +90,6 @@ export default class DateTimeUtil{ return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}` } } + ``` + diff --git a/zh-cn/application-dev/faqs/faqs-web-arkts.md b/zh-cn/application-dev/faqs/faqs-web-arkts.md new file mode 100644 index 0000000000000000000000000000000000000000..c423c07b5eb713b3455d90b29f5d5ae59633525f --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-web-arkts.md @@ -0,0 +1,80 @@ +# ArkUI Web组件(ArkTS)开发常见问题 + +## Web组件domStorageAccess属性设置 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启,控制web网页中localStorage的使用,对sessionStorage未做控制 + + +## Web组件加载的html页面内如何检测网络状态 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +1. 配置应用权限:ohos.permission.INTERNET 、 ohos.permission.GET_NETWORK_INFO + +2. html中通过window.navigator.onLine获取网络状态 + +## Web组件加载h5页面,首次加载无法设置拼接UserAgent参数 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +默认UserAgent通过WebController获取。一个WebController对象只能控制一个Web组件,且必须在Web组件和WebController绑定后,才能调用WebController上的方法,因此在初次加载前设置默认UserAgent + 自定义字符串拼接,可采用此方式: + +1. 使用\@State定义初始userAgent,绑定到Web组件; + +2. 在web组件的onUrlLoadIntercept回调中,通过WebController获取默认userAgent,修改Web组件绑定的userAgent。 + 参考代码如下: + + + ``` + @Entry + @Component + struct Index { + private controller: WebController = new WebController() + @State userAgentPa: string = '' + build() { + Row() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .width('100%') + .userAgent(this.userAgentPa) + .onUrlLoadIntercept((event) => { + let userAgent = this.controller.getDefaultUserAgent(); + this.userAgentPa = userAgent + ' 111111111' + console.log("userAgent onUrlLoadIntercept: " + userAgent); + return false; + }) + } + .width('100%').alignItems(HorizontalAlign.Start).backgroundColor(Color.Green) + } + .height('100%') + } + } + ``` + +## 加载Lottie动画的逻辑应该写在onAppear函数中还是应该写在onReady函数中 + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +onAppear方法只是定位完Canvas的位置,onReady方法才是测量完成,加载动画的逻辑应该写在onReady函数中。 + +## 调用deleteJavaScriptRegister后是否需要调用refresh接口 + +适用于:所有版本 + +不需要。 + +## 页面如何传递数据给Web组件 + +适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 + +1. 使用WebController创建两个消息端口。 + +2. 将消息端口1发送到HTML侧,由HTML侧保存并使用。 + +3. 将消息端口0在应用侧注册回调事件。 + +4. 使用应用侧的端口0给HTML侧消息端口1发送消息。 + +使用参考:[Web组件](../reference/arkui-ts/ts-basic-components-web.md#postmessage9) 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/media/Readme-CN.md b/zh-cn/application-dev/media/Readme-CN.md index b8d00b5eb8a45c2e24d21a4e0fc3d5c26c5baf7d..e1115fafee7fa9f5fb6fdfabb59b64bc17b10a36 100755 --- a/zh-cn/application-dev/media/Readme-CN.md +++ b/zh-cn/application-dev/media/Readme-CN.md @@ -15,6 +15,10 @@ - [视频播放开发指导](video-playback.md) - [视频录制开发指导](video-recorder.md) +- 媒体会话 + - [AVSession开发概述](avsession-overview.md) + - [AVSession开发指导](avsession-guidelines.md) + - 图片 - [图片开发指导](image.md) diff --git a/zh-cn/application-dev/media/audio-capturer.md b/zh-cn/application-dev/media/audio-capturer.md index 60318f711977e7f7001304c74166dd29222ba7e5..577d93292181bcd30a2a0c964c8bcb566d69fe26 100644 --- a/zh-cn/application-dev/media/audio-capturer.md +++ b/zh-cn/application-dev/media/audio-capturer.md @@ -32,86 +32,70 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 在audioCapturerOptions中设置音频采集器的相关参数。该实例可用于音频采集、控制和获取采集状态,以及注册通知回调。 ```js - var audioStreamInfo = { + import audio from '@ohos.multimedia.audio'; + + let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } - var audioCapturerInfo = { + let audioCapturerInfo = { source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 + capturerFlags: 0 // 0是音频采集器的扩展标志位,默认为0 } - var audioCapturerOptions = { + let audioCapturerOptions = { streamInfo: audioStreamInfo, capturerInfo: audioCapturerInfo } let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; + console.log('AudioRecLog: Create audio capturer success.'); ``` -2. (可选)使用on('stateChange')订阅音频采集器状态更改。 - 如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 - - ```js - audioCapturer.on('stateChange',(state) => { - console.info('AudioCapturerLog: Changed State to : ' + state) - switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } - }); - ``` - -3. 调用start()方法来启动/恢复采集任务。 +2. 调用start()方法来启动/恢复采集任务。 启动完成后,采集器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 ```js - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } - ``` - -4. 使用getBufferSize()方法获取要读取的最小缓冲区大小。 + import audio from '@ohos.multimedia.audio'; + + async function startCapturer() { + let state = audioCapturer.state; + // Capturer start时的状态应该是STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一. + if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || + state != audio.AudioState.STATE_STOPPED) { + console.info('Capturer is not in a correct state to start'); + return; + } + await audioCapturer.start(); - ```js - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); + let state = audioCapturer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.error('AudioRecLog: Capturer start failed'); + } + } ``` -5. 读取采集器的音频数据并将其转换为字节流。重复调用read()方法读取数据,直到应用准备停止采集。 +3. 读取采集器的音频数据并将其转换为字节流。重复调用read()方法读取数据,直到应用准备停止采集。 参考以下示例,将采集到的数据写入文件。 ```js import fileio from '@ohos.fileio'; + + let state = audioCapturer.state; + // 只有状态为STATE_RUNNING的时候才可以read. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Capturer is not in a correct state to read'); + return; + } - const path = '/data/data/.pulse_dir/capture_js.wav'; + const path = '/data/data/.pulse_dir/capture_js.wav'; // 采集到的音频文件存储路径 let fd = fileio.openSync(path, 0o102, 0o777); if (fd !== null) { console.info('AudioRecLog: file fd created'); @@ -126,38 +110,140 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 console.info('AudioRecLog: file fd opened in append mode'); } - var numBuffersToCapture = 150; + let numBuffersToCapture = 150; // 循环写入150次 while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); + let buffer = await audioCapturer.read(bufferSize, true); if (typeof(buffer) == undefined) { - console.info('read buffer failed'); + console.info('AudioRecLog: read buffer failed'); } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); + let number = fileio.writeSync(fd, buffer); + console.info(`AudioRecLog: data written: ${number}`); } numBuffersToCapture--; } ``` -6. 采集完成后,调用stop方法,停止录制。 +4. 采集完成后,调用stop方法,停止录制。 ```js - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + async function StopCapturer() { + let state = audioCapturer.state; + // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('AudioRecLog: Capturer is not running or paused'); + return; + } + + await audioCapturer.stop(); + + state = audioCapturer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.error('AudioRecLog: Capturer stop failed'); + } + } ``` -7. 任务结束,调用release()方法释放相关资源。 +5. 任务结束,调用release()方法释放相关资源。 ```js - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } - ``` \ No newline at end of file + async function releaseCapturer() { + let state = audioCapturer.state; + // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('AudioRecLog: Capturer already released'); + return; + } + + await audioCapturer.release(); + + state = audioCapturer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + } + ``` + +6. (可选)获取采集器相关信息 + + 通过以下代码,可以获取采集器的相关信息。 + + ```js + // 获取当前采集器状态 + let state = audioCapturer.state; + + // 获取采集器信息 + let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); + + // 获取音频流信息 + let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); + + // 获取音频流ID + let audioStreamId : number = await audioCapturer.getAudioStreamId(); + + // 获取纳秒形式的Unix时间戳 + let audioTime : number = await audioCapturer.getAudioTime(); + + // 获取合理的最小缓冲区大小 + let bufferSize : number = await audioCapturer.getBuffersize(); + ``` + +7. (可选)使用on('markReach')方法订阅采集器标记到达事件,使用off('markReach')取消订阅事件。 + + 注册markReach监听后,当采集器采集的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioCapturer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The Capturer reached frame: ${reachNumber}`); + }); + + audioCapturer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + ``` + +8. (可选)使用on('periodReach')方法订阅采集器区间标记到达事件,使用off('periodReach')取消订阅事件。 + + 注册periodReach监听后,**每当**采集器采集的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioCapturer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the Capturer reached frame: ${reachNumber}`); + }); + + audioCapturer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + ``` + +9. 如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件,当采集器状态更新时,会受到一个包含有事件类型的回调。 + + ```js + audioCapturer.on('stateChange', (state) => { + console.info(`AudioCapturerLog: Changed State to : ${state}`) + switch (state) { + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } + }); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md index 5b833306e08d8370f6d8433fdcc3dd91f9af01ce..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,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。 @@ -105,8 +109,9 @@ async function audioPlayerDemo() { setCallBack(audioPlayer); // 设置事件回调 // 2. 用户选择音频,设置uri let fdPath = 'fd://' - // path路径的码流可通过"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" 命令,将其推送到设备上 - 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" // 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 = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -124,6 +129,7 @@ async function audioPlayerDemo() { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' + export class AudioDemo { // 设置播放器回调函数 setCallBack(audioPlayer) { @@ -145,8 +151,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例 this.setCallBack(audioPlayer); // 设置事件回调 let fdPath = 'fd://' - // path路径的码流可通过"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" 命令,将其推送到设备上 - 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" // 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 = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -165,6 +172,7 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' + export class AudioDemo { // 设置播放器回调函数 private isNextMusic = false; @@ -191,8 +199,9 @@ export class AudioDemo { async nextMusic(audioPlayer) { this.isNextMusic = true; let nextFdPath = 'fd://' - // path路径的码流可通过"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" 命令,将其推送到设备上 - 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" // 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 = pathDir + '/02.mp3' await fileIO.open(nextpath).then((fdNumber) => { nextFdPath = nextFdPath + '' + fdNumber; console.info('open fd success fd is' + nextFdPath); @@ -208,8 +217,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例 this.setCallBack(audioPlayer); // 设置事件回调 let fdPath = 'fd://' - // path路径的码流可通过"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" 命令,将其推送到设备上 - 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" // 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 = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -228,6 +238,7 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' + export class AudioDemo { // 设置播放器回调函数 setCallBack(audioPlayer) { @@ -245,8 +256,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例 this.setCallBack(audioPlayer); // 设置事件回调 let fdPath = 'fd://' - // path路径的码流可通过"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" 命令,将其推送到设备上 - 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" // 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 = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); diff --git a/zh-cn/application-dev/media/audio-renderer.md b/zh-cn/application-dev/media/audio-renderer.md index 1e573b9a1edf423c9bb57fac7b337625798d95c8..7be8630c4d1d7cea8a950a0174f03760ad2f927d 100644 --- a/zh-cn/application-dev/media/audio-renderer.md +++ b/zh-cn/application-dev/media/audio-renderer.md @@ -8,6 +8,7 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 - **音频中断**:当优先级较高的音频流需要播放时,AudioRenderer会中断优先级较低的流。例如,当用户在收听音乐时有来电,则优先级较低音乐播放将被暂停。 - **状态检查**:在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioRenderer的状态变更。因为针对AudioRenderer的某些操作,仅在音频播放器在固定状态时才能执行。如果应用在音频播放器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 - **异步操作**:为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数,更多方式可参考[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8)。 +- **焦点模式**:OpenHarmony中有两种焦点模式:**共享焦点模式**和**独立焦点模式**。其中,共享焦点模式是指,同一个应用创建的所有AudioRenderer对象共享一个焦点对象,应用内部无焦点转移,因此无法触发回调通知;独立焦点模式与之相反,即同一个应用创建的每个AudioRenderer对象都拥有独立的焦点对象,会发生焦点抢占,当应用内部发生焦点抢占,将会发生焦点转移,原本拥有焦点的AudioRenderer对象会获取到相关的回调通知。需要注意的是,默认情况下,应用创建的都是共享焦点,开发者可以调用setInterruptMode()来设置创建的焦点模式,完整示例请参考开发指导14。 ## 运作机制 @@ -25,76 +26,281 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 ## 开发指导 +详细API含义可参考:[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8) + 1. 使用createAudioRenderer()创建一个AudioRenderer实例。 - 在audioCapturerOptions中设置相关参数。该实例可用于音频渲染、控制和获取采集状态,以及注册通知回调。 + 在audioRendererOptions中设置相关参数。该实例可用于音频渲染、控制和获取渲染状态,以及注册通知回调。 ```js - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } + import audio from '@ohos.multimedia.audio'; + + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + console.log("Create audio renderer success."); + ``` + +2. 调用start()方法来启动/恢复播放任务。 + + ```js + async function startRenderer() { + let state = audioRenderer.state; + // Renderer start时的状态应该是STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一. + if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && + state != audio.AudioState.STATE_STOPPED) { + console.info('Renderer is not in a correct state to start'); + return; + } + + await audioRenderer.start(); - var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('Renderer started'); + } else { + console.error('Renderer start failed'); + } } + ``` + 启动完成后,渲染器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 + + +3. 调用write()方法向缓冲区写入数据。 + + 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 - var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo + ```js + import fileio from '@ohos.fileio'; + import audio from '@ohos.multimedia.audio'; + + async function writeBuffer(buf) { + // 写入数据时,渲染器的状态必须为STATE_RUNNING + if (audioRenderer.state != audio.AudioState.STATE_RUNNING) { + console.error('Renderer is not running, do not write'); + return; + } + let writtenbytes = await audioRenderer.write(buf); + console.info(`Actual written bytes: ${writtenbytes} `); + if (writtenbytes < 0) { + console.error('Write buffer failed. check the state of renderer'); + } } + + // 此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + const bufferSize = await audioRenderer.getBufferSize(); + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const path = dir + '/file_example_WAV_2MG.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav + console.info(`file path: ${ path}`); + let ss = fileio.createStreamSync(path, 'r'); + const totalSize = fileio.statSync(path).size; // 音乐文件大小 + let discardHeader = new ArrayBuffer(bufferSize); + ss.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + let id = setInterval(() => { + if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为release,停止渲染 + ss.closeSync(); + await audioRenderer.stop(); + clearInterval(id); + } + if (audioRenderer.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize) { // 如果音频文件已经被读取完,停止渲染 + ss.closeSync(); + await audioRenderer.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + writeBuffer(buf); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 + ``` + +4. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 + + ```js + async function pauseRenderer() { + let state = audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING的时候才能暂停 + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + let state = audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` + +5. (可选)调用drain()方法清空缓冲区。 + + ```js + async function drainRenderer() { + let state = audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING的时候才能使用drain() + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.drain(); + + state = audioRenderer.state; + } + ``` + +6. 任务完成,调用release()方法释放相关资源。 + + AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + ```js + async function releaseRenderer() { + let state = audioRenderer.state; + // 渲染器状态不是STATE_RELEASED或STATE_NEW状态,才能release + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('Renderer already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + } + ``` + +7. (可选)获取渲染器相关信息 + + 通过以下代码,可以获取渲染器的相关信息。 + + ```js + // 获取当前渲染器状态 + let state = audioRenderer.state; + + // 获取渲染器信息 + let audioRendererInfo : audio.AudioRendererInfo = await audioRenderer.getRendererInfo(); + + // 获取音频流信息 + let audioStreamInfo : audio.AudioStreamInfo = await audioRenderer.getStreamInfo(); + + // 获取音频流ID + let audioStreamId : number = await audioRenderer.getAudioStreamId(); + + // 获取纳秒形式的Unix时间戳 + let audioTime : number = await audioRenderer.getAudioTime(); + + // 获取合理的最小缓冲区大小 + let bufferSize : number = await audioRenderer.getBuffersize(); + + // 获取渲染速率 + let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); + ``` + +8. (可选)设置渲染器相关信息 + + 通过以下代码,可以设置渲染器的相关信息。 + + ```js + // 设置渲染速率为正常速度 + let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; + await audioRenderer.setRenderRate(renderRate); + + // 设置渲染器音频中断模式为SHARE_MODE + let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; + await audioRenderer.setInterruptMode(interruptMode); + + // 设置一个流的音量为10 + let volume : number = 10; + await audioRenderer.setVolume(volume); ``` -2. 使用on('interrupt')方法订阅音频中断事件。 +9. (可选)使用on('audioInterrupt')方法订阅渲染器音频中断事件,使用off('audioInterrupt')取消订阅事件。 当优先级更高或相等的Stream-B请求激活并使用输出设备时,Stream-A被中断。 在某些情况下,框架会采取暂停播放、降低音量等强制操作,并通过InterruptEvent通知应用。在其他情况下,应用可以自行对InterruptEvent做出响应。 在音频中断的情况下,应用可能会碰到音频数据写入失败的问题。所以建议不感知、不处理中断的应用在写入音频数据前,使用audioRenderer.state检查播放器状态。而订阅音频中断事件,可以获取到更多详细信息,具体可参考[InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9)。 + + 需要说明的是,本模块的订阅音频中断事件与[AudioManager](../reference/apis/js-apis-audio.md#audiomanager)模块中的on('interrupt')稍有不同。自api9以来,on('interrupt')和off('interrupt')均被废弃。在AudioRenderer模块,当开发者需要监听焦点变化事件时,只需要调用on('audioInterrupt')函数,当应用内部的AudioRenderer对象在start\stop\pause等动作发生时,会主动请求焦点,从而发生焦点转移,相关的AudioRenderer对象即可获取到对应的回调信息。但对除AudioRenderer的其他对象,例如FM、语音唤醒等,应用不会创建对象,此时可调用AudioManager中的on('interrupt')获取焦点变化通知。 ```js - audioRenderer.on('interrupt', (interruptEvent) => { + audioRenderer.on('audioInterrupt', (interruptEvent) => { console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); + console.info(`InterruptType: ${interruptEvent.eventType}`); + console.info(`InterruptForceType: ${interruptEvent.forceType}`); + console.info(`AInterruptHint: ${interruptEvent.hintType}`); if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. + // 音频框架发起的强制暂停操作,为防止数据丢失,此时应该停止数据的写操作 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: isPlay = false; break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. + // 音频框架发起的强制停止操作,为防止数据丢失,此时应该停止数据的写操作 case audio.InterruptHint.INTERRUPT_HINT_STOP: isPlay = false; break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. + // 音频框架发起的强制降低音量操作 case audio.InterruptHint.INTERRUPT_HINT_DUCK: break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. + // 音频框架发起的恢复音量操作 case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: break; } } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. + // 提醒App开始渲染 case audio.InterruptHint.INTERRUPT_HINT_RESUME: startRenderer(); break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. + // 提醒App音频流被中断,由App自主决定是否继续(此处选择暂停) case audio.InterruptHint.INTERRUPT_HINT_PAUSE: isPlay = false; pauseRenderer(); @@ -102,137 +308,236 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 } } }); - ``` - -3. 调用start()方法来启动/恢复播放任务。 - - 启动完成后,渲染器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 - - ```js - async function startRenderer() { - var state = audioRenderer.state; - // state should be prepared, paused or stopped. - if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || - state != audio.AudioState.STATE_STOPPED) { - console.info('Renderer is not in a correct state to start'); - return; - } - - await audioRenderer.start(); - state = audioRenderer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('Renderer started'); - } else { - console.error('Renderer start failed'); - } - } + audioRenderer.off('audioInterrupt'); // 取消音频中断事件的订阅,后续将无法监听到音频中断事件 ``` -4. 调用write()方法向缓冲区写入数据。 +10. (可选)使用on('markReach')方法订阅渲染器标记到达事件,使用off('markReach')取消订阅事件。 - 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 + 注册markReach监听后,当渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioRenderer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The renderer reached frame: ${reachNumber}`); + }); - ```js - async function writeBuffer(buf) { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - isPlay = false; - return; - } - let writtenbytes = await audioRenderer.write(buf); + audioRenderer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + ``` - console.info('Actual written bytes: ' + writtenbytes); - if (writtenbytes < 0) { - console.error('Write buffer failed. check the state of renderer'); - } - } +11. (可选)使用on('periodReach')方法订阅渲染器区间标记到达事件,使用off('periodReach')取消订阅事件。 + + 注册periodReach监听后,**每当**渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 - // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. - const bufferSize = await audioRenderer.getBufferSize(); - const path = '/data/file_example_WAV_2MG.wav'; - let ss = fileio.createStreamSync(path, 'r'); - const totalSize = 2146166; // file_example_WAV_2MG.wav - let rlen = 0; - let discardHeader = new ArrayBuffer(44); - ss.readSync(discardHeader); - rlen += 44; + ```js + audioRenderer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the renderer reached frame: ${reachNumber} `); + }); - var id = setInterval(() => { - if (isPlay || isRelease) { - if (rlen >= totalSize || isRelease) { - ss.closeSync(); - stopRenderer(); - clearInterval(id); - } - let buf = new ArrayBuffer(bufferSize); - rlen += ss.readSync(buf); - console.info('Total bytes read from file: ' + rlen); - writeBuffer(buf); - } else { - console.info('check after next interval'); - } - } , 30); // interval to be set based on audio file format - ``` + audioRenderer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + ``` -5. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 +12. (可选)使用on('stateChange')方法订阅渲染器音频状态变化事件。 - ```js - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } + 注册stateChange监听后,当渲染器的状态发生改变时,会触发回调并返回当前渲染器的状态。 + + ```js + audioRenderer.on('stateChange', (audioState) => { + console.info('State change event Received'); + console.info(`Current renderer state is: ${audioState}`); + }); + ``` - await audioRenderer.pause(); +13. (可选)对on()方法的异常处理。 - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } + 在使用on()方法时,如果传入的字符串错误或传入的参数类型错误,程序会抛出异常,需要用try catch来捕获。 + + ```js + try { + audioRenderer.on('invalidInput', () => { // 字符串不匹配 + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // 程序抛出401异常 + } + try { + audioRenderer.on(1, () => { // 入参类型错误 + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // 程序抛出6800101异常 + } + ``` + +14. (可选)on('audioInterrupt')方法完整示例。 + 同一个应用中的AudioRender1和AudioRender2在创建时均设置了焦点模式为独立,并且调用on('audioInterrupt')监听焦点变化。刚开始AudioRender1拥有焦点,当AudioRender2获取到焦点时,audioRenderer1将收到焦点转移的通知,打印相关日志。如果AudioRender1和AudioRender2不将焦点模式设置为独立,则监听处理中的日志在应用运行过程中永远不会被打印。 + ```js + async runningAudioRender1(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; + //1.1 创建对象 + audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); + console.info("Create audio renderer 1 success."); + + //1.2 设置焦点模式为独立模式 :1 + audioRenderer1.setInterruptMode(1).then( data => { + console.info('audioRenderer1 setInterruptMode Success!'); + }).catch((err) => { + console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); + }); + + //1.3 设置监听 + audioRenderer1.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + }); + + //1.4 启动渲染 + await audioRenderer1.start(); + console.info('startAudioRender1 success'); + + //1.5 获取缓存区大小,此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + const bufferSize = await audioRenderer1.getBufferSize(); + console.info(`audio bufferSize: ${bufferSize}`); + + //1.6 获取原始音频数据文件 + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const path1 = dir + '/music001_48000_32_1.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav + console.info(`audioRender1 file path: ${ path1}`); + let ss1 = await fileio.createStream(path1,'r'); + const totalSize1 = fileio.statSync(path1).size; // 音乐文件大小 + console.info(`totalSize1 -------: ${totalSize1}`); + let discardHeader = new ArrayBuffer(bufferSize); + ss1.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + //2.7 通过audioRender对缓存区的原始音频数据进行渲染 + let id = setInterval(async () => { + if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为release,停止渲染 + ss1.closeSync(); + audioRenderer1.stop(); + clearInterval(id); + } + if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize1) { // 如果音频文件已经被读取完,停止渲染 + ss1.closeSync(); + await audioRenderer1.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss1.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + await writeBuffer(buf, that.audioRenderer1); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 } - await audioRenderer.stop(); + async runningAudioRender2(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); + //2.1 创建对象 + audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); + console.info("Create audio renderer 2 success."); + + //2.2 设置焦点模式为独立模式 :1 + audioRenderer2.setInterruptMode(1).then( data => { + console.info('audioRenderer2 setInterruptMode Success!'); + }).catch((err) => { + console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); + }); + + //2.3 设置监听 + audioRenderer2.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + }); + + //2.4 启动渲染 + await audioRenderer2.start(); + console.info('startAudioRender2 success'); + + //2.5 获取缓存区大小 + const bufferSize = await audioRenderer2.getBufferSize(); + console.info(`audio bufferSize: ${bufferSize}`); + + //2.6 读取原始音频数据文件 + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const path2 = dir + '/music002_48000_32_1.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav + console.error(`audioRender1 file path: ${ path2}`); + let ss2 = await fileio.createStream(path2,'r'); + const totalSize2 = fileio.statSync(path2).size; // 音乐文件大小 + console.error(`totalSize2 -------: ${totalSize2}`); + let discardHeader2 = new ArrayBuffer(bufferSize); + ss2.readSync(discardHeader2); + let rlen = 0; + rlen += bufferSize; + + //2.7 通过audioRender对缓存区的原始音频数据进行渲染 + let id = setInterval(async () => { + if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为release,停止渲染 + ss2.closeSync(); + that.audioRenderer2.stop(); + clearInterval(id); + } + if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize2) { // 如果音频文件已经被读取完,停止渲染 + ss2.closeSync(); + await audioRenderer2.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss2.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + await writeBuffer(buf, that.audioRenderer2); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 } - } - ``` - -6. 任务完成,调用release()方法释放相关资源。 - AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 - - ```js - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; + async writeBuffer(buf, audioRender) { + let writtenbytes; + await audioRender.write(buf).then((value) => { + writtenbytes = value; + console.info(`Actual written bytes: ${writtenbytes} `); + }); + if (typeof(writtenbytes) != 'number' || writtenbytes < 0) { + console.error('get Write buffer failed. check the state of renderer'); + } } - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); + //综合调用入口 + async test(){ + await runningAudioRender1(); + await runningAudioRender2(); } - } - ``` \ No newline at end of file + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-routing-manager.md b/zh-cn/application-dev/media/audio-routing-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..4d5f07047ccd27952945dbc61bc7a37fcb8a0bbe --- /dev/null +++ b/zh-cn/application-dev/media/audio-routing-manager.md @@ -0,0 +1,112 @@ +# 路由、设备管理开发指导 + +## 简介 + +AudioRoutingManager提供了音频路由、设备管理的方法。开发者可以通过本指导了解应用如何通过AudioRoutingManager获取当前工作的输入、输出音频设备,监听音频设备的连接状态变化,激活通信设备等。 + +## 运作机制 + +该模块提供了路由、设备管理模块常用接口 + +**图1** 音量管理常用接口 + +![zh-ch_image_audio_routing_manager](figures/zh-ch_image_audio_routing_manager.png) + +**说明:** AudioRoutingManager主要接口有:获取设备列表信息、监听与取消监听设备连接状态、激活通信设备、查询通信设备激活状态。更多介绍请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + +## 开发指导 + +详细API含义可参考:[音频路由、设备管理API文档AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9) + +1. 创建AudioRoutingManager实例。 + + 在使用AudioRoutingManager的API前,需要使用getRoutingManager创建一个AudioRoutingManager实例。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + + ``` + +2. (可选)获取设备列表信息、监听设备链接状态变化。 + + 如果开发者需要获取设备列表信息(输入、输出、分布式输入、分布式输出等),或者监听音频设备的链接状态变化时,可参考并调用以下接口。 + + ```js + import audio from '@ohos.multimedia.audio'; + //创建AudioRoutingManager实例 + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + //获取全部音频设备信息(开发者可以根据自身需要填入适当的DeviceFlag) + async getDevices() { + await loadAudioRoutingManager(); + await audioRoutingManager.getDevices(audio.DeviceFlag.ALL_DEVICES_FLAG).then((data) => { + console.info(`getDevices success and data is: ${JSON.stringify(data)}.`); + }); + } + //监听音频设备状态变化 + async onDeviceChange() { + await loadAudioRoutingManager(); + await audioRoutingManager.on('deviceChange', audio.DeviceFlag.ALL_DEVICES_FLAG, (deviceChanged) => { + console.info('on device change type : ' + deviceChanged.type); + console.info('on device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } + //取消监听音频设备状态变化 + async offDeviceChange() { + await loadAudioRoutingManager(); + await audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('off device change type : ' + deviceChanged.type); + console.info('off device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } + //综合调用:先查询所有设备,设置监听,然后开发者手动变更设备连接(例如有线耳机),再次查询所有设备,最后取消设备状态变化的监听。 + async test(){ + await getDevices(); + await onDeviceChange()(); + //开发者手动断开/连接设备 + await getDevices(); + await offDeviceChange(); + } + ``` + +3. (可选)设置通信设备激活并查询激活状态。 + + ```js + import audio from '@ohos.multimedia.audio'; + //创建AudioRoutingManager实例 + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + //设置通信设备激活状态 + async setCommunicationDevice() { + await loadAudioRoutingManager(); + await audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('setCommunicationDevice true is success.'); + }); + } + //查询通信设备激活状态 + async isCommunicationDeviceActive() { + await loadAudioRoutingManager(); + await audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`CommunicationDevice state is: ${value}.`); + }); + } + //综合调用:先设置设备激活,然后查询设备状态。 + async test(){ + await setCommunicationDevice(); + await isCommunicationDeviceActive(); + } + ``` + diff --git a/zh-cn/application-dev/media/audio-volume-manager.md b/zh-cn/application-dev/media/audio-volume-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..d26175b8822b49aafd9a5e7a0e26b009a1e8d451 --- /dev/null +++ b/zh-cn/application-dev/media/audio-volume-manager.md @@ -0,0 +1,127 @@ +# 音量管理开发指导 + +## 简介 + +AudioVolumeManager提供了音量管理的方法。开发者可以通过本指导了解应用如何通过AudioVolumeManager获取指定流音量信息、监听铃声模式变化、设置麦克风静音等。 + +## 运作机制 + +该模块提供了音量管理模块常用接口 + +**图1** 音量管理常用接口 + +![zh-ch_image_audio_volume_manager](figures/zh-ch_image_audio_volume_manager.png) + +**说明:** AudioVolumeManager包含音量变化监听处理和音频音量组管理相关(AudioVolumeGroupManager),开发者调用AudioVolumeGroupManager的相关方法,需要先调用getVolumeGroupManager方法创建AudioVolumeGroupManager实例,从而调用对应的接口实现相应的功能,主要接口有:获取指定流的音量、设置麦克风静音、监听麦克风状态变化等。更多介绍请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + +## 约束与限制 + +开发者在进行麦克风管理开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE),如果要设置麦克风状态,则需要配置音频管理配置权限(ohos.permission.MANAGE_AUDIO_CONFIG),需注意该权限为系统级别权限。权限配置相关内容可参考:[访问控制授权申请指导](../security/accesstoken-guidelines.md) + +## 开发指导 + +详细API含义可参考:[音量管理API文档AudioVolumeManager](../reference/apis/js-apis-audio.md#audiovolumemanager9) + +1. 创建AudioVolumeGroupManager实例。 + + 在使用AudioVolumeGroupManager的API前,需要使用getVolumeGroupManager创建一个AudioStreamManager实例。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.error('audioVolumeGroupManager create success.'); + } + + ``` + +2. (可选)获取音量信息、铃声模式。 + + 如果开发者需要获取指定音频流的音量信息(铃声、语音电话、媒体、语音助手等),或者获取当前设备是静音、震动、响铃模式,可参考并调用以下接口。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + + //获取指定流的当前音量(范围为0 ~ 15) + async getVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getVolume success and volume is: ${value}.`); + }); + } + //获取指定流的最小音量 + async getMinVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getMinVolume success and volume is: ${value}.`); + }); + } + //获取指定流的最大音量 + async getMaxVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getMaxVolume success and volume is: ${value}.`); + }); + } + //获取当前铃声模式: 静音(0)| 震动(1) | 响铃(2) + async getRingerMode() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`getRingerMode success and RingerMode is: ${value}.`); + }); + } + ``` + +3. (可选)查询、设置、监听麦克风状态。 + + 如果开发者需要获取、设置麦克风状态,或者监听麦克风状态变化等信息,可参考并调用以下接口。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + + async on() { //监听麦克风状态变化 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); + }); + } + + async isMicrophoneMute() { //查询麦克风是否静音 + await audioVolumeGroupManager.audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`isMicrophoneMute is: ${value}.`); + }); + } + + async setMicrophoneMuteTrue() { //设置麦克风静音 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('setMicrophoneMute to mute.'); + }); + } + + async setMicrophoneMuteFalse() { //取消麦克风静音 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(false).then(() => { + console.info('setMicrophoneMute to not mute.'); + }); + } + async test(){ //综合调用:先设置监听,然后查询麦克风状态,设置麦克风静音后再查询状态,最后取消麦克风静音。 + await on(); + await isMicrophoneMute(); + await setMicrophoneMuteTrue(); + await isMicrophoneMute(); + await setMicrophoneMuteFalse(); + } + ``` + diff --git a/zh-cn/application-dev/media/camera.md b/zh-cn/application-dev/media/camera.md index 60f0348ee1442aba10a477226a3effd969151c98..12c785c1d5cd84044cc43466661e515673fcb66c 100644 --- a/zh-cn/application-dev/media/camera.md +++ b/zh-cn/application-dev/media/camera.md @@ -59,7 +59,8 @@ import image from '@ohos.multimedia.image' import media from '@ohos.multimedia.media' // 创建CameraManager对象 -let cameraManager = await camera.getCameraManager(null) +context: any = getContext(this) +let cameraManager = await camera.getCameraManager(this.context) if (!cameraManager) { console.error('Failed to get the CameraManager instance'); } @@ -78,52 +79,48 @@ for (let index = 0; index < cameraArray.length; index++) { } // 创建相机输入流 -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]) // 获取相机设备支持的输出流能力 -let cameraOutputCap = await camera.getSupportedOutputCapability(cameraInput); +let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]); if (!cameraOutputCap) { console.error("outputCapability outputCapability == null || undefined") } else { console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); } -let previewProfilesArray = cameraOutputCap.previewProfiles; +let previewProfilesArray = cameraOutputCap.GetPreviewProfiles(); if (!previewProfilesArray) { console.error("createOutput previewProfilesArray == null || undefined") } -let photoProfilesArray = cameraOutputCap.photoProfiles; +let photoProfilesArray = cameraOutputCap.GetPhotoProfiles(); if (!photoProfilesArray) { console.error("createOutput photoProfilesArray == null || undefined") } -let videoProfilesArray = cameraOutputCap.videoProfiles; +let videoProfilesArray = cameraOutputCap.GetVideoProfiles(); if (!videoProfilesArray) { console.error("createOutput videoProfilesArray == null || undefined") } -let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; +let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType(); if (!metadataObjectTypesArray) { console.error("createOutput metadataObjectTypesArray == null || undefined") } -// 创建预览输出流 -let previewOutput = await camera.createPreviewOutput(previewProfilesArray[0], surfaceId) +// 创建预览输出流,其中参数 surfaceId 参考下面 XComponent 组件,预览流为XComponent组件提供的surface +let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) if (!previewOutput) { console.error("Failed to create the PreviewOutput instance.") } -// 创建ImageReceiver对象,并设置照片参数 +// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) // 获取照片显示SurfaceId let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() // 创建拍照输出流 -let photoOutput = await this.camera.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) +let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) if (!photoOutput) { console.error('Failed to create the PhotoOutput instance.'); return; @@ -155,20 +152,21 @@ let videoConfig = { // 创建录像输出流 let videoRecorder -await media.createVideoRecorder().then((recorder) => { +media.createVideoRecorder().then((recorder) => { console.log('createVideoRecorder called') videoRecorder = recorder }) // 设置视频录制的参数 -await videoRecorder.prepare(videoConfig) +videoRecorder.prepare(videoConfig) //获取录像SurfaceId -await videoRecorder.getInputSurface().then((id) => { +let videoSurfaceId +videoRecorder.getInputSurface().then((id) => { console.log('getInputSurface called') videoSurfaceId = id }) // 创建VideoOutput对象 -let videoOutput = camera.createVideoOutput(videoProfilesArray[0], videoSurfaceId) +let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) if (!videoOutput) { console.error('Failed to create the videoOutput instance.'); return; @@ -190,7 +188,7 @@ build() { controller: this.mXComponentController }) .onload(() => { // 设置onload回调 - // 设置Surface宽高(1920*1080) + // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) // 获取Surface ID globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() @@ -205,11 +203,11 @@ build() { ```typescript function getImageReceiverSurfaceId() { - var receiver = image.createImageReceiver(640, 480, 4, 8) + let receiver = image.createImageReceiver(640, 480, 4, 8) console.log(TAG + 'before ImageReceiver check') if (receiver !== undefined) { console.log('ImageReceiver is ok') - surfaceId1 = await receiver.getReceivingSurfaceId() + surfaceId1 = receiver.getReceivingSurfaceId() console.log('ImageReceived id: ' + JSON.stringify(surfaceId1)) } else { console.log('ImageReceiver is not ok') @@ -399,17 +397,17 @@ videoOutput.start(async (err) => { }); // 开始录像 -await videoRecorder.start().then(() => { +videoRecorder.start().then(() => { console.info('videoRecorder start success'); } // 停止录像 -await videoRecorder.stop().then(() => { +videoRecorder.stop().then(() => { console.info('stop success'); } // 停止录像输出流 -await videoOutput.stop((err) => { +videoOutput.stop((err) => { if (err) { console.error('Failed to stop the video output ${err.message}'); return; @@ -424,22 +422,22 @@ await videoOutput.stop((err) => { ```typescript // 停止当前会话 -await captureSession.stop() +captureSession.stop() // 释放相机输入流 -await cameraInput.release() +cameraInput.release() // 释放预览输出流 -await previewOutput.release() +previewOutput.release() // 释放拍照输出流 -await photoOutput.release() +photoOutput.release() // 释放录像输出流 -await videoOutput.release() +videoOutput.release() // 释放会话 -await captureSession.release() +captureSession.release() // 会话置空 captureSession = null diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png new file mode 100644 index 0000000000000000000000000000000000000000..710679f6cac0c30d06dffa97b0e80b3cebe80f79 Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png index 7497edd0edbdcfccbc448e9f2f48268ebb75e72e..22b7aeaa1db5b369d3daf44854d7f7f9a00f775b 100644 Binary files a/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_volume_manager.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_volume_manager.png new file mode 100644 index 0000000000000000000000000000000000000000..0d47fbfacce9c1ff48811e1cf5d764231bdb596b Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_volume_manager.png differ diff --git a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md index fa5d32573516b4da0bde2d7a931d5fac6e901792..057948c52a68b8525b0f7c815039139f31ddcb54 100644 --- a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md +++ b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md @@ -24,7 +24,7 @@ MindSpore Lite是一款AI引擎,它提供了面向不同硬件设备AI模型 | ------------------ | ----------------- | |OH_AI_ContextHandle OH_AI_ContextCreate()|创建一个上下文的对象。| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|设置运行时的线程数量。| -| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|设置运行时线程绑定CPU核心的策略。一般情况下CPU会按照频率分为大小核,即频率较高的为大核,频率较低的为小核。| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|创建一个运行时设备信息对象。| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|释放上下文对象。| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|设置是否开启Float16推理模式,仅CPU/GPU设备可用。| diff --git a/zh-cn/application-dev/napi/napi-guidelines.md b/zh-cn/application-dev/napi/napi-guidelines.md index 84c0b827089cf8001181fa2b45b6c2b820431d57..9ff575a8e0755a2546cc51b78d48df76b9746a85 100644 --- a/zh-cn/application-dev/napi/napi-guidelines.md +++ b/zh-cn/application-dev/napi/napi-guidelines.md @@ -642,7 +642,7 @@ export default { } ``` ## 相关实例 + 针对Native API的开发,有以下相关实例可供参考: -- [`NativeAPI`:NativeAPI(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Native/NativeAPI) - [第一个Native C++应用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) - [Native Component(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/Readme-CN.md b/zh-cn/application-dev/quick-start/Readme-CN.md index 429b62a2cf66d8a20401184d8fa6fc3a56a3f7a9..64e10076782a08f6aea0572f55d421b22603c086 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -8,7 +8,6 @@ - [应用包结构说明(FA模型)](package-structure.md) - [应用包结构说明(Stage模型)](stage-structure.md) - [SysCap说明](syscap.md) - - [HarmonyAppProvision配置文件](app-provision-structure.md) - [资源分类与访问](resource-categories-and-access.md) - 学习ArkTS语言 - [初识ArkTS语言](arkts-get-started.md) diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control.md b/zh-cn/application-dev/quick-start/arkts-rendering-control.md index 08663ab440ede2aa39dcc722da1fdb54217942a3..11066681cec9d1e13a10c4031dd407c9e72abb70 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control.md @@ -125,8 +125,8 @@ interface DataChangeListener { | 参数名 | 参数类型 | 必填 | 参数描述 | | ------------- | --------------------- | ---- | ------------------------------------------------------------ | | dataSource | IDataSource | 是 | 实现IDataSource接口的对象,需要开发者实现相关接口。 | -| itemGenerator | (item: any) => void | 是 | 生成子组件的lambda函数,为数组中的每一个数据项创建一个或多个子组件,单个子组件或子组件列表必须包括在大括号“{...}”中。 | -| keyGenerator | (item: any) => string | 否 | 匿名函数,用于给数组中的每一个数据项生成唯一且固定的键值。当数据项在数组中的位置更改时,其键值不得更改,当数组中的数据项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 | +| itemGenerator | (item: any, index?: number) => void | 是 | 生成子组件的lambda函数,为数组中的每一个数据项创建一个或多个子组件,单个子组件或子组件列表必须包括在大括号“{...}”中。 | +| keyGenerator | (item: any, index?: number) => string | 否 | 匿名函数,用于给数组中的每一个数据项生成唯一且固定的键值。当数据项在数组中的位置更改时,其键值不得更改,当数组中的数据项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 | ### IDataSource类型说明 @@ -142,14 +142,14 @@ interface DataChangeListener { | 名称 | 描述 | | -------------------------------------------------------- | -------------------------------------- | | onDataReloaded(): void | 重新加载所有数据。 | -| onDataAdded(index: number): void (deprecated) | 通知组件index的位置有数据添加。 | -| onDataMoved(from: number, to: number): void (deprecated) | 通知组件数据从from的位置移到to的位置。 | -| onDataDeleted(index: number): void (deprecated) | 通知组件index的位置有数据删除。 | -| onDataChanged(index: number): void (deprecated) | 通知组件index的位置有数据变化。 | -| onDataAdd(index: number): void 8+ | 通知组件index的位置有数据添加。 | -| onDataMove(from: number, to: number): void 8+ | 通知组件数据从from的位置移到to的位置。 | -| onDataDelete(index: number): void 8+ | 通知组件index的位置有数据删除。 | -| onDataChange(index: number): void 8+ | 通知组件index的位置有数据变化。 | +| onDataAdded(index: number): voiddeprecated | 通知组件index的位置有数据添加。从API Version 8开始废弃,建议使用onDataAdd。 | +| onDataMoved(from: number, to: number): voiddeprecated | 通知组件数据从from的位置移到to的位置。从API Version 8开始废弃,建议使用onDataMove。 | +| onDataDeleted(index: number): voiddeprecated | 通知组件index的位置有数据删除。从API Version 8开始废弃,建议使用onDataDelete。 | +| onDataChanged(index: number): voiddeprecated | 通知组件index的位置有数据变化。 从API Version 8开始废弃,建议使用onDataChange。 | +| onDataAdd(index: number): void8+ | 通知组件index的位置有数据添加。 | +| onDataMove(from: number, to: number): void8+ | 通知组件数据从from的位置移到to的位置。 | +| onDataDelete(index: number): void8+ | 通知组件index的位置有数据删除。 | +| onDataChange(index: number): void8+ | 通知组件index的位置有数据变化。 | ## 示例 diff --git a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md index 959f924a34bbe7fd48ded0a20c3b38178b323035..0f67972ef260d3e515a5d9a9d4b35694d8e35d1b 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md @@ -1,6 +1,6 @@ # 页面级变量的状态管理 -@State、@Prop、@Link、@Provide、Consume、@ObjectLink、@Observed和@Watch用于管理页面级变量的状态。 +@State、@Prop、@Link、@Provide、@Consume、@ObjectLink、@Observed和@Watch用于管理页面级变量的状态。 请参考[状态变量多种数据类型声明的使用限制](./arkts-restrictions-and-extensions.md)了解@State、@Provide、 @Link和@Consume四种状态变量的约束条件。 @@ -468,6 +468,11 @@ struct CompC { 装饰器@State、@Prop、@Link、@ObjectLink、@Provide、@Consume、@StorageProp以及@StorageLink所装饰的变量均可以通过@Watch监听其变化。 + +> **说明:** +> +> 深层次数据修改不会触发@Watch回调,例如无法监听数组中对象值的改变。 + ```ts // xxx.ets @Entry diff --git a/zh-cn/application-dev/quick-start/figures/01.png b/zh-cn/application-dev/quick-start/figures/01.png index cb9ddd68fc3ee2e6e15700a6a7a5d9e6ff1f4cc7..8342856ec6643e20a941187852e6aef3ead11010 100644 Binary files a/zh-cn/application-dev/quick-start/figures/01.png and b/zh-cn/application-dev/quick-start/figures/01.png differ diff --git a/zh-cn/application-dev/quick-start/figures/02.png b/zh-cn/application-dev/quick-start/figures/02.png index 4fd0a6d3e60c0a22a9b69ea9f46fe62050d37a7e..19dd76ca232282b19883dde63075c5d155e7db70 100644 Binary files a/zh-cn/application-dev/quick-start/figures/02.png and b/zh-cn/application-dev/quick-start/figures/02.png differ diff --git a/zh-cn/application-dev/quick-start/figures/04.png b/zh-cn/application-dev/quick-start/figures/04.png index 2d66f7513893e83e4e897ed63319316d9f5bd40e..cf23d17c7ee8552e30a5b234c97862b51981dcf8 100644 Binary files a/zh-cn/application-dev/quick-start/figures/04.png and b/zh-cn/application-dev/quick-start/figures/04.png differ diff --git a/zh-cn/application-dev/quick-start/figures/07.png b/zh-cn/application-dev/quick-start/figures/07.png index 1a232454b8485269d473611b126489c87d2f82d9..0f34d01d824ae1780c73cade9a39fff5f4b9b84e 100644 Binary files a/zh-cn/application-dev/quick-start/figures/07.png and b/zh-cn/application-dev/quick-start/figures/07.png differ diff --git a/zh-cn/application-dev/quick-start/figures/09.png b/zh-cn/application-dev/quick-start/figures/09.png index ac6dbbab11846274c42bfdd61f7bd5dfe0ace99f..2c08d85c610336a71b06407800603ed5c101606d 100644 Binary files a/zh-cn/application-dev/quick-start/figures/09.png and b/zh-cn/application-dev/quick-start/figures/09.png differ diff --git a/zh-cn/application-dev/quick-start/figures/@state.png b/zh-cn/application-dev/quick-start/figures/@state.png deleted file mode 100644 index 7c59f21eddc408bb9d13ef82420674fd094e5a7d..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/@state.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175120.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175120.png deleted file mode 100644 index 12978dc861aaa1f826404d9c6838bb8628381615..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175120.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175132.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175132.png index 2f401b2f8aa84e89bdef25bcf615ff1a621ab6d6..5eb654b04cbb85cda6e910949cd6312db6e1f969 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175132.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311175132.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334944.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334944.png index 9ce82237297b06c04113d0368d7145661de0d997..9f98b8a28700b08b1bbed0c7a42bdb827fd64667 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334944.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334944.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334972.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334972.png deleted file mode 100644 index 6499d0b2de7ee290b958059d13d9d19995e0e511..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334972.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334976.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334976.png index 7891c03e8fab1eaaf6159964fc338e0be9bb080a..fbbde9923a131d3ab69257b28cfe33ca2a1040cf 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334976.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311334976.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494580.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494580.png deleted file mode 100644 index 6c1ea01d448434e7cfd94e174474e72b57d3b4cc..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494580.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494592.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494592.png index a88a2ec512c0fa4f374d1e9ac03a27c717aeab58..a8fac2a024e51aeb0439463dab83f2763fa3fa76 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494592.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494592.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494604.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494604.png deleted file mode 100644 index 6c1ea01d448434e7cfd94e174474e72b57d3b4cc..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001311494604.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001363934577.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001363934577.png deleted file mode 100644 index 6499d0b2de7ee290b958059d13d9d19995e0e511..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001363934577.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001363934589.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001363934589.png deleted file mode 100644 index 2f401b2f8aa84e89bdef25bcf615ff1a621ab6d6..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001363934589.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png index a69b0c6f3b047e5961b05b40b663ce972a90b459..bcc45efdddb87a39201661c5f6d3ccbce9bfd3e6 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364173989.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364173989.png deleted file mode 100644 index f4b6f516a8340914c41600ef24012dd3699648b6..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364173989.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364174013.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364174013.png deleted file mode 100644 index 12978dc861aaa1f826404d9c6838bb8628381615..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364174013.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254729.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254729.png index 7fba7aab32a92752b341af024ef97e5acfe3d73d..164371727ee8a351e2c42f4b3ecab9175e088e7c 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254729.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254729.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254741.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254741.png deleted file mode 100644 index fbbde9923a131d3ab69257b28cfe33ca2a1040cf..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254741.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254773.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254773.png deleted file mode 100644 index 6499d0b2de7ee290b958059d13d9d19995e0e511..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364254773.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001384652328.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001384652328.png new file mode 100644 index 0000000000000000000000000000000000000000..e1ece174d44626d95ded4be698531937bde650a3 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001384652328.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001435376433.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001435376433.png new file mode 100644 index 0000000000000000000000000000000000000000..45a608777708de9a4e8fbe6148974b489aa0388d Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001435376433.png differ diff --git a/zh-cn/application-dev/quick-start/package-structure.md b/zh-cn/application-dev/quick-start/package-structure.md index 462dc9120fb3f296677c5cac7d2390078f41fe67..c51e7a2855d52515c947406c6c1cbe0d178f938b 100755 --- a/zh-cn/application-dev/quick-start/package-structure.md +++ b/zh-cn/application-dev/quick-start/package-structure.md @@ -92,9 +92,6 @@ app对象包含应用全局配置信息,内部结构说明参见表2。 | vendor | 标识对应用开发厂商的描述。字符串长度不超过255字节。 | 字符串 | 可缺省,缺省值为空 | | version | 标识应用的版本信息。参考表3。 | 对象 | 否 | | apiVersion | 标识应用程序所依赖的OpenHarmony API版本。参考表4。 | 对象 | 可缺省,缺省值为空 | -| singleton | 标识应用是否开启单例模式,仅支持系统应用,三方应用配置不生效。如果配置为true,在多用户场景下,该应用仍然单实例运行,不会随用户切换而变动,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为false | -| removable | 标识应用是否可卸载,仅支持系统应用,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true | -| userDataClearable | 标识是否允许应用清除用户数据,仅支持系统应用,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true | 表3 version内部结构说明 diff --git a/zh-cn/application-dev/quick-start/stage-structure.md b/zh-cn/application-dev/quick-start/stage-structure.md index dbdb68f9ae500bd586ec8fc85f20159cf1bcf8b6..fe72991043a1e313e677f968c8240d6b96bec2fa 100755 --- a/zh-cn/application-dev/quick-start/stage-structure.md +++ b/zh-cn/application-dev/quick-start/stage-structure.md @@ -2,7 +2,7 @@ # 应用包结构配置文件的说明 -在开发FA模型下的应用程序时,需要在config.json文件中对应用的包结构进行申明;同样的,在开发stage模型下的应用程序时,需要在module.json5和app.json配置文件中对应用的包结构进行声明。 +在开发stage模型的应用程序时,需要在app.json5和module.json5配置文件中对应用的包结构进行声明。 ## 配置文件内部结构 @@ -12,18 +12,41 @@ | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | ---------- | -| app | 标识应用的全局配置信息。参考[app对象内部结构](#app对象内部结构)。 | 对象 | 否 | -| module | 标识HAP包的配置信息。该标签下的配置只对当前HAP包生效。参考[module对象内部结构](#module对象内部结构)。 | 对象 | 否 | +| app | 标识应用的全局配置信息。参考[app对象内部结构](#app对象内部结构)。 | 对象 | 不可缺省。 | +| module | 标识HAP包的配置信息。该标签下的配置只对当前HAP包生效。参考[module对象内部结构](#module对象内部结构)。 | 对象 | 不可缺省。 | ### app对象内部结构 -app.json示例: +该标签为整个应用的属性,影响应用中所有HAP及组件。该标签的内部结构参见表2。 + +表2 app对象的内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | +| bundleName | 该标签标识应用的包名,用于标识应用的唯一性。标签的值命名规则 :
1)字符串以字母、数字、下划线和符号”.”组成;
2)以字母开头;
3)最小长度7字节,最大长度127个字节。
推荐采用反域名形式命名(如 :com.example.xxx,建议第一级为域名后缀com,第二级为厂商/个人名,第三级为应用名,也可以多级)。 | 字符串 | 不可缺省。 | +| debug | 该标签标识应用是否可调试。该标签由IDE编译构建时产生。 | 布尔值 | 可缺省,缺省值为false。 | +| icon | 该标签标识应用的图标,标签值为图标资源文件的索引。 | 字符串 | 不可缺省。 | +| label | 该标签标识应用的名称,标签值为字符串资源的索引。 | 字符串 | 不可缺省。 | +| description | 该标签标识App的描述信息,标签值是是字符串类型或对描述内容的字符串资源索引。 | 字符串 | 可缺省,缺省值为空。 | +| vendor | 该标签是对应用开发厂商的描述。最大长度255字节。 | 字符串 | 可缺省,缺省值为空。 | +| versionCode | 该标签标识应用的版本号,该标签值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。开发者可以将该值设置为任何正整数,但是必须确保应用的新版本都使用比旧版本更大的值。versionCode 值应小于2的31次方。 | 数值 | 不可缺省。 | +| versionName | 该标签标识版本号的文字描述,用于向用户展示。
该标签仅由数字和点构成,推荐采用“A.B.C.D”四段式的形式。四段式推荐的含义如下所示。
第一段 :主版本号/Major,范围0-99,重大修改的版本,如实现新的大功能或重大变化。
第二段 :次版本号/Minor,范围0-99,表示实现较突出的特点,如新功能添加和大问题修复。
第三段 :特性版本号/Feature,范围0-99,标识规划的新版本特性。
第四段 :修订版本号/Patch,范围0-999,表示维护版本,修复bug。 | 字符串 | 不可缺省。 | +| minCompatibleVersionCode | 该标签标识该app能够兼容的最低历史版本号,用于跨设备兼容性判断。 | 数值 | 可缺省。缺省值等于versionCode标签值。| +| minAPIVersion | 该标签标识应用运行需要的SDK的API最小版本。 | 数值 | 可缺省,缺省值为bundle-profile.json5中的compatibleSdkVersion。| +| targetAPIVersion | 该标签标识应用运行需要的API目标版本。 | 数值 | 可缺省,缺省值为bundle-profile.json5中的compileSdkVersion。| +| apiReleaseType | 该标签标识应用运行需要的API目标版本的类型,采用字符串类型表示。取值为“CanaryN”、“BetaN”或者“Release”,其中,N代表大于零的整数。
Canary :受限发布的版本。
Beta :公开发布的Beta版本。
Release :公开发布的正式版本。
该字段由IDE读取当前使用的SDK的stage来生成。 | 字符串 | 可缺省,由IDE生成并覆盖。 | +| distributedNotificationEnabled | 该标签标记该应用是否开启分布式通知。 | 布尔值 | 可缺省,缺省值为true。 | +| entityType | 该标签标记该应用的类别,具体有 :游戏类(game),影音类(media)、社交通信类(communication)、新闻类(news)、出行类(travel)、工具类(utility)、购物类(shopping)、教育类(education)、少儿类(kids)、商务类(business)、拍摄类(photography)。 | 字符串 | 可缺省,缺省值为"unspecified"。 | +| multiProjects | 标识当前工程是否支持多工程。 | 布尔值 | 可缺省,缺省值为false。 | +| 设备类型 | 该标签可以配置多个,表示具体设备上的特殊配置信息,具体的设备类型有:"tablet"、"tv"、"wearable"、"car"、"default",可包含的字段有:minAPIVersion、distributedNotificationEnabled。 | 对象 | 可缺省,缺省值使用app下面相关的字段。 | + +app.json示例 : ```json { "app": { - "bundleName": "com.application.music", - "vendor": "application", + "bundleName": "bundleName", + "vendor": "vendorName", "versionCode": 1, "versionName": "1.0", "minCompatibleVersionCode": 1, @@ -32,76 +55,73 @@ app.json示例: "apiReleaseType": "Release", "debug": false, "icon": "$media:app_icon", - "label": "$string:app_name", - "description": "$string:description_application", + "label": "$string:app_label", + "description": "$string:app_description", "distributedNotificationEnabled": true, "entityType": "game", "car": { - "apiCompatibleVersion": 8 + "minAPIVersion": 8 } } } ``` -该标签为整个应用的属性,影响应用中所有hap及组件。该标签的内部结构参见表2。 +### module对象内部结构 -表2 app对象的内部结构说明 +HAP包的配置信息,该标签下的配置只对当前HAP包生效。 -| 属性名称 | 含义 | 数据类型 | 是否可缺省 | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | 该标签标识应用的包名,用于标识应用的唯一性。该标签不可缺省。标签的值命名规则 :
1)字符串以字母、数字、下划线和符号”.”组成;
2)以字母开头;
3)最小长度7个字节,最大长度127个字节。
推荐采用反域名形式命名(如 :com.example.xxx,建议第一级为域名后缀com,第二级为厂商/个人名,第三级为应用名,也可以多级)。
其中,随系统源码编译的应用需命名为”com.ohos.xxx”形式, ohos标识OpenHarmony系统应用。 | 字符串 | 否 | -| debug | 该标签标识应用是否可调试。 | 布尔值 | 该标签可以缺省,缺省为false。 | -| icon | 该标签标识应用的图标,标签值为资源文件的索引。 | 字符串 | 该标签不可缺省。 | -| label | 该标签标识应用的的名称,标签值为资源文件的索引,以支持多语言。 | 字符串 | 该标签不可缺省。 | -| description | 该标签标识App的描述信息,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| vendor | 该标签是对应用开发厂商的描述。该标签的值是字符串类型(最大255个字节)。 | 字符串 | 该标签可以缺省,缺省为空。 | -| versionCode | 该标签标识应用的版本号,该标签值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。开发者可以将该值设置为任何正整数,但是必须确保应用的新版本都使用比旧版本更大的值。该标签不可缺省,versionCode 值应小于2的31方。 | 数值 | 该标签不可缺省 | -| versionName | 该标签标识版本号的文字描述,用于向用户展示。
该标签仅由数字和点构成,推荐采用“A.B.C.D”四段式的形式。四段式推荐的含义如下所示。
第一段 :主版本号/Major,范围0-99,重大修改的版本,如实现新的大功能或重大变化。
第二段 :次版本号/Minor,范围0-99,表示实现较突出的特点,如新功能添加和大问题修复。
第三段 :特性版本号/Feature,范围0-99,标识规划的新版本特性。
第四段 :修订版本号/Patch,范围0-999,表示维护版本,修复bug。 | 字符串 | 该标签不可缺省 | -| minCompatibleVersionCode | 该标签标识该app能够兼容的最低历史版本号,用于跨设备兼容性判断。 | 数值 | 该标签可缺省。缺省值等于versionCode标签值。| -| minAPIVersion | 该标签标识应用运行需要的API最小版本。 | 整形 | 该标签可缺省,缺省值为bundle-profile.json5中的compatibleSdkVersion。| -| targetAPIVersion | 该标签标识应用运行需要的API目标版本。 | 整形 | 该标签可缺省,缺省值为bundle-profile.json5中的compileSdkVersion。| -| apiReleaseType | 该标签标识应用运行需要的API目标版本的类型,采用字符串类型表示。取值为“CanaryN”、“BetaN”或者“Release”,其中,N代表大于零的整数。
Canary :受限发布的版本。
Beta :公开发布的Beta版本。
Release :公开发布的正式版本。 | 字符串 | 该标签可缺省,缺省为“Release”。 | -| distributedNotificationEnabled | 该标签标记该应用是否开启分布式通知。 | 布尔值 | 该标签可缺省,缺省值为true。 | -| entityType | 该标签标记该应用的类别,具体有 :游戏类(game),影音类(media)、社交通信类(communication)、新闻类(news)、出行类(travel)、工具类(utility)、购物类(shopping)、教育类(education)、少儿类(kids)、商务类(business)、拍摄类(photography)。 | 字符串 | 该标签可以缺省,缺省为unspecified。 | -| singleton | 标识该应用开启单例模式,仅支持系统应用配置,三方应用配置不生效。配置为true时,在多用户场景下,该应用仍然单实例运行,不会随用户切换而变动。采用布尔类型,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为false。 | -| removable | 标识应用是否可卸载,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 | -| keepAlive | 标识应用是否始终保持运行状态,仅支持系统应用配置,三方应用配置不生效。标签值为布尔类型,如果为true,应用将始终保持为运行状态,并且在系统启动的时候会被系统启动起来,应用进程退出后,系统也会重新启动该应用进程。 | 布尔值 | 可缺省,缺省值为false。 | -| userDataClearable | 标识是否允许应用清除用户数据,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 | -| accessible | 标识应用的安装目录是否是可访问的,仅支持系统应用配置,三方应用配置不生效。配置为true表示安装目录可以被三方应用访问,false表示不能被三方应用访问。 | 布尔值 | 可缺省,缺省值为false。 | -| multiProjects | 标识当前工程是否支持多工程。 | 布尔值 | 可缺省,缺省值为false。 | -| 设备类型 | 该标签可以配置多个,表示具体设备上的特殊配置信息,具体的设备类型有:"tablet"、"tv"、"wearable"、"car",可能包含的字段有:minAPIVersion、distributedNotificationEnabled、keepAlive、removable。 | 对象 | 该标签可缺省,缺省值使用app下面相关的字段。 | +表3 module对象内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| name | 该标签标识当前module的名字。module打包成HAP后,表示HAP的名称,标签值采用字符串表示(最大长度31字节),该名称在整个应用要唯一。 | 字符串 | 不可缺省。 | +| type | 该标签标识当前module的类型。类型有两种,分别是entry、feature。 | 字符串 | 不可缺省。 | +| srcEntrance | 该标签标识HAP所对应的入口js代码路径,标签值为字符串(最大长度127字节)。 | 字符串 | 可缺省,缺省值为空。 | +| description | 该标签标识HAP包的描述信息,标签值是是字符串类型或对描述内容的字符串资源索引。 | 字符串 | 可缺省,缺省值为空。 | +| process | 该标签标识HAP的进程名,标签值为字符串类型(最大长度31字节)。如果在HAP标签下配置了process,该应用的所有ability都运行在该进程中。该标签只支持系统应用配置。 | 字符串 | 可缺省,缺省值为app标签下的bundleName。 | +| mainElement | 该标签标识HAP的入口Ability名称或者Extension名称。只有配置为mainElement的Ability或者Extension才允许在服务中心露出。 | 字符串 | 创建OpenHarmony原子化服务时,不可缺省。OpenHarmony应用下,可缺省,缺省值为空。 | +| deviceTypes | 该标签标识HAP可以运行在哪类设备上,标签值采用字符串数组的表示,系统预定义的设备类型见表4。 | 字符串数组 | 不可缺省。 | +| deliveryWithInstall | 该标签标识当前HAP是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | 布尔值 | 不可缺省。 | +| installationFree | 标识当前HAP是否支持免安装特性。所有Hap包都需要配置不可缺省。
true :表示支持免安装特性,且符合免安装约束。
false :表示不支持免安装特性。

当entry.hap该字段配置为true时,与该entry.hap相关的所有feature.hap该字段也需要配置为true。
当entry.hap该字段配置为false时,与该entry.hap相关的各feature.hap该字段可按业务需求配置true或false。 | 布尔值 | 不可缺省。 | +| virtualMachine | 该标签用于标识当前HAP运行的目标虚拟机类型,供云端分发使用,如应用市场和分发中心。
该标签值为字符串。如果目标虚拟机类型为方舟虚拟机,则其值为"ark + 版本号"。 该标签由IDE构建HAP的时候自动插入。 | 字符串 | 该标签由IDE构建HAP的时候自动插入。 | +| uiSyntax(deprecated) | syntax定义该JS Component的语法类型。
hml标识该JS Component使用hml/css/js进行开发;
ets标识该JS Component使用ets声明式语法进行开发。 | 字符串 | 可缺省,缺省值为hml,该字段从API9开始废弃。 | +| pages | 该标签是一个profile资源,用于列举JS Component中每个页面信息。可以配置window标签定义与显示窗口相关的配置。window参考[window对象内部结构](#window对象内部结构)。 | 字符串 | 在有ability的场景下,不可缺省。 | +| metadata | 该标签标识Hap的自定义元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| abilities | 描述元能力的配置信息,该标签下的配置只对当前ability生效。参考[abilities对象内部结构](#abilities对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| extensionAbilities | 描述extensionAbilities的配置信息,该标签下的配置只对当前extensionAbility生效。参考[extensionAbilities对象内部结构](#extensionabilities对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| definePermissions | 标识HAP定义的权限,仅支持系统应用配置,三方应用配置不生效。参考[definePermissions对象内部结构](#definepermissions对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| requestPermissions | 该标签标识应用运行时需向系统申请的权限集合。参考[requestPermissions对象内部结构](#requestpermissions对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| testRunner | 该标签用于支持对测试框架的配置,参考[testRunner对象内部结构说明](#testrunner对象内部结构)。 | 对象 | 可缺省,缺省值为空。 | -### module对象内部结构 module.json5示例: ```json { "module": { - "name": "myHapName", - "type": "entry|feature|har", - "srcEntrance" : "./MyAbilityStage.js", + "name": "moduleName", + "type": "entry", + "srcEntrance" : "./abilityStage.js", "description" : "$string:description_application", "mainElement": "MainAbility", + "pages": "$profile:pages_config", "deviceTypes": [ "tablet", "tv", "wearable", - "car", - "router" + "car" ], "deliveryWithInstall": true, "installationFree": false, - "virtualMachine": "ark | default", "metadata": [ { - "name": "string", - "value": "string", + "name": "name1", + "value": "value1", "resource": "$profile:config_file1" }, { - "name": "string", - "value": "string", + "name": "name2", + "value": "value2", "resource": "$profile:config_file2" } ], @@ -111,7 +131,7 @@ module.json5示例: "srcEntrance" : "./login/MyMainAbility.ts", "description": "$string:description_main_ability", "icon": "$media:icon", - "label": "HiMusic", + "label": "$string:label", "visible": true, "skills": [ { @@ -121,7 +141,7 @@ module.json5示例: "entities": [ "entity.system.home" ], - "uris": [ ] + "uris": [] } ], "backgroundModes": [ @@ -143,7 +163,7 @@ module.json5示例: "srcEntrance" : "./login/sampleAbility.ts", "description": "$string:description_sample_ability", "icon": "$media:icon", - "label": "HiMusic", + "label": "$string:label", "visible": true, "startWindowIcon": "$media:icon", "startWindowBackground": "$color:red" @@ -151,7 +171,7 @@ module.json5示例: ], "requestPermissions": [ { - "name": "ohos.abilitydemo.permission.PROVIDER", + "name": "permissionName", "reason": "$string:reason", "usedScene": { "abilities": [ @@ -165,80 +185,76 @@ module.json5示例: } ``` -hap包的配置信息,该标签下的配置只对当前hap包生效。 +pages示例 : -表3 module对象内部结构 +1.在开发视图的resources/base/profile下面定义配置文件pages_config.json(文件名称可由开发者定义): -| 属性名称 | 含义 | 数据类型 | 是否可缺省 | -| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | 该标签标识当前module的名字,module打包成hap后,表示hap的名称,标签值采用字符串表示(最大长度31个字节),该名称在整个应用要唯一。 | 字符串 | 该标签不可缺省。 | -| type | 该标签标识当前hap的类型。类型有三种,分别是entry、feature和har。 | 字符串 | 该标签不可缺省。 | -| srcEntrance | 该标签标识hap所对应的入口js代码路径,标签值为字符串(最长为127字节)。 | 字符串 | 该标签可缺省。 | -| description | 该标签标识hap包的描述信息,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| process | 该标签标识hap的进程名,标签值为字符串类型(最长为31个字节)。如果在hap标签下配置了process,该应用的所有ability都运行在该进程中。该标签只支持系统应用配置。 | 字符串 | 可缺省,缺省为app标签下的bundleName。 | -| mainElement | 该标签标识hap的入口ability名称或者extension名称。只有配置为mainElement的ability或者extension才允许在服务中心露出。创建OpenHarmony原子化服务时,该标签不可缺省。 | 字符串 | OpenHarmony应用下,该标签可缺省。 | -| deviceTypes | 该标签标识hap可以运行在哪类设备上,标签值采用字符串数组的表示,系统预定义的设备类型见表4。
与syscap不同的是,deviceTypes是以设备类型为粒度,而syscap是以设备能力(例如蓝牙、wifi)为粒度。 | 字符串数组 | 该标签不可缺省,可以为空值。 | -| deliveryWithInstall | 该标签标识当前hap是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | 布尔值 | 该标签不可缺省。 | -| installationFree | 标识当前HAP是否支持免安装特性。所有Hap包都需要配置不可缺省。
true :表示支持免安装特性,且符合免安装约束。
false :表示不支持免安装特性。

当entry.hap该字段配置为true时,与该entry.hap相关的所有feature.hap该字段也需要配置为true。
当entry.hap该字段配置为false时,与该entry.hap相关的各feature.hap该字段可按业务需求配置true或false。 | 布尔值 | 该标签不可缺省。 | -| virtualMachine | 该标签用于标识当前hap运行的目标虚拟机类型,供云端分发使用,如应用市场和分发中心。
该标签值为字符串。如果目标虚拟机类型为方舟虚拟机,则其值为”ark”; 如果目标虚拟机类型不是方舟虚拟机,则其值为”default”。该标签由IDE构建hap的时候自动插入。解包工具解析时,如果hap包没有该标签,设置该标签值为”default”。 | 字符串 | 该标签可缺省,缺省值为“default”。 | -| uiSyntax(deprecated) | syntax定义该JS Component的语法类型。
hml标识该JS Component使用hml/css/js进行开发;
ets标识该JS Component使用ets声明式语法进行开发。 | 字符串 | 该标签可缺省,默认值为hml,该字段从API9开始废弃。 | -| pages | 该标签是一个profile资源,用于列举JS Component中每个页面信息。pages使用参考pages示例。 | 对象 | 在有ability的场景下,该标签不可缺省。 | -| metadata | 该标签标识Hap的自定义元信息,标签值为数组类型,该标签下的配置只对当前module、或者ability、或者extensionAbility生效。metadata参考[metadata对象内部结构](#metadata对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| abilities | 描述元能力的配置信息,标签值为数组类型,该标签下的配置只对当前ability生效。abilities参考[abilities对象内部结构](#abilities对象内部结构)。 | 对象 | 该标签可缺省,缺省值为空。 | -| extensionAbilities | 描述extensionAbilities的配置信息,标签值为数组类型,该标签下的配置只对当前extensionAbility生效。extensionAbilities参考[extensionAbility对象的内部结构说明](#extensionability对象的内部结构说明)。 | 对象 | 该标签可缺省,缺省值为空。 | -| definePermissions | 标识hap定义的权限,仅支持系统应用配置,三方应用配置不生效。该应用的调用者必须申请这些权限才能正常调用该应用。definePermissions参考[definePermissions对象内部结构](#definepermissions对象内部结构) | 对象 | 该标签可缺省,缺省值为空,表示调用者无需任何权限即可调用该应用。 | -| requestPermissions | 该标签标识应用运行时需向系统申请的权限集合,标签值为数组类型。requestPermissions参考[requestPermissions对象内部结构](#requestpermissions对象内部结构)。 | 对象 | 该标签可缺省,缺省值为空。 | -| testRunner | 此标签用于支持对测试框架的配置,参考[testRunner对象内部结构说明](#testrunner对象内部结构)说明。 | 对象 | 可缺省,缺省值为空 | - -表4 deviceTypes对象的系统预定义设备 - -| 中文 | 英文 | 枚举值 | 设备类型 | -| -------- | ----------- | -------- | -------------------------------------------------------- | -| 平板 | tablet | tablet | 平板,带屏音箱 | -| 智慧屏 | smart TV | tv | 智慧屏 | -| 智能手表 | smart watch | wearable | 智能手表,儿童手表,特指资源较丰富的的手表,具备电话功能 | -| 车机 | head unit | car | 车机 | -| 路由器 | router | router | 路由器 | +```json +{ + "src": [ + "pages/index/index", + "pages/second/second", + "pages/third/third", + "pages/four/four" + ], + "window": { + "designWidth": 720, + "autoDesignWidth": false + } +} +``` -deviceTypes示例 : +2.在module.json5的module标签下定义pages信息 : ```json { "module": { - "name": "myHapName", - "type": "har", - "deviceTypes" : [ - "wearable" - ] + "pages": "$profile:pages_config" } } ``` -pages示例 : +表4 deviceTypes对象的系统预定义设备 + +| 设备类型 | 枚举值 | 说明 | +| -------- | ----------- | -------- | +| 平板 | tablet | - | +| 智慧屏 | tv | - | +| 智能手表 | wearable | 系统能力较丰富的手表,具备电话功能。 | +| 车机 | car | - | +| 默认设备 | default | 能够使用全部系统能力的OpenHarmony设备。 | + +deviceTypes示例 : ```json { "module": { - "name": "myHapName", - "type": "har", "deviceTypes" : [ "wearable" - ], - "pages": "$profile:pages_config" + ] } } ``` -pages_config配置文件 +#### window对象内部结构 + +定义与显示窗口相关的配置。 + +表5 window对象内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| -------- | ------------------------------------------------------------ | -------- | -------------------------- | +| designWidth | 定义页面设计基准宽度,根据实际设备宽度来缩放元素大小。 | 数值 | 可缺省,缺省值为750。 | +| autoDesignWidth | 定义页面设计基准宽度是否自动计算,当设置为true时,designWidth将被忽略,设计基准宽度由设备宽度与屏幕密度计算得出。 | 布尔值 | 可缺省,缺省值为false。 | + +window示例 : ```json { - "src": [ - "pages/index/index", - "pages/second/second", - "pages/third/third", - "pages/four/four" - ] + "window": { + "designWidth": 720, + "autoDesignWidth": false + } } ``` @@ -248,112 +264,32 @@ pages_config配置文件 描述的module、ability、extensionAbility配置信息,标签值为数组类型,该标签下的配置只对当前module、或者ability、或者extensionAbility生效。 -表5 metadata对象内部结构说明 +表6 metadata对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------------- | -| name | 该标签标识数据项的键名称,字符串类型(最大长度255字节)。 | 字符串 | 该标签可缺省,缺省值为空。 | -| value | 该标签标识数据项的值,标签值为字符串(最大长度255字节)。 | 字符串 | 可缺省,缺省为空。 | -| resource | 该标签标识定义用户自定义数据格式,标签值为标识该数据的资源的索引值。 | 字符串 | 可缺省,缺省为空。 | +| name | 该标签标识数据项的键名称,最大长度255字节。 | 字符串 | 可缺省,缺省值为空。 | +| value | 该标签标识数据项的值,最大长度255字节。 | 字符串 | 可缺省,缺省值为空。 | +| resource | 该标签标识定义用户自定义数据格式,标签值为标识该数据的资源的索引值。 | 字符串 | 可缺省,缺省值为空。 | -metadata示例 : +metadata示例 : ```json -{ +{ "module": { "metadata": [ { - "name": "string", - "value": "string", - "resource": "$profile:config_file" + "name": "name1", + "value": "value1", + "resource": "$profile:config_file1" }, { - "name": "string", - "value": "string", - "resource": "$profile:config_file" + "name": "name2", + "value": "value2", + "resource": "$profile:config_file2" } - ] - } -} -``` - -#### abilities对象内部结构 - -abilities描述ability的配置信息,标签值为数组类型。 - -表6 abilities对象内部结构说明 - -| 属性 | 含义 | 数据类型 | 是否可缺省 | -| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | 该标签标识当前ability的逻辑名,该名称在整个应用要唯一,标签值采用字符串表示(最大长度127个字节)。 | 字符串 | 该标签不可缺省。 | -| srcEntrance | 该标签标识ability所对应的js代码路径,标签值为字符串(最长为127字节)。。 | 字符串 | 该标签不可缺省。 | -| launchType | 该标签标示ability的启动模式,标签值可选“standard”、“singleton”、“specified”。该标签缺省为"singleton"。standard表示普通多实例,specified表示指定实例,运行时由ability内部业务决定是否创建多实例,singleton表示单实例。 | 字符串 | 可缺省,该标签缺省为"singleton" | -| description | 该标签标识ability的描述,标签值是是字符串类型或对描述内容的资源索引,要求采用用资源索引方式,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| icon | 该标签标识ability图标,标签值为资源文件的索引。该标签可缺省,缺省值为空。
如果ability被配置为MainElement,该标签必须配置。 | 字符串 | 该标签可缺省,缺省值为空。
如果ability被配置为MainElement,该标签必须配置。 | -| permissions | 该标签标识被其它应用的ability调用时需要申请的权限的集合,一个数组元素为一个权限名称。通常采用反向域名格式(最大255字节),取值为系统预定义的权限。 | 字符串数组 | 该标签可缺省,缺省值为空。 | -| metadata | 该标签标识ability的元信息。metadata参考[metadata对象内部结构](#metadata对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| visible | 该标签标识ability是否可以被其它应用调用,为布尔类型,true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 | -| continuable | 该标签标识ability是否可以迁移,为布尔类型,true表示可以被迁移, false表示不可以被迁移。 | 布尔值 | 该标签可缺省,缺省值为false。 | -| skills | 该标签标识ability能够接收的意图的特征集,为数组格式。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的ability,其中第一个配置了skills标签的ability中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
skills内部结构参考[skills对象内部结构](#skills对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| backgroundModes | 该标签标识ability长时任务集合。指定用于满足特定类型的长时任务。
长时任务类型有如下 :
dataTransfer :通过网络/对端设备进行数据下载、备份、分享、传输等业务。
audioPlayback :音频输出业务。
audioRecording :音频输入业务。
location :定位、导航业务。
bluetoothInteraction :蓝牙扫描、连接、传输业务(穿戴)。
multiDeviceConnection :多设备互联业务。
wifiInteraction :Wifi扫描、连接、传输业务(克隆 多屏)。
voip :音视频电话,VOIP业务。
taskKeeping :计算业务。
| 字符串 | 可缺省,缺省为空。 | -| startWindowIcon | 标识该Ability启动页面图标资源文件的索引。取值示例:$media:icon。 | 字符串 | 不可缺省。| -| startWindowBackground | 标识该Ability启动页面背景颜色资源文件的索引。取值示例:$color:red。 | 字符串 | 不可缺省。| -| removeMissionAfterTerminate | 该标签标识ability销毁后是否从任务列表中移除任务。为布尔类型,true表示销毁后移除任务, false表示销毁后不移除任务。 | 布尔值 | 该标签可缺省,缺省值为false。| -| orientation | 标识该ability启动时的方向。该方向的取值范围包括:
unspecified: 未指定方向,由系统自动判断显示方向,
landscape:横屏,
portrait:竖屏,
landscape_inverted: 反向横屏,
portrait_inverted: 反向竖屏,
auto_rotation: 随传感器旋转,
auto_rotation_landscape: 传感器横屏旋转,包括了横屏和反向横屏,
auto_rotation_portrait: 传感器竖屏旋转,包括了竖屏和反向竖屏,
auto_rotation_restricted: 传感器开关打开,方向可随传感器旋转,
auto_rotation_landscape_restricted: 传感器开关打开,方向可随传感器旋转为横屏, 包括了横屏和反向横屏,
auto_rotation_portrait_restricted: 传感器开关打开,方向随可传感器旋转为竖屏, 包括了横屏和反向横屏,
locked: 传感器开关关闭,方向锁定。 | 字符串 | 该标签可缺省,缺省值为unspecified。| -|supportWindowMode|标识该ability所支持的窗口模式,包含:
fullscreen: 全屏模式,
split: 分屏模式,
floating: 悬浮窗模式。 |数组 | 该标签可缺省,缺省值为
["fullscreen", "split", "floating"]。| -|priority|标识ability的优先级,仅支持系统应用配置,三方应用配置不生效。隐式查询时,优先级越高,ability在返回列表越靠前。该标签取值为integer类型,取值范围0-10。数值越大,优先级越高。 |数值 | 该标签可缺省,缺省值为0。 | -|maxWindowRatio|标识该ability支持的最大的宽高比。| 数值 |该标签可缺省,缺省值为平台支持的最大的宽高比。| -|minWindowRatio|标识该ability支持的最小的宽高比。| 数值 |该标签可缺省,缺省值为平台支持的最小的宽高比。| -|maxWindowWidth|标识该ability支持的最大的窗口宽度,宽度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最大的窗口宽度。| -|minWindowWidth|标识该ability支持的最小的窗口宽度, 宽度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口宽度。| -|maxWindowHeight|标识该ability支持的最大的窗口高度, 高度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最大的窗口高度。| -|minWindowHeight|标识该ability支持的最小的窗口高度, 高度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口高度。| -| excludeFromMissions | 该标签标识ability是否在最近任务列表中显示,仅支持系统应用配置,三方应用配置不生效。为布尔类型,true表示不在任务列表中显示,false表示在任务列表中显示。 | 布尔值 | 该标签可缺省,缺省值为false。| - -abilities示例 - -```json -{ - "abilities": [{ - "name": "MainAbility", - "srcEntrance": "./ets/login/MyLoginAbility.ts", - "launchType":"standard", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "Login", - "permissions": [], - "metadata": [], - "visible": true, - "continuable": true, - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" ], - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red", - "removeMissionAfterTerminate": true, - "orientation": " ", - "supportWindowMode": ["fullscreen", "split", "floating"], - "maxWindowRatio": 3.5, - "minWindowRatio": 0.5, - "maxWindowWidth": 2560, - "minWindowWidth": 1400, - "maxWindowHeight": 300, - "minWindowHeight": 200, - "excludeFromMissions": false - }] + } } ``` @@ -361,231 +297,374 @@ abilities示例 该标签标识ability或者extension能够接收的意图的特征。 -表7 skills内部结构示例 +表7 skill对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | 该标签标识能够接收的意图的action值的集合,取值通常为系统预定义的action值,也允许自定义。 | 字符串数组 | 可缺省,缺省值为空。 | | entities | 该标签标识能够接收Want的元能力的类别集合,取值通常为系统预定义的类别,也允许自定义。 | 字符串数组 | 可缺省,缺省值为空。 | -| uris | 该标签标识向 want过滤器添加数据规范集合。该规范可以是只有数据类型(mimeType 属性),可以是只有 URI,也可以是既有数据类型又有 URI。uris内部结构参考表8。 | 对象数组 | 可缺省,缺省值为空。 | +| uris | 该标签标识与意图中URI(Uniform Resource Identifier)相匹配的集合。uris内部结构参考表8。 | 对象数组 | 可缺省,缺省值为空。 | -表8 uris对象的内部结构说明 +表8 uris对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------- | -------- | -------------------- | -| scheme | 标识uri的scheme值。 | 字符串 | 不可缺省。 | -| host | 标识uri的host值。 | 字符串 | 可缺省,缺省值为空。 | -| port | 标识uri的port值。 | 字符串 | 可缺省,缺省值为空。 | -| path | 标识uri的path值。 | 字符串 | 可缺省,缺省值为空。 | -| type | 标识uri的type值。 | 字符串 | 可缺省,缺省值为空。 | +| scheme | 标识URI的协议名部分,常见的有http、https、file、ftp等。 | 字符串 | 当配置type时可缺省,缺省值为空。没有配置type时不可缺省。 | +| host | 标识URI的主机地址部分,常见的有域名的方式,如example.com,ip地址的方式,如192.0.0.1。该字段要在scheme存在时才有意义。 | 字符串 | 可缺省,缺省值为空。 | +| port | 标识URI的端口部分。如http默认端口为80,https默认端口是443,ftp默认端口是21。该字段要在scheme和host都存在时才有意义。| 字符串 | 可缺省,缺省值为空。 | +| path \| pathStartWith \| pathRegex | 标识URI的路径部分,path、pathStartWith和pathRegex配置时三选一。path标识URI与want中的路径部分全匹配,pathStartWith标识URI与want中的路径部分允许前缀匹配,pathRegex标识URI与want中的路径部分允许正则匹配。该字段要在scheme和host都存在时才有意义。| 字符串 | 可缺省,缺省值为空。 | +| type | 标识数据类型,使用MIME(Multipurpose Internet Mail Extensions)类型规范。可与scheme同时配置,也可以单独配置。| 字符串 | 可缺省,缺省值为空。 | -skills示例 +skills示例 : ```json { - "abilities": [ - { - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ], - "extensionAbilities": [ - { - "skills": [ - { - "actions": [ - ], - "entities": [ - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ] + "module": { + "abilities": [ + { + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme":"https", + "host":"www.example.com", + "port":"8080", + "path":"query/student/name", + "pathStartWith":"query/student", + "pathRegex":"query/.*/name", + "type": "text/*" + } + ] + } + ] + } + ], + "extensionAbilities": [ + { + "skills": [ + { + "actions": [ + "actionName" + ], + "entities": [ + "entityName" + ], + "uris": [ + { + "scheme":"https", + "host":"www.example.com", + "port":"8080", + "path":"query/student/name", + "pathStartWith":"query/student", + "pathRegex":"query/.*/name", + "type": "text/*" + } + ] + } + ] + } + ] + } +} +``` + +#### abilities对象内部结构 + +abilities描述Ability组件的配置信息,标签值为数组类型。 + +表9 ability对象内部结构说明 + +| 属性 | 含义 | 数据类型 | 是否可缺省 | +| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| name | 该标签标识当前Ability组件的逻辑名,该名称在整个应用要唯一,标签值采用字符串表示(最大长度127字节)。 | 字符串 | 不可缺省。 | +| srcEntrance | 该标签标识Ability组件所对应的js代码路径,标签值为字符串(最大长度127字节)。 | 字符串 | 不可缺省。 | +| launchType | 该标签标识Ability组件的启动模式,可选标签值:
"standard":多实例,每次启动创建一个新的实例。
"singleton":单实例,仅第一次启动创建新实例。
"specified":运行时由开发者决定是否创建新实例。 | 字符串 | 可缺省,缺省值为"singleton" | +| description | 该标签标识Ability组件的描述信息,标签值是是字符串类型或对描述内容的资源索引,要求采用资源索引方式,以支持多语言。 | 字符串 | 可缺省,缺省值为空。 | +| icon | 该标签标识Ability组件的图标,标签值为图标资源文件的索引。 | 字符串 | 可缺省,缺省值为空。
如果Ability组件被配置为MainElement,该标签必须配置。 | +| permissions | 该标签标识被其它应用的Ability组件调用时需要申请的权限的集合,一个数组元素为一个权限名称。通常采用反向域名格式(最大长度255字节),取值为系统预定义的权限。 | 字符串数组 | 可缺省,缺省值为空。 | +| metadata | 该标签标识Ability组件的元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| visible | 该标签标识Ability组件是否可以被其它应用调用,true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 可缺省,缺省值为false。 | +| continuable | 该标签标识Ability组件是否可以迁移,true表示可以被迁移, false表示不可以被迁移。 | 布尔值 | 可缺省,缺省值为false。 | +| skills | 该标签标识Ability组件能够接收的意图的特征集。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的Ability组件,其中第一个配置了skills标签的Ability组件中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
参考[skills对象内部结构](#skills对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| backgroundModes | 该标签标识Ability组件的长时任务集合。指定用于满足特定类型的长时任务。
长时任务类型有如下 :
dataTransfer :通过网络/对端设备进行数据下载、备份、分享、传输等业务。
audioPlayback :音频输出业务。
audioRecording :音频输入业务。
location :定位、导航业务。
bluetoothInteraction :蓝牙扫描、连接、传输业务(穿戴)。
multiDeviceConnection :多设备互联业务。
wifiInteraction :Wifi扫描、连接、传输业务(克隆 多屏)。
voip :音视频电话,VOIP业务。
taskKeeping :计算业务。
| 字符串 | 可缺省,缺省值为空。 | +| startWindowIcon | 标识该Ability组件启动页面图标资源文件的索引。取值示例:$media:icon。 | 字符串 | 不可缺省。| +| startWindowBackground | 标识该Ability组件启动页面背景颜色资源文件的索引。取值示例:$color:red。 | 字符串 | 不可缺省。| +| removeMissionAfterTerminate | 该标签标识Ability组件销毁后是否从任务列表中移除任务。true表示销毁后移除任务, false表示销毁后不移除任务。 | 布尔值 | 可缺省,缺省值为false。| +| orientation | 标识该Ability组件启动时的方向。取值范围包括:
unspecified: 未指定方向,由系统自动判断显示方向,
landscape:横屏,
portrait:竖屏,
landscape_inverted: 反向横屏,
portrait_inverted: 反向竖屏,
auto_rotation: 随传感器旋转,
auto_rotation_landscape: 传感器横屏旋转,包括了横屏和反向横屏,
auto_rotation_portrait: 传感器竖屏旋转,包括了竖屏和反向竖屏,
auto_rotation_restricted: 传感器开关打开,方向可随传感器旋转,
auto_rotation_landscape_restricted: 传感器开关打开,方向可随传感器旋转为横屏, 包括了横屏和反向横屏,
auto_rotation_portrait_restricted: 传感器开关打开,方向随可传感器旋转为竖屏, 包括了横屏和反向横屏,
locked: 传感器开关关闭,方向锁定。 | 字符串 | 可缺省,缺省值为"unspecified"。| +|supportWindowMode|标识该Ability组件所支持的窗口模式,取值范围包括:
fullscreen: 全屏模式,
split: 分屏模式,
floating: 悬浮窗模式。 |字符串数组 | 可缺省,缺省值为
["fullscreen", "split", "floating"]。| +|maxWindowRatio|标识该Ability组件支持的最大的宽高比。| 数值 |可缺省,缺省值为平台支持的最大的宽高比。| +|minWindowRatio|标识该Ability组件支持的最小的宽高比。| 数值 |可缺省,缺省值为平台支持的最小的宽高比。| +|maxWindowWidth|标识该Ability组件支持的最大的窗口宽度,宽度单位为vp。| 数值 |可缺省,缺省值为平台支持的最大的窗口宽度。| +|minWindowWidth|标识该Ability组件支持的最小的窗口宽度, 宽度单位为vp。| 数值 |可缺省,缺省值为平台支持的最小的窗口宽度。| +|maxWindowHeight|标识该Ability组件支持的最大的窗口高度, 高度单位为vp。| 数值 |可缺省,缺省值为平台支持的最大的窗口高度。| +|minWindowHeight|标识该Ability组件支持的最小的窗口高度, 高度单位为vp。| 数值 |可缺省,缺省值为平台支持的最小的窗口高度。| + +abilities示例 : + +```json +{ + "module": { + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/login/LoginAbility.ts", + "launchType":"standard", + "description": "$string:description", + "icon": "$media:icon", + "label": "$string:label", + "permissions": [], + "metadata": [], + "visible": true, + "continuable": true, + "skills": [ + { + "actions": ["action.system.home"], + "entities": ["entity.system.home"], + "uris": [] + } + ], + "backgroundModes": [ + "dataTransfer", + "audioPlayback", + "audioRecording", + "location", + "bluetoothInteraction", + "multiDeviceConnection", + "wifiInteraction", + "voip", + "taskKeeping" + ], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true, + "orientation": "landscape", + "supportWindowMode": ["fullscreen", "split", "floating"], + "maxWindowRatio": 3.5, + "minWindowRatio": 0.5, + "maxWindowWidth": 2560, + "minWindowWidth": 1400, + "maxWindowHeight": 300, + "minWindowHeight": 200 + } + ] + } } ``` -#### extensionAbility对象的内部结构说明 -描述extensionAbility的配置信息,标签值为数组类型,该标签下的配置只对当前extensionAbility生效。 +#### extensionAbilities对象内部结构 + +extensionAbilities描述extensionAbility的配置信息,标签值为数组类型。 -表9 extensionAbility对象内部结构说明 +表10 extensionAbility对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ----------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | 该标签标识当前extensionAbility的逻辑名,标签值采用字符串表示(最大长度127个字节),该名称在整个应用要唯一。 | 字符串 | 该标签不可缺省。 | -| srcEntrance | 该标签标识extensionAbility所对应的js代码路径,标签值为字符串(最长为127字节)。 | 字符串 | 该标签不可缺省。 | -| description | 该标签标识extensionAbility的描述,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| icon | 该标签标识extensionAbility图标,标签值为资源文件的索引。如果extensionAbility被配置为MainElement,该标签必须配置。 | 字符串 | 该标签可缺省,缺省值为空。 | -| label | 该标签标识extensionAbility对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。
如果extensionAbility被配置为MainElement,该标签必须配置,且应用内唯一。 | 字符串 | 该标签不可缺省。 | -| type | 该标签标识extensionAbility的类型,取值为form、workScheduler、inputMethod、service、accessibility、dataShare、fileShare、staticSubscriber、wallpaper、backup、window、enterpriseAdmin、thumbnail、preview其中之一。 | 字符串 | 该标签不可缺省。 | -| permissions | 该标签标识被其它应用的ability调用时需要申请的权限的集合,字符串数组类型,每个数组元素为一个权限名称,通常采用反向域名方式表示(最大255字节),可以是系统预定义的权限,也可以是该应用自定义的权限。如果是后者,需与defPermissions标签中定义的某个权限的name标签值一致。 | 字符串数组 | 该标签可缺省,缺省值为空。 | -| uri | 该标签标识ability提供的数据uri,为字符数组类型(最大长度255),用反向域名的格式表示。该标签在type为dataShare类型的extensionAbility时,不可缺省。 | 字符串 | 该标签可缺省,缺省值为空。 | -| skills | 该标签标识ability能够接收的意图的特征集,为数组格式。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的ability,其中第一个配置了skills标签的ability中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
skills内部结构参考[skills对象内部结构](#skills对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| metadata | 该标签标识extensionAbility的元信息。metadata内部结构参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象 | 该标签可缺省,缺省值为空。 | -| visible | 该标签标识extensionAbility是否可以被其它应用调用,为布尔类型。true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 | - -extensionAbility示例 : +| name | 该标签标识当前ExtensionAbility组件的逻辑名,标签值采用字符串表示(最大长度127字节),该名称在整个应用要唯一。 | 字符串 | 不可缺省。 | +| srcEntrance | 该标签标识ExtensionAbility组件所对应的js代码路径,标签值为字符串(最大长度127字节)。 | 字符串 | 不可缺省。 | +| description | 该标签标识ExtensionAbility组件的描述,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 可缺省,缺省值为空。 | +| icon | 该标签标识ExtensionAbility组件图标,标签值为资源文件的索引。 | 字符串 | 可缺省,缺省值为空。如果ExtensionAbility组件被配置为MainElement,不可缺省。 | +| label | 该标签标识ExtensionAbility组件对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。 | 字符串 | 可缺省,缺省值为空。如果ExtensionAbility组件被配置为MainElement,该标签必须配置,且应用内唯一。 | +| type | 该标签标识ExtensionAbility组件的类型,取值为form、workScheduler、inputMethod、service、accessibility、dataShare、fileShare、staticSubscriber、wallpaper、backup、window、enterpriseAdmin、thumbnail、preview其中之一。 | 字符串 | 不可缺省。 | +| permissions | 该标签标识被其它应用的ability调用时需要申请的权限的集合,字符串数组类型,每个数组元素为一个权限名称,通常采用反向域名方式表示(最大长度255字节),取值为系统预定义权限或者应用自定义权限,如果是后者,需与defPermissions标签中定义的某个权限的name标签值一致。 | 字符串数组 | 可缺省,缺省值为空。 | +| uri | 该标签标识ability提供的数据URI,为字符数组类型(最大长度255字节),用反向域名的格式表示。 | 字符串 | 可缺省,缺省值为空。该标签在type为dataShare类型的ExtensionAbility组件时,不可缺省。 | +| skills | 该标签标识ability能够接收的意图的特征集,为数组格式。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的ability,其中第一个配置了skills标签的ability中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
参考[skills对象内部结构](#skills对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| metadata | 该标签标识ExtensionAbility组件的元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| visible | 该标签标识ExtensionAbility组件是否可以被其它应用调用。true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 可缺省,缺省值为false。 | +| readPermission | 该标签标识读取ExtensionAbility组件的数据所需的权限。最大长度255字节。type为dataShare类型的ExtensionAbility组件支持该配置。该标签只对系统应用生效。 | 字符串 | 可缺省,缺省值为空。 | +| writePermission | 该标签标识向ExtensionAbility组件写数据所需的权限。最大长度255字节。type为dataShare类型的ExtensionAbility组件支持该配置。该标签只对系统应用生效。 | 字符串 | 可缺省,缺省值为空。 | + +extensionAbilities示例 : ```json { - "extensionAbilities": [ - { - "name": "FormName", - "srcEntrance": "./form/MyForm.ts", - "icon": "$media:icon", - "label" : "$string:extension_name", - "description": "$string:form_description", - "type": "form", - "permissions": ["ohos.abilitydemo.permission.PROVIDER"], - "readPermission": "", - "writePermission": "", - "visible": true, - "uri":"scheme://authority/path/query" - "skills": [{ - "actions": [], - "entities": [], - "uris": [] - }], - "metadata": [ - { - "name": "ohos.extability.form", - "resource": "$profile:form_config", - } - ] - } - ] + "module": { + "extensionAbilities": [ + { + "name": "extensionName", + "srcEntrance": "./extension/FormExtension.ts", + "icon": "$media:icon", + "label" : "$string:label", + "description": "$string:description", + "type": "form", + "permissions": ["permissionName"], + "readPermission": "", + "writePermission": "", + "visible": true, + "uri":"scheme://authority/path/query" + "skills": [ + { + "actions": [], + "entities": [], + "uris": [] + } + ], + "metadata": [ + { + "name": "ohos.extability.form", + "resource": "$profile:form_config", + } + ] + } + ] + } } ``` #### definePermissions对象内部结构 -该标签标识hap定义的权限。 +该标签标识HAP定义的权限。该标签只支持系统应用配置。 -表10 definePermissions定义权限字段说明 +表11 definePermission对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------ | -| name | 标识权限的名称。 | 字符串 | 不可缺省 | -| grantMode | 标识权限的授予方式,授予模式如下:
system_grant:安装后系统自动授予该权限。
user_grant:使用动态申请,用户授权后才可使用 | 字符串 | 可缺省,缺省值为system_grant。 | -| availableLevel | 标识权限限制门限,可选值为"system_core"、"system_basic"、"normal"。该标签有缺省值,缺省值为normal。权限范围如下:
system_core:系统核心权限。
system_basic:系统基础权限。
normal:普通权限。所有应用允许申请的权限。 | 字符串 | 可缺省,缺省值为"normal" | -| provisionEnable | 标识权限是否支持证书方式申请权限,包括高级别的权限,true标识需要开发者可以通过provision证书acls方式申请权限。 | 布尔值 | 可缺省,缺省值为true | -| distributedSceneEnable | 标识权限是否支持分布式场景下使用该权限。 | 布尔值 | 可缺省,缺省值为false | -| label | 标识权限的简短描述,配置为对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空 | -| description | 标识权限的详细描述,可以是表示描述内容的字符串,也可以是对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空 | +| name | 标识权限的名称。 | 字符串 | 不可缺省。 | +| grantMode | 标识权限的授予方式,授予模式如下:
system_grant:安装后系统自动授予该权限。
user_grant:应用动态申请,用户授权后才可使用 | 字符串 | 可缺省,缺省值为"system_grant"。 | +| availableLevel | 标识权限限制门限,可选值为system_core、system_basic、normal。
system_core:系统核心权限。
system_basic:系统基础权限。
normal:普通权限。所有应用允许申请的权限。 | 字符串 | 可缺省,缺省值为"normal"。 | +| provisionEnable | 标识权限是否支持证书方式申请权限,包括高级别的权限,true标识需要开发者可以通过provision证书acls方式申请权限。 | 布尔值 | 可缺省,缺省值为true。 | +| distributedSceneEnable | 标识权限是否支持分布式场景下使用该权限。 | 布尔值 | 可缺省,缺省值为false。 | +| label | 标识权限的简短描述,配置为对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空。 | +| description | 标识权限的详细描述,可以是表示描述内容的字符串,也可以是对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空。 | + +definePermissions示例 : + +```json +{ + "module": { + "definePermissions": [ + { + "name": "permissionName", + "grantMode": "user_grant", + "availableLevel": "system_basic", + "provisionEnable": false, + "distributedSceneEnable": true, + "label" : "$string:label", + "description": "$string:description" + } + ] + } +} + +``` #### requestPermissions对象内部结构 该标签标识应用运行时需向系统申请的权限集合。 -表11 requestPermissions权限申请字段说明 +表12 requestPermission对象内部结构说明 -| 属性名称 | 含义 | **类型** | **取值范围** | **默认值** | **规则约束** | -| --------- | ------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ | -| name | 必须,填写需要使用的权限名称。 | 字符串 | 自定义 | 无 | 未填写时,解析失败。 | -| reason | 可选,当申请的权限为user_grant权限时此字段必填。描述申请权限的原因。 | 字符串 | 使用string类资源引用。格式为`$string: ***`。 | 空 | user_grant权限必填,否则不允许在应用市场上架。需做多语种适配。 | -| usedScene | 可选,当申请的权限为user_grant权限时此字段必填。描述权限使用的场景和时机。场景类型有 :ability、when(调用时机)。可配置多个ability。 | abilities:ability字符串数组,when:字符串 | abilities:ability的名称,when:inuse(使用时)、always(始终) | abilities:空 when:空 | user_grant权限必填abilities,可选填when。 | +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| ------| ------| -------- | ------------------------------ | +| name | 需要申请的权限名称。| 字符串 | 不可缺省。 | +| reason | 申请权限的原因。配置为描述内容的资源索引,以支持多语言。 | 字符串 | 可缺省,缺省值为空。当申请权限的grantMode为user_grant时不可缺省。 | +| usedScene | 权限使用的场景和时机。参考[usedScene对象内部结构](#usedscene对象内部结构)。| 对象 | 可缺省,缺省值为空。当申请权限的grantMode为user_grant时不可缺省。 | -requestPermissions示例 : +requestPermissions示例 : ```json { - "name": "ohos.abilitydemo.permission.PROVIDER", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "AudioAbility", - "VideoAbility", - ], - "when": "inuse" - } + "module": { + "requestPermissions": [ + { + "name": "permissionName", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "AudioAbility", + "VideoAbility" + ], + "when": "inuse" + } + } + ] + } } ``` + 权限访问的更多说明,可参考[访问控制开发指导](../security/accesstoken-guidelines.md) -#### form对象内部结构 +#### usedScene对象内部结构 + +该标签标识权限使用的场景和时机。 + +表13 usedScene对象内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| ------- | --------------------| -------- | ------ | +| abilities | 标识需要使用到该权限的ability。| 字符串数组 | 不可缺省。 | +| when | 标识使用该权限的时机,可选值为inuse和always。inuse表示仅前台使用,always表示前后台都可使用 | 字符串 | 可缺省,缺省值为空。 | -forms标签标识卡片的配置,form卡片是可以嵌入桌面上并接收定期更新的应用简要视图。在以下场景中可以包含form标签。 -1. extensions中指定type为form。 +usedScene示例 : + +```json +{ + "module": { + "requestPermissions": [ + { + "usedScene": { + "abilities": [ + "AudioAbility", + "VideoAbility" + ], + "when": "inuse" + } + } + ] + } +} +``` + +#### forms对象内部结构 -2. metadata中指定form信息,其中 : - name :指定form的名称。使用ohos.extability.form作为form信息的标识。 - resource :指定form信息的资源位置。 +forms标签标识卡片的配置,form卡片是可以嵌入桌面上并接收定期更新的应用简要视图。
+配置方式如下:
+extensionAbility标签配置type为form,并配置metadata信息:name :"ohos.extability.form"。resource :指定form信息的资源位置。 -表12 forms对象的内部结构说明 +表14 form对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ------------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | 标识卡片的类名。字符串最大长度为127字节。 | 字符串 | 否 | -| description | 标识卡片的描述。取值可以是描述性内容,也可以是对描述性内容的资源索引,以支持多语言。字符串最大长度为255字节。 | 字符串 | 可缺省,缺省为空。 | -| src | 该标签标识JS卡片对应的UI代码。建议开发者通过自适应布局显示不同规格卡片,如果不同规格卡片布局相差较大,建议通过不同卡片来区分。 | 字符串 | 可缺省,缺省为空。 | -| window | 该标签标识JS卡片的自适应能力。window结构参考表12。 | 对象 | 可缺省,缺省为空。 | -| isDefault | 标识该卡片是否为默认卡片,每个Ability有且只有一个默认卡片。 true :默认卡片。 false :非默认卡片。 | 布尔值 | 否 | -| colorMode | 标识卡片的主题样式,取值范围如下 : auto :自适应。 dark :深色主题。 light :浅色主题。 | 字符串 | 可缺省,缺省值为“auto”。 | -| supportDimensions | 标识卡片支持的外观规格,取值范围 : 1 * 2 :表示1行2列的二宫格。 2 * 1 :表示2行1列的二宫格。 2 * 2 :表示2行2列的四宫格。 2 * 4 :表示2行4列的八宫格。 4 * 4 :表示4行4列的十六宫格。 | 字符串数组 | 否 | -| defaultDimension | 标识卡片的默认外观规格,取值必须在该卡片supportDimensions配置的列表中。 | 字符串 | 否 | -| updateEnabled | 该标签标识该卡片是否支持实时刷新,true标识卡片支持实时刷新,false标识不支持。 | 布尔值 | 否 | -| scheduledUpdateTime | 该标签标识卡片定点刷新的时间,采用24小时计数,精确到分钟。 | 字符串 | 是 | -| updateDuration | 该标签标识卡片定时刷新的更新频率,单位为30分钟,取值为30的倍数值。卡片的最高频率为每30分钟刷新一次,和定点刷新二选一,二者都配置的情况下,定时优先。 | 数值 | 可缺省,缺省为空。 | -| metadata | 该标签标识卡片的自定义信息。metadata内部结构参考表5。 | 对象 | 可缺省,缺省为空。 | -| formConfigAbility | 该标签标识卡片调整的Ability名称。标签值为字符串类型(最长127字符)。该标签值必须满足下面的格式 :
ability://单个ability名字
单个ability名字必须为本应用的ability。 | 字符串 | 可缺省,缺省为空。 | -| formVisibleNotify | 该标签标识卡片是否被允许使用卡片可见性通知。标签值为true或false | 布尔值 | 该标签可缺省,默认值为false。 | - -表13 window内部结构说明 - -| 属性名称 | 含义 | 数据类型 | 是否可缺省 | -| --------------- | ------------------------------------------------------------ | -------- | -------------------- | -| designWidth | 指示页面设计的基线宽度,以像素为单位。 元素的大小由实际设备宽度缩放。 这个标签是一个整数。 | 数值 | 可缺省,缺省值为空。 | -| autoDesignWidth | 指定是否自动计算页面设计的基线宽度。 如果设置为true,则designWidth属性无效。基线宽度根据设备宽度和屏幕密度计算。 | 布尔值 | 可缺省,缺省值为空。 | +| name | 标识卡片的名称。最大长度为127字节。 | 字符串 | 不可缺省。 | +| description | 标识卡片的描述。取值可以是描述性内容,也可以是对描述性内容的资源索引,以支持多语言。最大长度为255字节。 | 字符串 | 可缺省,缺省值为空。 | +| src | 该标签标识JS卡片对应的UI代码。建议开发者通过自适应布局显示不同规格卡片,如果不同规格卡片布局相差较大,建议通过不同卡片来区分。 | 字符串 | 可缺省,缺省值为空。 | +| window | 该标签标识JS卡片的自适应能力。参考[window对象内部结构](#window对象内部结构)。 | 对象 | 可缺省,缺省值为空。 | +| isDefault | 标识该卡片是否为默认卡片,每个Ability有且只有一个默认卡片。 true :默认卡片。 false :非默认卡片。 | 布尔值 | 不可缺省。 | +| colorMode | 标识卡片的主题样式,取值范围如下 :
auto :自适应。
dark :深色主题。
light :浅色主题。
| 字符串 | 可缺省,缺省值为“auto”。 | +| supportDimensions | 标识卡片支持的外观规格,取值范围 :
1 * 2 :表示1行2列的二宫格。
2 * 1 :表示2行1列的二宫格。
2 * 2 :表示2行2列的四宫格。
2 * 4 :表示2行4列的八宫格。
4 * 4 :表示4行4列的十六宫格。 | 字符串数组 | 不可缺省。 | +| defaultDimension | 标识卡片的默认外观规格,取值必须在该卡片supportDimensions配置的列表中。 | 字符串 | 不可缺省。 | +| updateEnabled | 该标签标识该卡片是否支持实时刷新,true标识卡片支持实时刷新,false表示不支持。 | 布尔值 | 不可缺省。 | +| scheduledUpdateTime | 该标签标识卡片定点刷新的时间,采用24小时计数,精确到分钟。 | 字符串 | 可缺省,缺省值为空。 | +| updateDuration | 该标签标识卡片定时刷新的更新频率,单位为30分钟,取值为30的倍数。卡片的最高频率为每30分钟刷新一次,和定点刷新二选一,二者都配置的情况下,定时优先。 | 数值 | 可缺省,缺省值为空。 | +| metadata | 该标签标识卡片的元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| formConfigAbility | 该标签标识卡片调整的Ability名称。最大长度127字节。该标签值必须满足下面的格式 :
ability://单个ability名字
单个ability名字必须为本应用的ability。 | 字符串 | 可缺省,缺省值为空。 | +| formVisibleNotify | 该标签标识卡片是否被允许使用卡片可见性通知。 | 布尔值 | 可缺省,缺省值为false。 | form示例 : -在开发视图的resources/base/profile下面定义配置文件form_config.json(文件名称可由开发者定义) +1.在开发视图的resources/base/profile下面定义配置文件form_config.json(文件名称可由开发者定义): ```json { "forms": [ { "name": "Form_Js", - "description": "$string:form_description", + "description": "$string:description", "src": "./js/pages/card/index", "window": { "designWidth": 720, "autoDesignWidth": true }, "colorMode": "auto", - "formConfigAbility": "ability://xxxxx", + "formConfigAbility": "ability://xxx", "formVisibleNotify": false, "isDefault": true, "updateEnabled": true, @@ -593,200 +672,221 @@ form示例 : "updateDuration": 1, "defaultDimension": "2*2", "updateEnabled": true, - "scheduledUpdateTime": "21:33", "supportDimensions": [ "2*2" ], "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - } + { + "name": "name", + "value": "value", + "resource": "$profile:resource" + } ] } ] } ``` -在module.json5的extension组件下面定义metadata信息 +2.在module.json5的extensionAbilities标签下定义metadata信息 : ```json { - "extensionAbilities": [{ - "name": "MyForm", - "type": "form", - "metadata": [{ - "name": "ohos.extability.form", - "resource": "$profile:form_config" - }] - }] + "module": { + "extensionAbilities": [ + { + "type": "form", + "metadata": [ + { + "name": "ohos.extability.form", + "resource": "$profile:form_config" + } + ] + } + ] + } } ``` #### shortcuts对象内部结构 -标识应用的快捷方式信息。标签值为数组,最多可以配置四个快捷方式。其包含四个子标签shortcutId、label、icon、wants。 - -metadata中指定shortcut信息,其中 : -1)name :指定shortcuts的名称。使用ohos.ability.shortcuts作为shortcuts信息的标识。 -2)resource :指定shortcuts信息的资源位置。 +标识应用的快捷方式信息。最多可以配置四个快捷方式。
+配置方式如下:
+ability标签配置metadata信息。name :"ohos.ability.shortcuts"。resource :指定shortcuts信息的资源位置。 -表14 shortcuts对象的内部结构说明 +表15 shortcut对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ---------- | ------------------------------------------------------------ | -------- | -------------------------- | -| shortcutId | 标识快捷方式的ID。字符串的最大长度为63字节。 | 字符串 | 否 | -| label | 标识快捷方式的标签信息,即快捷方式对外显示的文字描述信息。取值可以是描述性内容,也可以是标识label的资源索引。字符串最大长度为63字节。 | 字符串 | 可缺省,缺省为空。 | -| icon | 该标签标识shortcut的图标,标签值为资源文件的索引。 | 字符串 | 该标签可缺省,缺省值为空。 | -| wants | 该标签标识快捷方式内定义的目标wants信息集合,每个want可配置两个子标签,bundleName,abilityName。
bundleName :快捷方式目标包名,字符串类型。
abilityName :快捷方式的目标组件名,字符串类型。 | 对象 | 该标签可缺省,缺省为空。 | +| shortcutId | 标识快捷方式的ID。最大长度为63字节。 | 字符串 | 不可缺省。 | +| label | 标识快捷方式的标签信息,即快捷方式对外显示的文字描述信息。取值可以是描述性内容,也可以是标识label的资源索引。字符串最大长度为63字节。 | 字符串 | 可缺省,缺省值为空。 | +| icon | 该标签标识shortcut的图标,标签值为资源文件的索引。 | 字符串 | 可缺省,缺省值为空。 | +| wants | 该标签标识快捷方式内定义的目标wants信息集合,每个want可配置两个子标签,bundleName,abilityName。
bundleName :快捷方式目标包名,字符串类型。
abilityName :快捷方式的目标组件名,字符串类型。 | 对象数组 | 可缺省,缺省值为空。 | -在开发视图的resources/base/profile下面定义配置文件shortcut_config.json(文件名称可由开发者定义)。 +shortcuts示例 : + +1.在开发视图的resources/base/profile下面定义配置文件shortcuts_config.json(文件名称可由开发者定义): ```json { - "shortcuts": [{ - "shortcutId": "id_test1", - "label": "$string:shortcut", - "icon": "$media:aa_icon", - "wants": [{ - "bundleName": "com.ohos.hello", - "abilityName": "MainAbility" - }] - }] + "shortcuts": [ + { + "shortcutId": "shortcut_id", + "label": "$string:label", + "icon": "$media:icon", + "wants": [ + { + "bundleName": "bundleName", + "abilityName": "abilityName" + } + ] + } + ] } ``` -在module.json5的module下面定义metadata信息,如下 : +2.在module.json5的abilities标签下定义metadata信息 : ```json { "module": { - "name": "MyAbilityStage", - "abilities": [{ - "name": "MyAbility", - "srcEntrance": "./abilities/MyAbility.ts", - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "metadata": [{ - "name": "ohos.ability.shortcuts", - "resource": "$profile:shortcuts_config" - }] - }] + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./abilities/MainAbility.ts", + "skills": [ + { + "actions": ["action.system.home"], + "entities": ["entity.system.home"] + } + ], + "metadata": [ + { + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + } + ] + } + ] } } ``` #### commonEvents对象内部结构 -commonEvents标签标识注册静态公共事件信息。标签值为数组。 -metadata中指定commonEvent信息,其中 : - -1. name :指定commonEvent的名称。使用ohos.extability.staticSubscriber作为commonEvent信息的标识。 +commonEvents标签标识注册静态公共事件信息。
+配置方式如下:
+extensionAbility标签配置type为staticSubscriber,并配置metadata信息:name :"ohos.extability.staticSubscriber"。resource :指定commonEvents信息的资源位置。 -2. resource :指定commonEvent信息的资源位置。 - -表15 commonEvents对象内部结构 +表16 commonEvent对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ---------- | ------------------------------------------------------------ | ---------- | -------------------------- | -| name | 该标签指明当前静态公共事件对应的ability名,该类需要在ability中标明。 | 字符串 | 该标签不可缺省。 | +| name | 该标签指明当前静态公共事件对应的ability名,该类需要在ability中标明。 | 字符串 | 不可缺省。 | | permission | 该标签标识实现该静态公共事件需要申请的权限,以字符串类型表示一个权限名称,通常采用反向域名方式表示(最大255字节)。 | 字符串 | 可缺省,缺省值为空。 | -| types | 该标签配置当前静态公共事件的类别数组,字符串数组类型,每个数组元素为一个类别名称。 | 字符串数组 | 该标签可缺省,缺省值为空。 | -| events | 该标签标识能够接收的意图的event值的集合,取值通常为系统预定义的event值,也允许自定义。 | 字符串数组 | 该标签不可缺省。 | +| types | 该标签配置当前静态公共事件的类别数组,字符串数组类型,每个数组元素为一个类别名称。 | 字符串数组 | 可缺省,缺省值为空。 | +| events | 该标签标识能够接收的意图的event值的集合,取值通常为系统预定义的event值,也允许自定义。 | 字符串数组 | 不可缺省。 | + +commonEvents示例 : -在开发视图的resources/base/profile下面定义配置文件common_event_config.json(文件名称可由开发者定义)。 +1.在开发视图的resources/base/profile下面定义配置文件common_event_config.json(文件名称可由开发者定义): ```json { - "commonEvents": [{ - "name": "abilityName", - "permission": "string", - "types": [ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - }] + "commonEvents": [ + { + "name": "abilityName", + "permission": "permissionName", + "types": [ + "type1", + "type2" + ], + "events": [ + "event1", + "event2" + ] + } + ] } ``` -在module.json5的extension组件下面定义metadata信息,如下 : +2.在module.json5的extensionAbilities标签下定义metadata信息 : ```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:common_event_config", - }], +{ + "module": { + "extensionAbilities": [ + { + "name": "subscriber", + "srcEntrance": "./extension/subscriber.js", + "type": "staticSubscriber", + "metadata": [ + { + "name": "ohos.extability.staticSubscriber", + "resource": "$profile:common_event_config" + } + ] + } + ] } -] +} ``` #### distroFilter对象内部结构 标识应用的分发规则。 -该标签用于定义HAP包对应的细分设备规格的分发策略,以便在应用市场进行云端分发应用包时做精准匹配。该标签可配置的分发策略维度包括API Version、屏幕形状、屏幕分辨率。在进行分发时,通过deviceType与这三个属性的匹配关系,唯一确定一个用于分发到设备的HAP。 +该标签用于定义HAP包对应的细分设备规格的分发策略,以便在应用市场进行云端分发应用包时做精准匹配。该标签可配置的分发策略维度包括API Version、屏幕形状、窗口分辨率、屏幕分辨率、国家码。在进行分发时,通过deviceType与这五个属性的匹配关系,唯一确定一个用于分发到设备的HAP。
+配置方式如下:
+module标签配置metadata信息。name :"ohos.module.distro"。resource :指定distroFilter信息的资源位置。 -表16 distroFilter对象内部结构 +表17 distroFilter对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ------------- | ------------------------------------------------------------ | -------- | -------------------------- | -| apiVersion | 标识支持的apiVersion范围。参考表16。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| screenShape | 标识屏幕形状的支持策略。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| screenWindow | 标识应用运行时窗口的分辨率支持策略。该字段仅支持对轻量级智能穿戴设备进行配置。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| screenDensity | 该标签标识屏幕的像素密度(dpi :Dot Per Inch)。该字段可选,如果配置了该字段,取值必须合法。该标签为字符串数组,字符串范围如下。
sdpi :表示小规模的屏幕密度(Small-scale Dots per Inch),适用于dpi取值为(0,120]的设备。
mdpi :表示中规模的屏幕密度(Medium-scale Dots Per Inch),适用于dpi取值为(120,160]的设备。
ldpi :表示大规模的屏幕密度(Large-scale Dots Per Inch),适用于dpi取值为(160,240]的设备。
xldpi :表示大规模的屏幕密度(Extra Large-scale Dots Per Inch),适用于dpi取值为(240,320]的设备。
xxldpi :表示大规模的屏幕密度(Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(320,480]的设备。
xxxldpi :表示大规模的屏幕密度(Extra Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(480, 640]的设备。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| countryCode | 该标签标识应用需要分发的国家地区码,具体值以ISO-3166-1标准为准。支持多个国家和地区枚举定义。该字段可选,如果配置了该字段,取值必须合法。标签值字符串数组,子串表示所支持的国家或地区,由两个大写字母组成。 | 对象数组 | 该标签可缺省,缺省值为空。 | +| apiVersion | 标识支持的apiVersion。 | 对象 | 可缺省,缺省值为空。 | +| screenShape | 标识屏幕形状的支持策略。仅支持liteWearable设备配置。 | 对象 | 可缺省,缺省值为空。 | +| screenWindow | 标识应用运行时窗口的分辨率支持策略。仅支持liteWearable设备配置。 | 对象 | 可缺省,缺省值为空。 | +| screenDensity | 标识屏幕的像素密度(dpi : Dot Per Inch)。 | 对象 | 可缺省,缺省值为空。 | +| countryCode | 标识应用需要分发的国家地区码。具体值以ISO-3166-1标准为准。 | 对象 | 可缺省,缺省值为空。 | -表17 apiVersion对象的内部结构说明 +表18 apiVersion对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 支持的取值为API Version存在的整数值,例如4、5、6。场景示例 :某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 支持的取值为API Version存在的整数值,例如4、5、6,最小取值为3。场景示例 :某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数值数组 | 可缺省,缺省值为空。 | -表18 screenShape对象的内部结构说明 +表19 screenShape对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 支持的取值为circle(圆形)、rect(矩形)。场景示例 :针对智能穿戴设备,可为圆形表盘和矩形表盘分别提供不同的HAP。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 支持的取值为circle(圆形屏幕)、rect(矩形屏幕)。场景示例:针对智能穿戴设备,可为圆形表盘和矩形表盘分别提供不同的HAP。 | 字符串数组 | 可缺省,缺省值为空。 | -表19 screenWindow对象的内部结构说明 +表20 screenWindow对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 单个字符串的取值格式为 :“宽 * 高”,取值为整数像素值,例如“454 * 454”。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 单个字符串的取值格式为 :“宽 * 高”,取值为整数像素值,例如“454 * 454”。 | 字符串数组 | 可缺省,缺省值为空。 | -表20 screenDensity对象的内部结构说明 +表21 screenDensity对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 该标签标识屏幕的像素密度(dpi :Dot Per Inch)。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 字符串范围如下:
sdpi :表示小规模的屏幕密度(Small-scale Dots per Inch),适用于dpi取值为(0,120]的设备。
mdpi :表示中规模的屏幕密度(Medium-scale Dots Per Inch),适用于dpi取值为(120,160]的设备。
ldpi :表示大规模的屏幕密度(Large-scale Dots Per Inch),适用于dpi取值为(160,240]的设备。
xldpi :表示大规模的屏幕密度(Extra Large-scale Dots Per Inch),适用于dpi取值为(240,320]的设备。
xxldpi :表示大规模的屏幕密度(Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(320,480]的设备。
xxxldpi :表示大规模的屏幕密度(Extra Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(480, 640]的设备。 | 字符串数组 | 可缺省,缺省值为空。 | -表21 countryCode对象的内部结构说明 +表22 countryCode对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 该标签标识应用需要分发的国家地区码。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 支持多个国家和地区枚举定义。字符串表示所支持的国家或地区,由两个大写字母组成。 | 字符串数组 | 可缺省,缺省值为空。 | distroFilter示例 : -在开发视图的resources/base/profile下面定义配置文件distroFilter_config.json(文件名称可由开发者定义)。 +1.在开发视图的resources/base/profile下面定义配置文件distro_filter_config.json(文件名称可由开发者定义): ```json "distroFilter": [ @@ -802,39 +902,50 @@ distroFilter示例 : "screenWindow": { "policy": "include", "value": ["454*454", "466*466"] + }, + "screenDensity": { + "policy": "exclude", + "value": ["ldpi", "xldpi"] + }, + "countryCode": { + "policy": "include", + "value": ["CN", "HK"] } } ] ``` -在module.json5的extensionAbilities组件下面定义metadata信息,如下 : +2.在module.json5的module标签下定义metadata信息 : ```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:distroFilter_config", - }], +{ + "module":{ + "metadata": [ + { + "name": "ohos.module.distro", + "resource": "$profile:distro_filter_config" + } + ] } -] +} ``` #### testRunner对象内部结构 -表22 testRunner对象内部结构说明 +该标签用于支持对测试框架的配置 + +表23 testRunner对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ---------------------- | -------- | ---------- | | name | 标识测试框架对象名称。 | 字符串 | 不可缺省。 | | srcPath | 标识测试框架代码路径。 | 字符串 | 不可缺省。 | +testRunner示例 : + ``` "testRunner": { - "name": "myTestRUnnerName", + "name": "testRunnerName", "srcPath": "etc/test/TestRunner.ts" } ``` diff --git a/zh-cn/application-dev/quick-start/start-overview.md b/zh-cn/application-dev/quick-start/start-overview.md index 8b3da7d45a8f15236dcd3ed13f3fecceff8589f4..bd60ac1f216078584fa45713809cf6783153c006 100644 --- a/zh-cn/application-dev/quick-start/start-overview.md +++ b/zh-cn/application-dev/quick-start/start-overview.md @@ -2,10 +2,8 @@ 本文档适用于OpenHarmony应用开发的初学者。通过构建一个简单的具有页面跳转/返回功能的应用(如下图所示),快速了解工程目录的主要文件,熟悉OpenHarmony应用开发流程。 - ![zh-cn_image_0000001364254729](figures/zh-cn_image_0000001364254729.png) - 在开始之前,您需要了解有关OpenHarmony应用的一些基本概念:UI框架的简单说明、Ability的基本概念。 @@ -45,7 +43,7 @@ FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持 ## 工具准备 -1. 安装最新版[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download)。 +1. 安装最新版[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio)。 2. 请参考[配置OpenHarmony SDK](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443),完成**DevEco Studio**的安装和开发环境配置。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-fa.md b/zh-cn/application-dev/quick-start/start-with-ets-fa.md index 8508a182044fa156f6253aa4f08168c32ec694ef..b11c6b5ed204d66584dcc7974525fd18d0a40b7d 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-fa.md @@ -2,22 +2,24 @@ > **说明:** -> 请使用**DevEco Studio V3.0.0.601 Beta1**及更高版本。 -> -> 为确保运行效果,本文以使用**DevEco Studio V3.0.0.993**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download)获取下载链接。 +> +> 请使用**DevEco Studio V3.0.0.601 Beta1**及更高版本。 +> +> 为确保运行效果,本文以使用**DevEco Studio V3.1.0.100**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio)获取下载链接。 -## 创建eTS工程 +## 创建ArkTS工程 1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**OpenHarmony**模板库,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 ![01](figures/01.png) -2. 进入配置工程界面,**Compile SDK** 选择“**8**”(**Compile SDK**选择“**9**”时注意同步选择**Model** 为“**FA**”,此处以选择“**8**”为例),**Language**选择“**eTS**”,其他参数保持默认设置即可。 +2. 进入配置工程界面,**Compile SDK** 选择“**8**”(**Compile SDK**选择“**9**”时注意同步选择**Model** 为“**FA**”,此处以选择“**8**”为例),**Language**选择“**ArkTS**”,其他参数保持默认设置即可。 ![02](figures/02.png) > **说明:** + > > DevEco Studio V3.0 Beta3及更高版本支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 @@ -27,7 +29,9 @@ 3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 -## eTS工程目录结构 +## ArkTS工程目录结构(FA模型) + +![zh-cn_image_0000001384652328](figures/zh-cn_image_0000001384652328.png) - **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 - **src > main > ets**:用于存放ets源码。 @@ -38,11 +42,11 @@ - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > config.json**:模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用包结构配置文件的说明(FA模型)](package-structure.md)。 - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 - - **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 + - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 -- **hvigorfile.js**:应用级编译构建任务脚本。 +- **hvigorfile.ts**:应用级编译构建任务脚本。 ## 构建第一个页面 @@ -112,18 +116,18 @@ 3. 在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。第一个页面效果如下图所示: - ![zh-cn_image_0000001364254741](figures/zh-cn_image_0000001364254741.png) + ![zh-cn_image_0000001311334976](figures/zh-cn_image_0000001311334976.png) ## 构建第二个页面 1. 创建第二个页面。 - - 新建第二个页面文件。在“**Project**”窗口,打开“**entry > src > main > ets > MainAbility**”,右键点击“**pages**”文件夹,选择“**New > eTS File**”,命名为“**second**”,点击“**Finish**”。可以看到文件目录结构如下: - + - 新建第二个页面文件。在“**Project**”窗口,打开“**entry > src > main > ets > MainAbility**”,右键点击“**pages**”文件夹,选择“**New > ArkTS File**”,命名为“**second**”,点击“**Finish**”。可以看到文件目录结构如下: ![zh-cn_image_0000001311334932](figures/zh-cn_image_0000001311334932.png) > **说明:** + > > 开发者也可以在右键点击“**pages**”文件夹时,选择“**New > Page**”,则无需手动配置相关页面路由。 - 配置第二个页面的路由。在config.json文件中的“module - js - pages”下配置第二个页面的路由“pages/second”。示例如下: @@ -273,21 +277,21 @@ } ``` -3. 打开index.ets文件,点击预览器中的![zh-cn_image_0000001311175120](figures/zh-cn_image_0000001311175120.png)按钮进行刷新。效果如下图所示: +3. 打开index.ets文件,点击预览器中的![zh-cn_image_0000001311015192](figures/zh-cn_image_0000001311015192.png)按钮进行刷新。效果如下图所示: - ![zh-cn_image_0000001364173989](figures/zh-cn_image_0000001364173989.png) + ![zh-cn_image_0000001364254729](figures/zh-cn_image_0000001364254729.png) ## 使用真机运行应用 1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 -2. 点击**File**> **Project Structure...** > **Project**>**SigningConfigs** 界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: +2. 点击**File** > **Project Structure...** > **Project** > **SigningConfigs** 界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: ![06](figures/06.png) -3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001311494580](figures/zh-cn_image_0000001311494580.png)按钮运行。效果如下图所示: +3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001364054485](figures/zh-cn_image_0000001364054485.png)按钮运行。效果如下图所示: - ![zh-cn_image_0000001363934577](figures/zh-cn_image_0000001363934577.png) + ![zh-cn_image_0000001364254729](figures/zh-cn_image_0000001364254729.png) 恭喜您已经使用ArkTS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index 2db4732dc202fe9f23bb8b07008869607809a8ec..1699fbf6d46081fe2ee27d81c0d18a5130264f1e 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -2,12 +2,13 @@ > **说明:** +> > 请使用**DevEco Studio V3.0.0.900 Beta3**及更高版本。 > -> 为确保运行效果,本文以使用**DevEco Studio V3.0.0.993**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download)获取下载链接。 +> 为确保运行效果,本文以使用**DevEco Studio V3.1.0.100**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio)获取下载链接。 -## 创建eTS工程 +## 创建ArkTS工程 1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**OpenHarmony**模板库,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 @@ -28,36 +29,32 @@ 3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 -## eTS工程目录结构 +## ArkTS工程目录结构(Stage模型) ![zh-cn_image_0000001364054489](figures/zh-cn_image_0000001364054489.png) -- **AppScope > app.json5**:应用的全局配置信息。 - - **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 - **src > main > ets**:用于存放ets源码。 - - **src > main > ets > Application > AbilityStage.ts**:实现AbilityStage接口。 - - **src > main > ets > MainAbility**:应用/服务的入口。 - - **src > main > ets > MainAbility > MainAbility.ts**:承载Ability生命周期。 - - **src > main > ets > pages**:MainAbility包含的页面。 + - **src > main > ets > entryability**:应用/服务的入口。 + - **src > main > ets > pages**:应用/服务包含的页面。 - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > module.json5**:模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用包结构配置文件的说明(Stage模型)](stage-structure.md)。 - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 - - **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 + - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 -- **hvigorfile.js**:应用级编译构建任务脚本。 +- **hvigorfile.ts**:应用级编译构建任务脚本。 ## 构建第一个页面 1. 使用文本组件。 - 工程同步完成后,在“**Project**”窗口,点击“**entry > src > main > ets > pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下: + 工程同步完成后,在“**Project**”窗口,点击“**entry > src > main > ets > pages**”,打开“**Index.ets**”文件,可以看到页面由Text组件组成。“**Index.ets**”文件的示例如下: ```ts - // index.ets + // Index.ets @Entry @Component struct Index { @@ -79,10 +76,10 @@ 2. 添加按钮。 - 在默认页面基础上,我们添加一个Button组件,作为按钮响应用户点击,从而实现跳转到另一个页面。“**index.ets**”文件的示例如下: + 在默认页面基础上,我们添加一个Button组件,作为按钮响应用户点击,从而实现跳转到另一个页面。“**Index.ets**”文件的示例如下: ```ts - // index.ets + // Index.ets @Entry @Component struct Index { @@ -124,29 +121,30 @@ 1. 创建第二个页面。 - - 新建第二个页面文件。在“**Project**”窗口,打开“**entry > src > main > ets**”,右键点击“**pages**”文件夹,选择“**New > eTS File**”,命名为“**second**”,点击“**Finish**”。可以看到文件目录结构如下: + - 新建第二个页面文件。在“**Project**”窗口,打开“**entry > src > main > ets **”,右键点击“**pages**”文件夹,选择“**New > ArkTS File**”,命名为“**Second**”,点击“**Finish**”。可以看到文件目录结构如下: ![09](figures/09.png) > **说明:** + > > 开发者也可以在右键点击“**pages**”文件夹时,选择“**New > Page**”,则无需手动配置相关页面路由。 - - 配置第二个页面的路由。在“**Project**”窗口,打开“**entry > src > main > resources > base > profile**”,在main_pages.json文件中的“src”下配置第二个页面的路由“pages/second”。示例如下: + - 配置第二个页面的路由。在“**Project**”窗口,打开“**entry > src > main > resources > base > profile**”,在main_pages.json文件中的“src”下配置第二个页面的路由“pages/Second”。示例如下: ```json { "src": [ - "pages/index", - "pages/second" + "pages/Index", + "pages/Second" ] } ``` 2. 添加文本及按钮。 - 参照第一个页面,在第二个页面添加Text组件、Button组件等,并设置其样式。“**second.ets**”文件的示例如下: + 参照第一个页面,在第二个页面添加Text组件、Button组件等,并设置其样式。“**Second.ets**”文件的示例如下: ```ts - // second.ets + // Second.ets @Entry @Component struct Second { @@ -185,10 +183,10 @@ 1. 第一个页面跳转到第二个页面。 - 在第一个页面中,跳转按钮绑定onClick事件,点击按钮时跳转到第二页。“**index.ets**”文件的示例如下: + 在第一个页面中,跳转按钮绑定onClick事件,点击按钮时跳转到第二页。“**Index.ets**”文件的示例如下: ```ts - // index.ets + // Index.ets // 导入页面路由模块 import router from '@ohos.router'; @@ -218,7 +216,7 @@ .height('5%') // 跳转按钮绑定onClick事件,点击时跳转到第二页 .onClick(() => { - router.push({ url: 'pages/second' }) + router.push({ url: 'pages/Second' }) }) } .width('100%') @@ -230,10 +228,10 @@ 2. 第二个页面返回到第一个页面。 - 在第二个页面中,返回按钮绑定onClick事件,点击按钮时返回到第一页。“**second.ets**”文件的示例如下: + 在第二个页面中,返回按钮绑定onClick事件,点击按钮时返回到第一页。“**Second.ets**”文件的示例如下: ```ts - // second.ets + // Second.ets // 导入页面路由模块 import router from '@ohos.router'; @@ -272,21 +270,21 @@ } ``` -3. 打开index.ets文件,点击预览器中的![zh-cn_image_0000001311015192](figures/zh-cn_image_0000001311015192.png)按钮进行刷新。效果如下图所示: +3. 打开Index.ets文件,点击预览器中的![zh-cn_image_0000001311015192](figures/zh-cn_image_0000001311015192.png)按钮进行刷新。效果如下图所示: - ![zh-cn_image_0000001364254773](figures/zh-cn_image_0000001364254773.png) + ![zh-cn_image_0000001364254729](figures/zh-cn_image_0000001364254729.png) ## 使用真机运行应用 1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 -2. 点击**File**> **Project Structure...** > **Project**>**SigningConfigs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: +2. 点击**File** > **Project Structure...** > **Project** > **SigningConfigs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: ![06](figures/06.png) 3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001364054485](figures/zh-cn_image_0000001364054485.png)按钮运行。效果如下图所示: - ![zh-cn_image_0000001311334972](figures/zh-cn_image_0000001311334972.png) + ![zh-cn_image_0000001364254729](figures/zh-cn_image_0000001364254729.png) 恭喜您已经使用ArkTS语言开发(Stage模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 diff --git a/zh-cn/application-dev/quick-start/start-with-js-fa.md b/zh-cn/application-dev/quick-start/start-with-js-fa.md index 5ff342becee7da2850a374270c9d2f0e875615f1..453a0a9e129823cb6d973158d198685c39bbeb61 100644 --- a/zh-cn/application-dev/quick-start/start-with-js-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-js-fa.md @@ -2,6 +2,7 @@ > **说明:** +> > 为确保运行效果,本文以使用**DevEco Studio V3.0.0.993**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download)获取下载链接。 @@ -16,6 +17,7 @@ ![04](figures/04.png) > **说明:** + > > DevEco Studio V2.2 Beta1及更高版本支持使用JS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 @@ -27,6 +29,8 @@ ## JS工程目录结构 +![zh-cn_image_0000001435376433](figures/zh-cn_image_0000001435376433.png) + - **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 - **src > main > js**:用于存放js源码。 - **src > main > js > MainAbility**:应用/服务的入口。 @@ -37,11 +41,11 @@ - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源限定与访问](../ui/js-framework-resource-restriction.md)。 - **src > main > config.json**:模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用包结构配置文件的说明(FA模型)](package-structure.md)。 - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 - - **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 + - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 -- **hvigorfile.js**:应用级编译构建任务脚本。 +- **hvigorfile.ts**:应用级编译构建任务脚本。 ## 构建第一个页面 @@ -211,7 +215,7 @@ } ``` -3. 打开index文件夹下的任意一个文件,点击预览器中的![zh-cn_image_0000001364174013](figures/zh-cn_image_0000001364174013.png)按钮进行刷新。效果如下图所示: +3. 打开index文件夹下的任意一个文件,点击预览器中的![zh-cn_image_0000001311015192](figures/zh-cn_image_0000001311015192.png)按钮进行刷新。效果如下图所示: ![zh-cn_image_0000001311175132](figures/zh-cn_image_0000001311175132.png) @@ -220,17 +224,18 @@ 1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 -2. 点击**File**> **Project Structure...** > **Project**>**Signing Configs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: +2. 点击**File** > **Project Structure...** > **Project** > **Signing Configs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: ![06](figures/06.png) -3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001311494604](figures/zh-cn_image_0000001311494604.png)按钮运行。效果如下图所示: +3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001364054485](figures/zh-cn_image_0000001364054485.png)按钮运行。效果如下图所示: - ![zh-cn_image_0000001363934589](figures/zh-cn_image_0000001363934589.png) + ![zh-cn_image_0000001311175132](figures/zh-cn_image_0000001311175132.png) 恭喜您已经使用JS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 ## 相关实例 针对使用JS语言开发(FA模型),有以下相关实例可供参考: + - [`JsHelloWorld`:你好世界(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/JsHelloWorld) diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index c5d34d86f5b43fa4406c9ac48dc9cce6628edaf9..b0acbfbbdeca2001712ad83c4002d04b5cfb96c0 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -61,33 +61,20 @@ - continuation/[ContinuationResult (ContinuationResult)](js-apis-continuation-continuationResult.md) - 公共事件与通知 - [@ohos.commonEvent (公共事件模块)](js-apis-commonEvent.md) + - [@ohos.commonEventManager (新公共事件模块)](js-apis-commonEventManager.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.notification (Notification模块)](js-apis-notification.md) - application/[EventHub (EventHub)](js-apis-eventhub.md) -- 应用程序包管理 - - [@ohos.bundle (Bundle模块)](js-apis-Bundle.md) - - [@ohos.bundle.defaultAppManager (Bundle模块)](js-apis-bundle-defaultAppManager.md) - - [@ohos.bundle.innerBundleManager (innerBundleManager模块(JS端SDK接口))](js-apis-Bundle-InnerBundleManager.md) - - [@ohos.distributedBundle (distributedBundle模块(JS端SDK接口))](js-apis-Bundle-distributedBundle.md) +- 包管理 + - [@ohos.bundle.appControl(appControl模块)](js-apis-appControl.md) + - [@ohos.bundle.bundleManager (bundleManager模块)](js-apis-bundleManager.md) + - [@ohos.bundle.bundleMonitor(bundleMonitor模块)](js-apis-bundleMonitor.md) + - [@ohos.bundle.defaultAppManager(defaultAppManager模块)](js-apis-defaultAppManager.md) + - [@ohos.bundle.innerBundleManager (innerBundleManager模块)](js-apis-Bundle-InnerBundleManager.md) + - [@ohos.bundle.distributedBundle (distributedBundle模块)](js-apis-distributedBundle.md) + - [@ohos.bundle.freeInstall(freeInstall模块)](js-apis-freeInstall.md) + - [@ohos.bundle.installer(installer模块)](js-apis-installer.md) - [@ohos.zlib (Zip模块)](js-apis-zlib.md) - - bundle/[AbilityInfo (AbilityInfo)](js-apis-bundle-AbilityInfo.md) - - bundle/[ApplicationInfo (ApplicationInfo)](js-apis-bundle-ApplicationInfo.md) - - bundle/[BundleInfo (BundleInfo)](js-apis-bundle-BundleInfo.md) - - bundle/[BundleInstaller (BundleInstaller)](js-apis-bundle-BundleInstaller.md) - - bundle/[BundleStatusCallback (BundleStatusCallback)](js-apis-Bundle-BundleStatusCallback.md) - - bundle/[CustomizeData (CustomizeData)](js-apis-bundle-CustomizeData.md) - - bundle/[DispatchInfo (DispatchInfo)](js-apis-dispatchInfo.md) - - bundle/[ElementName (ElementName)](js-apis-bundle-ElementName.md) - - bundle/[ExtensionAbilityInfo (ExtensionAbilityInfo)](js-apis-bundle-ExtensionAbilityInfo.md) - - bundle/[HapModuleInfo (HapModuleInfo)](js-apis-bundle-HapModuleInfo.md) - - bundle/[LauncherAbilityInfo (LauncherAbilityInfo)](js-apis-bundle-LauncherAbilityInfo.md) - - bundle/[Metadata (Metadata)](js-apis-bundle-Metadata.md) - - bundle/[ModuleInfo (ModuleInfo)](js-apis-bundle-ModuleInfo.md) - - bundle/[PermissionDef (PermissionDef)](js-apis-bundle-PermissionDef.md) - - bundle/[RemoteAbilityInfo (RemoteAbilityInfo)](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[ShortcutInfo(deprecated) (ShortcutInfo)](js-apis-bundle-ShortcutInfo.md) - - bundle/[PackInfo (PackInfo)](js-apis-bundle-PackInfo.md) - - bundleManager/[ShortcutInfo (ShortcutInfo)](js-apis-bundleManager-shortcutInfo.md) - UI界面 - [@ohos.animator (动画)](js-apis-animator.md) - [@ohos.curves (插值计算)](js-apis-curve.md) @@ -202,6 +189,7 @@ - [@ohos.inputmethodengine (输入法服务)](js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability (InputMethodExtensionAbility)](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext (InputMethodExtensionContext)](js-apis-inputmethod-extension-context.md) + - [@ohos.inputmethodsubtype(输入法子类型)](js-apis-inputmethod-subtype.md) - [@ohos.pasteboard (剪贴板)](js-apis-pasteboard.md) - [@ohos.screenLock (锁屏管理)](js-apis-screen-lock.md) - [@ohos.systemTime (系统时间、时区)](js-apis-system-time.md) @@ -219,9 +207,9 @@ - [@ohos.geolocation (位置服务)](js-apis-geolocation.md) - [@ohos.multimodalInput.inputConsumer (组合按键)](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice (输入设备)](js-apis-inputdevice.md) - - [@ohos.multimodalInput.inputDeviceCooperate (键鼠穿越管理)](js-apis-cooperate.md) + - [@ohos.multimodalInput.inputDeviceCooperate (键鼠穿越)](js-apis-cooperate.md) - [@ohos.multimodalInput.inputEvent (输入事件)](js-apis-inputevent.md) - - [@ohos.multimodalInput.inputEventClient (注入按键)](js-apis-inputeventclient.md) + - [@ohos.multimodalInput.inputEventClient (按键注入)](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputMonitor (输入监听)](js-apis-inputmonitor.md) - [@ohos.multimodalInput.keyCode (键值)](js-apis-keycode.md) - [@ohos.multimodalInput.keyEvent (按键输入事件)](js-apis-keyevent.md) @@ -267,13 +255,14 @@ - 测试 - [@ohos.application.testRunner (TestRunner)](js-apis-testRunner.md) - [@ohos.uitest (UiTest)](js-apis-uitest.md) - - 已停止维护的接口 - [@ohos.backgroundTaskManager (后台任务管理)](js-apis-backgroundTaskManager.md) + - [@ohos.bundle(包管理)](js-apis-Bundle.md) - [@ohos.bundleState (设备使用信息统计)](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace (性能打点)](js-apis-bytrace.md) - [@ohos.data.storage (轻量级存储)](js-apis-data-storage.md) - [@ohos.data.distributedData (分布式数据管理)](js-apis-distributed-data.md) + - [@ohos.distributedBundle(分布式包管理)](js-apis-Bundle-distributedBundle.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) - [@ohos.usb (USB管理)](js-apis-usb-deprecated.md) diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Blur.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Blur.png new file mode 100644 index 0000000000000000000000000000000000000000..e3b0acfef7bffa4e6a8c9f9ab6a7dc9b809fa467 Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Blur.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Brightness.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Brightness.png new file mode 100644 index 0000000000000000000000000000000000000000..997602e7d7c8ea440a4f344f6a480ea66022fabf Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Brightness.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Grayscale.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Grayscale.png new file mode 100644 index 0000000000000000000000000000000000000000..69990adea571b907fabd854eb531528d7a60dc8f Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Grayscale.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Main_Color.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Main_Color.png new file mode 100644 index 0000000000000000000000000000000000000000..25e130fcf37fc3654592f619c8a93b703a085e9a Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Main_Color.png differ diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md index 128c916edc2d5616aa91d00d689d360a97cd7c9b..d51482cbf6a0e7af6ca32209d8227119e956c456 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,15 +1,12 @@ # BundleStatusCallback - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - - 应用包回调的信息,通过接口[innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md)获取。 -## BundleStatusCallback +## BundleStatusCallback(deprecated) +> 从API version 9开始不再维护。 **系统API:** 此接口为系统接口,三方应用不支持调用。 @@ -17,9 +14,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-context.md b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md index 4b64eed4162a4bbc9db8cf10e6d4e97c42be8eaa..89222edbdadcf8a22f074e101cd4927d9751da6a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md @@ -13,11 +13,13 @@ AbilityContext模块提供允许访问特定Ability的资源的能力,包括 在使用AbilityContext的功能前,需要通过Ability子类实例获取。 -```js -import Ability from '@ohos.application.Ability'; +```ts +import Ability from '@ohos.app.ability.UIAbility'; + + let context = undefined; class MainAbility extends Ability { onWindowStageCreate(windowStage) { - let context = this.context; + context = this.context; } } ``` @@ -47,17 +49,54 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + bundleName: "com.example.myapp", + abilityName: "MyAbility" }; - this.context.startAbility(want, (error) => { - console.log("error.code = " + error.code) - }) + + try { + this.context.startAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -77,22 +116,59 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | +**错误码:** + +| 错误码ID | 错误信息 +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) - ``` + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` ## AbilityContext.startAbility @@ -115,23 +191,57 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; | -------- | -------- | | Promise<void> | Promise形式返回启动结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + bundleName: "com.example.myapp", + abilityName: "MyAbility" }; var options = { windowMode: 0, }; - this.context.startAbility(want, options) - .then(() => { - console.log('Operation successful.') - }).catch((error) => { - console.log('Operation failed.'); - }) + + try { + this.context.startAbility(want, options) + .then((data) => { + // 执行正常业务 + console.log('startAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -139,7 +249,7 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -启动Ability并在结束的时候返回执行结果(callback形式)。 +启动Ability并在该Ability退出的时候返回执行结果(callback形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -150,24 +260,63 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): | want |[Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | 是 | 执行结果回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **示例:** - ```js - this.context.startAbilityForResult( - {deviceId: "", bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.startAbilityForResult(want, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResult succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityForResult startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -启动Ability并在结束的时候返回执行结果(callback形式)。 +启动Ability并在该Ability退出的时候返回执行结果(callback形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -179,20 +328,59 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | 是 | 执行结果回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **示例:** - ```js + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; var options = { windowMode: 0, }; - this.context.startAbilityForResult( - {deviceId: "", bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); + + try { + this.context.startAbilityForResult(want, options, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResult succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -200,7 +388,7 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -启动Ability并在结束的时候返回执行结果(promise形式)。 +启动Ability并在该Ability退出的时候返回执行结果(promise形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -218,17 +406,57 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityRes | -------- | -------- | | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise形式返回执行结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; var options = { - windowMode: 0, + windowMode: 0, }; - this.context.startAbilityForResult({deviceId: "", bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options).then((result) => { - console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) - }, (error) => { - console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) - }) + + try { + this.context.startAbilityForResult(want, options) + .then((result) => { + // 执行正常业务 + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityForResultWithAccount @@ -251,19 +479,58 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数,返回Ability结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startAbilityWithAccount(want, accountId, (err, data) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - console.log('---------- startAbilityWithAccount success, data: -----------', data); - }); + + try { + this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -288,21 +555,61 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityForResultWithAccount(want, accountId, options, (err) => { - console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -332,25 +639,61 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO | -------- | -------- | | Promise<AbilityResult> | 返回一个Promise,包含Ability结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityForResultWithAccount(want, accountId, options) - .then((data) => { - console.log('---------- startAbilityForResultWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); - }) + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((result) => { + // 执行正常业务 + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startServiceExtensionAbility @@ -369,17 +712,48 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want, (err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startServiceExtensionAbility @@ -398,22 +772,50 @@ startServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want) - .then(() => { - console.log('---------- startServiceExtensionAbility success -----------'); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` + ## AbilityContext.startServiceExtensionAbilityWithAccount startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; @@ -434,18 +836,46 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startServiceExtensionAbilityWithAccount @@ -467,22 +897,50 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId) - .then(() => { - console.log('---------- startServiceExtensionAbilityWithAccount success -----------'); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbility @@ -501,17 +959,45 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want, (err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbility @@ -530,21 +1016,45 @@ stopServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want) - .then(() => { - console.log('---------- stopServiceExtensionAbility success -----------'); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbilityWithAccount @@ -567,18 +1077,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbilityWithAccount @@ -600,22 +1139,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId) - .then(() => { - console.log('---------- stopServiceExtensionAbilityWithAccount success -----------'); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.terminateSelf @@ -632,11 +1196,29 @@ terminateSelf(callback: AsyncCallback<void>): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); + ```ts + this.context.terminateSelf((error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('terminateSelf succeed'); }); ``` @@ -655,13 +1237,27 @@ terminateSelf(): Promise<void>; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - this.context.terminateSelf().then(() => { - console.log('success'); + ```ts + this.context.terminateSelf().then((data) => { + // 执行正常业务 + console.log('terminateSelf succeed'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); }); ``` @@ -681,12 +1277,23 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | 是 | 返回给调用startAbilityForResult 接口调用方的相关信息。 | | callback | AsyncCallback<void> | 是 | callback形式返回停止结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "bundleName": "com.extreme.myapplication", - "abilityName": "SecondAbility" + bundleName: "com.extreme.myapplication", + abilityName: "SecondAbility" } var resultCode = 100; // 返回给接口调用方AbilityResult信息 @@ -694,10 +1301,23 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi want, resultCode } - this.context.terminateSelfWithResult(abilityResult, (error) => { - console.log("terminateSelfWithResult is called = " + error.code) + + try { + this.context.terminateSelfWithResult(abilityResult, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; } - ); + // 执行正常业务 + console.log('terminateSelfWithResult succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -721,12 +1341,24 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; | -------- | -------- | | Promise<void> | promise形式返回停止结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + + **示例:** - ```js + ```ts var want = { - "bundleName": "com.extreme.myapplication", - "abilityName": "SecondAbility" + bundleName: "com.extreme.myapplication", + abilityName: "SecondAbility" } var resultCode = 100; // 返回给接口调用方AbilityResult信息 @@ -734,15 +1366,28 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; want, resultCode } - this.context.terminateSelfWithResult(abilityResult).then((result) => { - console.log("terminateSelfWithResult") + + try { + this.context.terminateSelfWithResult(abilityResult) + .then((data) => { + // 执行正常业务 + console.log('terminateSelfWithResult succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } - ) ``` -## AbilityContext.connectAbility +## AbilityContext.connectServiceExtensionAbility -connectAbility(want: Want, options: ConnectOptions): number; +connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; 使用AbilityInfo.AbilityType.SERVICE模板将当前Ability连接到一个Ability。 @@ -763,27 +1408,46 @@ connectAbility(want: Want, options: ConnectOptions): number; | -------- | -------- | | number | 返回Ability连接的结果code。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - const result = this.context.connectAbility(want, options); - console.log('----------- connectAbilityResult: ------------', result); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## AbilityContext.connectAbilityWithAccount +## AbilityContext.connectServiceExtensionAbilityWithAccount -connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; +connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; 使用AbilityInfo.AbilityType.SERVICE模板和account将当前Ability连接到一个Ability。 @@ -807,13 +1471,26 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions | -------- | -------- | | number | 返回Ability连接的结果code。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { @@ -821,13 +1498,20 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - const result = this.context.connectAbilityWithAccount(want, accountId, options); - console.log('----------- connectAbilityResult: ------------', result); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## AbilityContext.disconnectAbility +## AbilityContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number): Promise\; +disconnectServiceExtensionAbility(connection: number): Promise\; 断开连接(promise形式)。 @@ -847,20 +1531,44 @@ disconnectAbility(connection: number): Promise\; | -------- | -------- | | Promise\ | 返回执行结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - var connectionNumber = 0; - this.context.disconnectAbility(connectionNumber).then(() => { - console.log('disconnectAbility success'); - }).catch((err) => { - console.log('disconnectAbility fail, err: ', err); - }); + ```ts + // connection为connectAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection) + .then((data) => { + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## AbilityContext.disconnectAbility +## AbilityContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number, callback:AsyncCallback\): void; +disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; 断开连接(callback形式)。 @@ -875,13 +1583,39 @@ disconnectAbility(connection: number, callback:AsyncCallback\): void; | connection | number | 是 | 连接的Ability的数字代码。 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - var connectionNumber = 0; - this.context.disconnectAbility(connectionNumber, (err) => { - console.log('---------- disconnectAbility fail, err: -----------', err); + ```ts + // connection为connectServiceExtensionAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityByCall @@ -906,8 +1640,10 @@ startAbilityByCall(want: Want): Promise<Caller>; **示例:** - ```js - let caller = undefined; + 后台启动: + + ```ts + var caller = undefined; // 后台启动Ability,不配置parameters var wantBackground = { @@ -916,13 +1652,29 @@ startAbilityByCall(want: Want): Promise<Caller>; abilityName: "MainAbility", deviceId: "" }; - this.context.startAbilityByCall(wantBackground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + 前台启动: + + ```ts + var caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true var wantForeground = { @@ -934,13 +1686,23 @@ startAbilityByCall(want: Want): Promise<Caller>; "ohos.aafwk.param.callAbilityToForeground": true } }; - this.context.startAbilityByCall(wantForeground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityWithAccount @@ -963,18 +1725,57 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startAbilityWithAccount(want, accountId, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -999,21 +1800,60 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityWithAccount(want, accountId, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -1037,25 +1877,60 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options) - .then(() => { - console.log('---------- startAbilityWithAccount success -----------'); - }) - .catch((err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.requestPermissionsFromUser @@ -1075,7 +1950,7 @@ requestPermissionsFromUser(permissions: Array<string>, requestCallback: As **示例:** - ```js + ```ts var permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions,(result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); @@ -1106,7 +1981,7 @@ requestPermissionsFromUser(permissions: Array<string>) : Promise<Permis **示例:** - ```js + ```ts var permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions).then((data) => { console.log('success:' + JSON.stringify(data)); @@ -1134,7 +2009,7 @@ setMissionLabel(label: string, callback:AsyncCallback<void>): void; **示例:** - ```js + ```ts this.context.setMissionLabel("test",(result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); }); @@ -1163,7 +2038,7 @@ setMissionLabel(label: string): Promise<void>; **示例:** - ```js + ```ts this.context.setMissionLabel("test").then(() => { console.log('success'); }).catch((error) => { @@ -1189,7 +2064,7 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; **示例:** - ```js + ```ts import image from '@ohos.multimedia.image'; var imagePixelMap; var color = new ArrayBuffer(0); @@ -1236,7 +2111,7 @@ setMissionIcon(icon: image.PixelMap): Promise\; **示例:** - ```js + ```ts import image from '@ohos.multimedia.image'; var imagePixelMap; var color = new ArrayBuffer(0); @@ -1277,7 +2152,7 @@ restoreWindowStage(localStorage: LocalStorage) : void; **示例:** - ```js + ```ts var storage = new LocalStorage(); this.context.restoreWindowStage(storage); ``` @@ -1298,7 +2173,7 @@ isTerminating(): boolean; **示例:** - ```js + ```ts var isTerminating = this.context.isTerminating(); console.log('ability state :' + isTerminating); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-animator.md b/zh-cn/application-dev/reference/apis/js-apis-animator.md index 6689361e739a8a6746f1a6fe98b7f19b70977cbb..5a8dad19cbdb6903b750f7ab7ed19aca7acea863 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-animator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-animator.md @@ -34,7 +34,7 @@ create(options: AnimatorOptions): AnimatorResult **示例:** ```js - var options = { + let options = { duration: 1500, easing: 'friction', delay: 0, @@ -79,7 +79,7 @@ reset(options: AnimatorOptions): void **示例:** ```js -var options = { +let options = { duration: 1500, easing: 'friction', delay: 0, @@ -266,7 +266,7 @@ export default { animator: null }, onInit() { - var options = { + let options = { duration: 1500, easing: 'friction', delay: 0, @@ -279,7 +279,7 @@ export default { this.animator = animator.create(options); }, Show() { - var options1 = { + let options1 = { duration: 1500, easing: 'friction', delay: 0, @@ -294,7 +294,7 @@ export default { } catch(error) { console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`); } - var _this = this; + let _this = this; this.animator.onframe = function(value) { _this.divWidth = value; _this.divHeight = value; @@ -353,7 +353,7 @@ createAnimator(options: AnimatorOptions): AnimatorResult **示例:** ```js -var options = { +let options = { duration: 1500, easing: 'friction', delay: 0, diff --git a/zh-cn/application-dev/reference/apis/js-apis-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-appControl.md new file mode 100644 index 0000000000000000000000000000000000000000..71058a3a8c86c7c6c54067cd6f9ea7c2705de741 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-appControl.md @@ -0,0 +1,394 @@ +# appControl模块 + +本模块提供应用拦截能力。对应用设置处置状态后,应用会被禁止运行;用户点击桌面图标时,会根据应用的处置状态,跳转到对应的页面。本模块支持对应用的处置状态进行设置、获取、删除。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## 导入模块 + +``` ts +import appControl from '@ohos.bundle.appControl' +``` + +## appControl.setDisposedStatus + +setDisposedStatus(appId: string, disposedWant: Want): Promise\ + +以异步方法设置应用的处置状态。使用Promise异步回调。成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 需要设置处置状态的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| disposedWant | Want | 是 | 对应用的处置意图。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +var want = {bundleName: 'com.example.myapplication'}; + +try { + appControl.setDisposedStatus(appId, want) + .then(() => { + console.info('setDisposedStatus success'); + }).catch((error) => { + console.error('setDisposedStatus failed ' + error.message); + }); +} catch (error) { + console.error('setDisposedStatus failed ' + error.message); +} +``` + +## appControl.setDisposedStatus + +setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\): void; + +以异步方法设置应用的处置状态。使用callback异步回调。成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| appId | string | 是 | 需要设置处置的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| disposedWant | Want | 是 | 对应用的处置意图。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为undefined,否则为错误对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +var want = {bundleName: 'com.example.myapplication'}; + +try { + appControl.setDisposedStatus(appId, want, (err, data) => { + if (err) { + console.error('setDisposedStatus failed ' + error.message); + return; + } + console.info('setDisposedStatus success'); + }); +} catch (error) { + console.error('setDisposedStatus failed ' + error.message); +} +``` + +## appControl.getDisposedStatus + +getDisposedStatus(appId: string): Promise\; + +以异步方法获取指定应用已设置的处置状态。使用Promise异步回调,成功返回应用的处置状态,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象,返回应用的处置状态。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.getDisposedStatus(appId) + .then((data) => { + console.info('getDisposedStatus success. DisposedStatus: ' + JSON.stringify(data)); + }).catch((error) => { + console.error('getDisposedStatus failed ' + error.message); + }); +} catch (error) { + console.error('getDisposedStatus failed ' + error.message); +} +``` + +## appControl.getDisposedStatus + +getDisposedStatus(appId: string, callback: AsyncCallback\): void; + +以异步方法获取指定应用的处置状态。使用callback异步回调,成功返回应用的处置状态,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.getDisposedStatus(appId, (err, data) => { + if (err) { + console.error('getDisposedStatus failed ' + error.message); + return; + } + console.info('getDisposedStatus success. DisposedStatus: ' + JSON.stringify(data)); + }); +} catch (error) { + console.error('getDisposedStatus failed ' + error.message); +} +``` + +## appControl.deleteDisposedStatus + +deleteDisposedStatus(appId: string): Promise\ + +以异步方法删除应用的处置状态。使用promise异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要删除处置状态的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象,无返回结果的Promise对象 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.deleteDisposedStatus(appId) + .then(() => { + console.info('deleteDisposedStatus success'); + }).catch((error) => { + console.error('deleteDisposedStatus failed ' + error.message); + }); +} catch (error) { + console.error('deleteDisposedStatus failed ' + error.message); +} +``` + +## appControl.deleteDisposedStatus + +deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void + +以异步方法删除应用的处置状态。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.deleteDisposedStatus(appId, (err, data) => { + if (err) { + console.error('deleteDisposedStatus failed ' + error.message); + return; + } + console.info('deleteDisposedStatus success'); + }); +} catch (error) { + console.error('deleteDisposedStatus failed ' + error.message); +} +``` + diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-Want.md b/zh-cn/application-dev/reference/apis/js-apis-application-Want.md index be3a1a0272edf7872b269db394cf6e77c87614f0..bcd3d7213b44ff085acd546ddb78aaf97f870c5c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-Want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-Want.md @@ -3,7 +3,7 @@ Want模块提供系统的基本通信组件的能力。 > **说明:** -> +> > 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -24,9 +24,9 @@ import Want from '@ohos.application.Want'; | 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 | 否 | 表示action选项描述。 | -| parameters | 只读 | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示发起方的uid。[Bundle](js-apis-Bundle.md)模块中userId参数,可用于获取应用信息、包信息等,具体参考:[Bundle](js-apis-Bundle.md)。 | -| entities | 只读 | Array\ | 否 | 表示entities相关描述。 | +| 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)。 | **示例:** @@ -46,79 +46,91 @@ import Want from '@ohos.application.Want'; }) ``` -- 传递FD数据,FD表示文件描述符(FileDescriptor) +- 通过自定字段传递数据, 以下为当前支持类型。 - ``` js - import fileio from '@ohos.fileio'; - var fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); - } - var want = { - "deviceId": "", // deviceId为空表示本设备 - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName非必选 - "parameters": { - "keyFd":{"type":"FD", "value":fd} + * 字符串(String) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForString: "str", + }, } - }; - this.context.startAbility(want, (error) => { - // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability - console.log("error.code = " + error.code) - }) - ``` - -- 传递RemoteObject数据 - - ``` js - import rpc from '@ohos.rpc'; - import Ability from '@ohos.application.Ability' - - class Stub extends rpc.RemoteObject { - constructor(des) { - if (typeof des == 'string') { - super(des); - } else { - return null; - } + ``` + * 数字(Number) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForInt: 100, + keyForDouble: 99.99, + }, } - - onRemoteRequest(code, data, reply, option) { - if (code === 1) { - console.log('onRemoteRequest called') - let token = data.readInterfaceToken(); - let num = data.readInt(); - this.method(); - return true; - } - return false; + ``` + * 布尔(Boolean) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForBool: true, + }, } - - method() { - console.log('method called'); + ``` + * 对象(Object) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForObject: { + keyForObjectString: "str", + keyForObjectInt: -200, + keyForObjectDouble: 35.5, + keyForObjectBool: false, + }, + }, } - } - - var remoteObject = new Stub('want-test'); - var want = { - "deviceId": "", // deviceId为空表示本设备 - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName非必选 - "parameters": { - "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} + ``` + * 数组(Array) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForArrayString: ["str1", "str2", "str3"], + keyForArrayInt: [100, 200, 300, 400], + keyForArrayDouble: [0.1, 0.2], + keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], + }, } - }; - - this.context.startAbility(want, (error) => { - // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability - console.log("error.code = " + error.code) - }) + ``` + * 文件描述符(FD) + ```ts + import fileio from '@ohos.fileio'; + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // deviceId为空表示本设备 + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry", // moduleName非必选 + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability + console.log("error.code = " + error.code) + }) + ``` - ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md index 1c67e86ee5d26139313b32180d9beb9a54accbf1..fc61145af95542b9d40503644445fa2337f1c2d6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md @@ -45,8 +45,8 @@ Ability创建时回调,执行初始化业务逻辑操作。 | param | AbilityConstant.LaunchParam | 是 | 创建 ability、上次异常退出的原因信息。 | **示例:** - - ```js + + ```ts class myAbility extends Ability { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); @@ -71,7 +71,7 @@ onWindowStageCreate(windowStage: window.WindowStage): void **示例:** - ```js + ```ts class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -90,7 +90,7 @@ onWindowStageDestroy(): void **示例:** - ```js + ```ts class myAbility extends Ability { onWindowStageDestroy() { console.log('onWindowStageDestroy'); @@ -115,7 +115,7 @@ onWindowStageRestore(windowStage: window.WindowStage): void **示例:** - ```js + ```ts class myAbility extends Ability { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); @@ -134,7 +134,7 @@ Ability生命周期回调,在销毁时回调,执行资源清理等操作。 **示例:** - ```js + ```ts class myAbility extends Ability { onDestroy() { console.log('onDestroy'); @@ -153,7 +153,7 @@ Ability生命周期回调,当应用从后台转到前台时触发。 **示例:** - ```js + ```ts class myAbility extends Ability { onForeground() { console.log('onForeground'); @@ -172,7 +172,7 @@ Ability生命周期回调,当应用从前台转到后台时触发。 **示例:** - ```js + ```ts class myAbility extends Ability { onBackground() { console.log('onBackground'); @@ -203,7 +203,7 @@ onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; **示例:** - ```js + ```ts import AbilityConstant from "@ohos.application.AbilityConstant" class myAbility extends Ability { onContinue(wantParams) { @@ -232,7 +232,7 @@ onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; **示例:** - ```js + ```ts class myAbility extends Ability { onNewWant(want) { console.log('onNewWant, want:' + want.abilityName); @@ -257,7 +257,7 @@ onConfigurationUpdated(config: Configuration): void; **示例:** - ```js + ```ts class myAbility extends Ability { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); @@ -281,7 +281,7 @@ dump(params: Array\): Array\; **示例:** - ```js + ```ts class myAbility extends Ability { dump(params) { console.log('dump, params:' + JSON.stringify(params)); @@ -306,7 +306,7 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; **示例:** - ```js + ```ts class myAbility extends Ability { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); @@ -320,7 +320,6 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; 通用组件Caller通信客户端调用接口, 用来向通用组件服务端发送约定数据。 - ## Caller.call call(method: string, data: rpc.Sequenceable): Promise<void>; @@ -342,54 +341,65 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; | -------- | -------- | | Promise<void> | Promise形式返回应答。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ // 自定义的Sequenceable数据结构 - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } }; var method = 'call_Function'; // 约定的通知消息字符串 var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); // 参考Sequenceable数据定义 - caller.call(method, msg) - .then(() => { - console.log('Caller call() called'); - }).catch((e) => { - console.log('Caller call() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble("msg", "world"); // 参考Sequenceable数据定义 + caller.call(method, msg) + .then(() => { + console.log('Caller call() called'); + }) + .catch((callErr) => { + console.log('Caller.call catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` @@ -415,55 +425,67 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa | -------- | -------- | | Promise<rpc.MessageParcel> | Promise形式返回通用组件服务端应答数据。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + **示例:** - - ```js - import Ability from '@ohos.application.Ability'; + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } }; var method = 'call_Function'; var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); - caller.callWithResult(method, msg) - .then((data) => { - console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); - data.readSequenceable(retmsg); - }).catch((e) => { - console.log('Caller callWithResult() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble(1, "world"); + caller.callWithResult(method, msg) + .then((data) => { + console.log('Caller callWithResult() called'); + let retmsg = new MyMessageAble(0, ""); + data.readSequenceable(retmsg); + }) + .catch((callErr) => { + console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` @@ -476,36 +498,46 @@ release(): void; **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.release(); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.release(); + } catch (releaseErr) { + console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + + ' error.message: ' + JSON.stringify(releaseErr.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` -## Caller.onRelease +## Caller.on -onRelease(callback: OnReleaseCallBack): void; + on(type: "release", callback: OnReleaseCallback): void; 注册通用组件服务端Stub(桩)断开监听通知。 @@ -515,33 +547,43 @@ onRelease(callback: OnReleaseCallBack): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | type | string | 是 | 监听releaseCall事件,固定为'release'。 | | callback | OnReleaseCallBack | 是 | 返回onRelease回调结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.onRelease((str) => { - console.log(' Caller OnRelease CallBack is called ' + str); - }); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.on("release", (str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }); + } catch (error) { + console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` @@ -550,7 +592,6 @@ onRelease(callback: OnReleaseCallBack): void; 通用组件服务端注册和解除客户端caller通知送信的callback接口。 - ## Callee.on on(method: string, callback: CalleeCallBack): void; @@ -566,10 +607,18 @@ on(method: string, callback: CalleeCallBack): void; | method | string | 是 | 与客户端约定的通知消息字符串。 | | callback | CalleeCallBack | 是 | 一个rpc.MessageParcel类型入参的js通知同步回调函数, 回调函数至少要返回一个空的rpc.Sequenceable数据对象, 其他视为函数执行错误。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200004 | Method registered. The method has registered. | +| 16000050 | Internal Error. | + **示例:** - - ```js - import Ability from '@ohos.application.Ability'; + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -599,14 +648,18 @@ on(method: string, callback: CalleeCallBack): void; return new MyMessageAble(10, "Callee test"); } export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.on(method, funcCallBack); + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); } + } } ``` - ## Callee.off off(method: string): void; @@ -621,20 +674,34 @@ off(method: string): void; | -------- | -------- | -------- | -------- | | method | string | 是 | 已注册的通知事件字符串。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200005 | Method not registered. The method has not registered. | +| 16000050 | Internal Error. | + + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; var method = 'call_Function'; export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.off(method); + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.off(method); + } catch (error) { + console.log('Callee.off catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); } + } } ``` -## OnReleaseCallBack +## OnReleaseCallback (msg: string): void; @@ -644,7 +711,7 @@ off(method: string): void; | -------- | -------- | -------- | -------- | -------- | | (msg: string) | function | 是 | 否 | 调用者注册的侦听器函数接口的原型。 | -## CalleeCallBack +## CalleeCallback (indata: rpc.MessageParcel): rpc.Sequenceable; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md index 7fb56e487ec5d78cd1f6ae87edbc645faee0a5bc..978d61fb22593e3bd13d26f1cec086de57720e5d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md @@ -8,17 +8,17 @@ ## 使用说明 -通过abilityDelegator中的executeShellCommand方法来获取。 +通过abilityDelegator中的[executeShellCommand](js-apis-application-abilityDelegator.md#executeshellcommand)方法来获取。 ```js -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; -var cmd = "cmd"; -var timeout = 100; +import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; +let abilityDelegator; +let cmd = "cmd"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { - console.info("executeShellCommand promise"); +abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { + console.info("executeShellCommand callback, failed: ", err); + console.info("executeShellCommand callback, success: ", data); }); ``` @@ -30,5 +30,5 @@ Shell命令执行结果 | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| stdResult | string | 是 | 是 | 标准输出内容 | -| exitCode | number | 是 | 是 | 结果码 | +| stdResult | string | 是 | 是 | 标准输出内容。 | +| exitCode | number | 是 | 是 | 结果码。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md index 3914df193cee7647614ef2dee59689654c094bce..44d9ce297359623bc6c77ffc43fe33bfb8575d75 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md @@ -96,9 +96,10 @@ add(element: T): boolean let b = [1, 2, 3]; let result2 = arrayList.add(b); let c = {name: "Dylon", age: "13"}; - let result3 = arrayList.add(false); + let result3 = arrayList.add(c); + let result4 = arrayList.add(false); try { - arraylist.add.bind({}, "b")(); + arraylist.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -136,17 +137,17 @@ arrayList.insert("A", 0); arrayList.insert(0, 1); arrayList.insert(true, 2); try { - arraylist.insert.bind({}, 1, 2)(); + arraylist.insert.bind({}, 1, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - let res = arrayList.insert(8, 11); + let res = arrayList.insert(8, 11); // 测试越界异常 } catch (err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - let res = arrayList.insert("a", "b"); + let res = arrayList.insert("a", "b"); // 测试类型异常 } catch (err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -188,7 +189,7 @@ let result = arrayList.has("squirrel"); arrayList.add("squirrel"); let result1 = arrayList.has("squirrel"); try { - arraylist.has.bind({}, "squirrel")(); + arraylist.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -235,7 +236,7 @@ arrayList.add(2); arrayList.add(4); let result = arrayList.getIndexOf(2); try { - arraylist.getIndexOf.bind({}, 2)(); + arraylist.getIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -282,7 +283,7 @@ arrayList.add(2); arrayList.add(4); let result = arrayList.getLastIndexOf(2); try { - arraylist.getLastIndexOf.bind({}, 2)(); + arraylist.getLastIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -328,17 +329,17 @@ arrayList.add(2); arrayList.add(4); let result = arrayList.removeByIndex(2); try { - arraylist.removeByIndex.bind({}, 2)(); + arraylist.removeByIndex.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.removeByIndex("a"); + arraylist.removeByIndex("a"); // 测试类型异常 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.removeByIndex(8); + arraylist.removeByIndex(8); // 测试越界异常 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -382,7 +383,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.remove(2); try { - arraylist.remove.bind({}, 2)(); + arraylist.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -421,15 +422,13 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.removeByRange(2, 4); -arrayList.removeByRange(4, 3); -arrayList.removeByRange(2, 6); try { - arraylist.removeByRange.bind({}, 2, 4)(); + arraylist.removeByRange.bind({}, 2, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.removeByRange(8, 4); + arraylist.removeByRange(8, 4); // 测试越界异常 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -484,7 +483,7 @@ arrayList.replaceAllElements((value: number, index: number) => { try { arraylist.replaceAllElements.bind({}, (value: number, index: number)=> { return value = 2 * value; - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -536,7 +535,7 @@ arrayList.forEach((value, index) => { try { arraylist.forEach.bind({}, (value, index) => { console.log(`value:${value}`, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -583,7 +582,7 @@ arrayList.sort((a: number, b: number) => a - b); arrayList.sort((a: number, b: number) => b - a); arrayList.sort(); try { - arraylist.sort.bind({})(); + arraylist.sort.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -631,7 +630,7 @@ let result1 = arrayList.subArrayList(2, 4); let result2 = arrayList.subArrayList(4, 3); let result3 = arrayList.subArrayList(2, 6); try { - arraylist.subArrayList.bind({}, 2, 4)(); + arraylist.subArrayList.bind({}, 2, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -668,7 +667,7 @@ arrayList.add(5); arrayList.add(4); arrayList.clear(); try { - arraylist.clear.bind({})(); + arraylist.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -707,7 +706,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.clone(); try { - arraylist.clone.bind({})(); + arraylist.clone.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -745,7 +744,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.getCapacity(); try { - arraylist.getCapacity.bind({})(); + arraylist.getCapacity.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -783,7 +782,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.convertToArray(); try { - arraylist.convertToArray.bind({})(); + arraylist.convertToArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -821,7 +820,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.isEmpty(); try { - arraylist.isEmpty.bind({})(); + arraylist.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -860,7 +859,7 @@ arrayList.add(4); arrayList.increaseCapacityTo(2); arrayList.increaseCapacityTo(8); try { - arraylist.increaseCapacityTo.bind({}, 5)(); + arraylist.increaseCapacityTo.bind({}, 5)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -892,7 +891,7 @@ arrayList.add(5); arrayList.add(4); arrayList.trimToCurrentLength(); try { - arraylist.trimToCurrentLength.bind({})(); + arraylist.trimToCurrentLength.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -942,7 +941,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - arraylist[Symbol.iterator].bind({})(); + arraylist[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 0fddf9e9588d7165b64047f31cc65001127b671b..fd8c5a68e0bbcb5bc50bd0dec63377c551e66f84 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -20,13 +20,11 @@ import audio from '@ohos.multimedia.audio'; ## 常量 -**系统接口:** 该接口为系统接口 - -**系统能力:** SystemCapability.Multimedia.Audio.Device - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----- | -------------------------- | ---- | ---- | ------------------ | -| LOCAL_NETWORK_ID9+ | string | 是 | 否 | 本地设备网络id。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------------------------- | ----------| ---- | ---- | ------------------ | +| LOCAL_NETWORK_ID9+ | string | 是 | 否 | 本地设备网络id。
此接口为系统接口。
**系统能力:** SystemCapability.Multimedia.Audio.Device | +| DEFAULT_VOLUME_GROUP_ID9+ | number | 是 | 否 | 默认音量组id。
**系统能力:** SystemCapability.Multimedia.Audio.Volume | +| DEFAULT_INTERRUPT_GROUP_ID9+ | number | 是 | 否 | 默认音频中断组id。
**系统能力:** SystemCapability.Multimedia.Audio.Interrupt | **示例:** @@ -34,6 +32,8 @@ import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio'; const localNetworkId = audio.LOCAL_NETWORK_ID; +const defaultVolumeGroupId = audio.DEFAULT_VOLUME_GROUP_ID; +const defaultInterruptGroupId = audio.DEFAULT_INTERRUPT_GROUP_ID; ``` ## audio.getAudioManager @@ -263,6 +263,8 @@ createTonePlayer(options: AudioRendererInfo, callback: AsyncCallback<TonePlay **系统能力:** SystemCapability.Multimedia.Audio.Tone +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -281,6 +283,7 @@ let audioRendererInfo = { "rendererFlags": 0 } let tonePlayer; + audio.createTonePlayer(audioRendererInfo, (err, data) => { console.info(`callback call createTonePlayer: audioRendererInfo: ${audioRendererInfo}`); if (err) { @@ -300,6 +303,8 @@ createTonePlayer(options: AudioRendererInfo): Promise<TonePlayer> **系统能力:** SystemCapability.Multimedia.Audio.Tone +**系统接口:** 该接口为系统接口 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -338,18 +343,31 @@ async function createTonePlayer(){ | RINGTONE | 2 | 铃声。 | | MEDIA | 3 | 媒体。 | | VOICE_ASSISTANT8+ | 9 | 语音助手。 | -| ALL9+ | 100 | 所有公共音频流。
此接口为系统接口,三方应用不支持调用。| +| ALL9+ | 100 | 所有公共音频流。
此接口为系统接口。| + +## InterruptRequestResultType9+ + +枚举,音频中断请求结果类型。 + +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt + +**系统接口:** 该接口为系统接口 + +| 名称 | 默认值 | 描述 | +| ---------------------------- | ------ | ---------- | +| INTERRUPT_REQUEST_GRANT | 0 | 请求音频中断成功。 | +| INTERRUPT_REQUEST_REJECT | 1 | 请求音频中断失败,可能具有较高优先级类型。 | ## InterruptMode9+ 枚举,焦点模型。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt | 名称 | 默认值 | 描述 | | ---------------------------- | ------ | ---------- | -| SHARE_MODE | 0 | 共享焦点模式。 | -| INDEPENDENT_MODE| 1 | 独立焦点模式。 | +| SHARE_MODE | 0 | 共享焦点模式。 | +| INDEPENDENT_MODE | 1 | 独立焦点模式。 | ## DeviceFlag @@ -359,14 +377,13 @@ async function createTonePlayer(){ | 名称 | 默认值 | 描述 | | ------------------------------- | ------ | ------------------------------------------------- | -| NONE_DEVICES_FLAG9+ | 0 | 无
此接口为系统接口,三方应用不支持调用。 | +| NONE_DEVICES_FLAG9+ | 0 | 无
此接口为系统接口。 | | OUTPUT_DEVICES_FLAG | 1 | 输出设备。 | | INPUT_DEVICES_FLAG | 2 | 输入设备。 | | ALL_DEVICES_FLAG | 3 | 所有设备。 | -| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | 分布式输出设备。
此接口为系统接口,三方应用不支持调用。 | -| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | 分布式输入设备。
此接口为系统接口,三方应用不支持调用。 | -| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | 分布式输入和输出设备。
此接口为系统接口,三方应用不支持调用。 | - +| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | 分布式输出设备。
此接口为系统接口。 | +| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | 分布式输入设备。
此接口为系统接口。 | +| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | 分布式输入和输出设备。
此接口为系统接口。 | ## DeviceRole @@ -379,7 +396,6 @@ async function createTonePlayer(){ | INPUT_DEVICE | 1 | 输入设备角色。 | | OUTPUT_DEVICE | 2 | 输出设备角色。 | - ## DeviceType 枚举,设备类型。 @@ -399,16 +415,15 @@ async function createTonePlayer(){ | USB_HEADSET | 22 | USB耳机,带麦克风。 | | DEFAULT9+ | 1000 | 默认设备类型。 | -## ActiveDeviceType +## CommunicationDeviceType9+ -枚举,活跃设备类型。 +枚举,用于通信的可用设备类型。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Communication -| 名称 | 默认值 | 描述 | -| ------------- | ------ | ---------------------------------------------------- | -| SPEAKER | 2 | 扬声器。 | -| BLUETOOTH_SCO | 7 | 蓝牙设备SCO(Synchronous Connection Oriented)连接。 | +| 名称 | 默认值 | 描述 | +| ------------- | ------ | -------------| +| SPEAKER | 2 | 扬声器。 | ## AudioRingMode @@ -437,6 +452,22 @@ async function createTonePlayer(){ | SAMPLE_FORMAT_S32LE | 3 | 带符号的32位整数,小尾数。
由于系统限制,该采样格式仅部分设备支持,请根据实际情况使用。| | SAMPLE_FORMAT_F32LE9+ | 4 | 带符号的32位整数,小尾数。
由于系统限制,该采样格式仅部分设备支持,请根据实际情况使用。| +## AudioErrors9+ + +枚举,音频错误码。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core + +| 错误信息 | 错误码 | 错误描述 | +| ---------------------| --------| ----------------- | +| ERROR_INVALID_PARAM | 6800101 | 无效入参。 | +| ERROR_NO_MEMORY | 6800102 | 分配内存失败。 | +| ERROR_ILLEGAL_STATE | 6800103 | 状态不支持。 | +| ERROR_UNSUPPORTED | 6800104 | 参数选项不支持。 | +| ERROR_TIMEOUT | 6800105 | 处理超时。 | +| ERROR_STREAM_LIMIT | 6800201 | 音频流数量达到限制。| +| ERROR_SYSTEM | 6800301 | 系统处理异常。 | + ## AudioChannel8+ 枚举, 音频声道。 @@ -508,18 +539,17 @@ async function createTonePlayer(){ | STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | 语音播报。 | | STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | 通知铃声。 | -## FocusType9+ +## InterruptRequestType9+ -表示焦点类型的枚举。 +枚举,音频中断请求类型。 **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Core - -| 名称 | 默认值 | 描述 | -| ---------------------------------- | ------ | ------------------------------- | -| FOCUS_TYPE_RECORDING | 0 | 在录制场景使用,可打断其他音频。 | +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt +| 名称 | 默认值 | 描述 | +| ---------------------------------- | ------ | ------------------------- | +| INTERRUPT_REQUEST_TYPE_DEFAULT | 0 | 默认类型,可中断音频请求。 | ## AudioState8+ @@ -586,29 +616,18 @@ async function createTonePlayer(){ | INTERRUPT_HINT_DUCK | 4 | 提示音频躲避。(躲避:音量减弱,而不会停止) | | INTERRUPT_HINT_UNDUCK8+ | 5 | 提示音量恢复。 | -## InterruptActionType - -枚举,中断事件返回类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer - -| 名称 | 默认值 | 描述 | -| -------------- | ------ | ------------------ | -| TYPE_ACTIVATED | 0 | 表示触发焦点事件。 | -| TYPE_INTERRUPT | 1 | 表示音频打断事件。 | - ## AudioStreamInfo8+ 音频流信息。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core -| 名称 | 类型 | 必填 | 说明 | -| ------------ | ---------------------------------------- | ---- | ------------------ | -| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | 是 | 音频文件的采样率。 | -| channels | [AudioChannel](#audiochannel8) | 是 | 音频文件的通道数。 | -| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | 是 | 音频采样格式。 | -| encodingType | [AudioEncodingType](#audioencodingtype8) | 是 | 音频编码格式。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ------------------------------------------------- | ---- | ------------------ | +| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | 是 | 音频文件的采样率。 | +| channels | [AudioChannel](#audiochannel8) | 是 | 音频文件的通道数。 | +| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | 是 | 音频采样格式。 | +| encodingType | [AudioEncodingType](#audioencodingtype8) | 是 | 音频编码格式。 | ## AudioRendererInfo8+ @@ -622,6 +641,19 @@ async function createTonePlayer(){ | usage | [StreamUsage](#streamusage) | 是 | 音频流使用类型。 | | rendererFlags | number | 是 | 音频渲染器标志。 | +## InterruptResult9+ + +音频中断结果。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Interrupt + +**系统接口:** 该接口为系统接口 + +| 名称 | 类型 | 必填 | 说明 | +| --------------| -------------------------------------------------------------- | ---- | ---------------- | +| requestResult | [InterruptRequestResultType](#interruptrequestresulttype9) | 是 | 表示音频请求中断类型。 | +| interruptNode | number | 是 | 音频请求中断的节点。 | + ## AudioRendererOptions8+ 音频渲染器选项信息。 @@ -645,31 +677,6 @@ async function createTonePlayer(){ | forceType | [InterruptForceType](#interruptforcetype9) | 是 | 操作是由系统执行或是由应用程序执行。 | | hintType | [InterruptHint](#interrupthint) | 是 | 中断提示。 | -## AudioInterrupt - -音频监听事件传入的参数。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer - -| 名称 | 类型 | 必填 | 说明 | -| --------------- | --------------------------- | ---- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | 是 | 音频流使用类型。 | -| contentType | [ContentType](#contenttype) | 是 | 音频打断媒体类型。 | -| pauseWhenDucked | boolean | 是 | 音频打断时是否可以暂停音频播放(true表示音频播放可以在音频打断期间暂停,false表示相反)。 | - -## InterruptAction - -音频打断/获取焦点事件的回调方法。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer - -| 名称 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontype) | 是 | 事件返回类型。TYPE_ACTIVATED为焦点触发事件,TYPE_INTERRUPT为音频打断事件。 | -| type | [InterruptType](#interrupttype) | 否 | 打断事件类型。 | -| hint | [InterruptHint](#interrupthint) | 否 | 打断事件提示。 | -| activated | boolean | 否 | 获得/释放焦点。true表示焦点获取/释放成功,false表示焦点获得/释放失败。 | - ## VolumeEvent8+ 音量改变时,应用接收的事件。 @@ -702,13 +709,21 @@ async function createTonePlayer(){ **系统接口:** 该接口为系统接口 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Volume | 名称 | 默认值 | 描述 | | :------------------------------ | :----- | :--------------------- | | CONNECT_TYPE_LOCAL | 1 | 本地设备。 | | CONNECT_TYPE_DISTRIBUTED | 2 | 分布式设备。 | +## VolumeGroupInfos9+ + +音量组信息,数组类型,为[VolumeGroupInfo](#volumegroupinfo9)的数组,只读。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume + ## VolumeGroupInfo9+ 音量组信息。 @@ -725,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().getVolumeGroups(audio.LOCAL_NETWORK_ID); - console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) -} -getVolumeGroupInfos(); -``` - ## DeviceChangeAction 描述设备连接状态变化和设备信息。 @@ -811,889 +806,968 @@ getVolumeGroupInfos(); | 名称 | 默认值 | 描述 | | :--------------------- | :----- | :-------------------------------------------- | | AUDIO_SCENE_DEFAULT | 0 | 默认音频场景。 | -| AUDIO_SCENE_RINGING | 1 | 响铃模式。
此接口为系统接口,三方应用不支持调用。 | -| AUDIO_SCENE_PHONE_CALL | 2 | 电话模式。
此接口为系统接口,三方应用不支持调用。 | +| AUDIO_SCENE_RINGING | 1 | 响铃模式。
此接口为系统接口。 | +| AUDIO_SCENE_PHONE_CALL | 2 | 电话模式。
此接口为系统接口。 | | AUDIO_SCENE_VOICE_CHAT | 3 | 语音聊天模式。 | ## AudioManager 管理音频音量和音频设备。在调用AudioManager的接口前,需要先通过[getAudioManager](#audiogetaudiomanager)创建实例。 -### getRoutingManager9+ +### setAudioParameter -getRoutingManager(callback: AsyncCallback<AudioRoutingManager>): void +setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void -获取AudioRoutingManager对象,使用callback方式异步返回结果。 +音频参数设置,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 + +**需要权限:** ohos.permission.MODIFY_AUDIO_SETTINGS + +**系统能力:** SystemCapability.Multimedia.Audio.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------------------------------------------- | ---- | --------------------------------- | -| callback | AsyncCallback<[AudioRoutingManager](#audioroutingmanager9)> | 是 | 回调,返回AudioRoutingManager对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| key | string | 是 | 被设置的音频参数的键。 | +| value | string | 是 | 被设置的音频参数的值。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | **示例:** + ```js -audioManager.getRoutingManager((err, callback) => { +audioManager.setAudioParameter('key_example', 'value_example', (err) => { if (err) { - console.error(`Result ERROR: ${err}`); + console.error(`Failed to set the audio parameter. ${err}`); + return; } - console.info('getRoutingManager Callback SUCCESS.'); - let audioRoutingManager; - audioRoutingManager = callback; + console.info('Callback invoked to indicate a successful setting of the audio parameter.'); }); ``` -### getRoutingManager9+ +### setAudioParameter + +setAudioParameter(key: string, value: string): Promise<void> -getRoutingManager(): Promise<AudioRoutingManager> +音频参数设置,使用Promise方式异步返回结果。 -获取AudioRoutingManager对象,使用Promise方式异步返回结果。 +本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**需要权限:** ohos.permission.MODIFY_AUDIO_SETTINGS + +**系统能力:** SystemCapability.Multimedia.Audio.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| key | string | 是 | 被设置的音频参数的键。 | +| value | string | 是 | 被设置的音频参数的值。 | **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | --------------------------------------- | -| Promise<[AudioRoutingManager](#audioroutingmanager9)> | Promise回调返回AudioRoutingManager对象。 | +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | **示例:** + ```js -let audioManager = audio.getAudioManager(); -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - let routingManager = value; - console.info('getRoutingManager Promise SUCCESS.'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioManager.setAudioParameter('key_example', 'value_example').then(() => { + console.info('Promise returned to indicate a successful setting of the audio parameter.'); +}); ``` -### setVolume - -setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void +### getAudioParameter -设置指定流的音量,使用callback方式异步返回结果。 +getAudioParameter(key: string, callback: AsyncCallback<string>): void -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +获取指定音频参数值,使用callback方式异步返回结果。 -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | -| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ---------------------------- | +| key | string | 是 | 待获取的音频参数的键。 | +| callback | AsyncCallback<string> | 是 | 回调返回获取的音频参数的值。 | **示例:** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioManager.getAudioParameter('key_example', (err, value) => { if (err) { - console.error(`Failed to set the volume. ${err}`); + console.error(`Failed to obtain the value of the audio parameter. ${err}`); return; } - console.info('Callback invoked to indicate a successful volume setting.'); + console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`); }); ``` -### setVolume - -setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> +### getAudioParameter -设置指定流的音量,使用Promise方式异步返回结果。 +getAudioParameter(key: string): Promise<string> -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +获取指定音频参数值,使用Promise方式异步返回结果。 -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| key | string | 是 | 待获取的音频参数的键。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<void> | Promise回调表示成功还是失败。 | +| 类型 | 说明 | +| --------------------- | ----------------------------------- | +| Promise<string> | Promise回调返回获取的音频参数的值。 | **示例:** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioManager.getAudioParameter('key_example').then((value) => { + console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`); }); ``` -### getVolume +### setAudioScene8+ -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void -获取指定流的音量,使用callback方式异步返回结果。 +设置音频场景模式,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回音量大小。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------------------- | :--- | :------------------- | +| scene | AudioScene | 是 | 音频场景模式。 | +| callback | AsyncCallback | 是 | 用于返回结果的回调。 | **示例:** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +let audioManager = audio.getAudioManager(); +audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { - console.error(`Failed to obtain the volume. ${err}`); + console.error(`Failed to set the audio scene mode.​ ${err}`); return; } - console.info('Callback invoked to indicate that the volume is obtained.'); + console.info('Callback invoked to indicate a successful setting of the audio scene mode.'); }); ``` -### getVolume +### setAudioScene8+ -getVolume(volumeType: AudioVolumeType): Promise<number> +setAudioScene\(scene: AudioScene\): Promise -获取指定流的音量,使用Promise方式异步返回结果。 +设置音频场景模式,使用Promise方式返回异步结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----------------------------------- | :--- | :------------- | +| scene | AudioScene | 是 | 音频场景模式。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------- | -| Promise<number> | Promise回调返回音量大小。 | +| 类型 | 说明 | +| :------------- | :------------------- | +| Promise | 用于返回结果的回调。 | **示例:** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value} .`); -}); +let audioManager = audio.getAudioManager(); +audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { + console.info('Promise returned to indicate a successful setting of the audio scene mode.'); +}).catch ((err) => { + console.error(`Failed to set the audio scene mode ${err}`); +}); ``` -### getMinVolume +### getAudioScene8+ -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +getAudioScene\(callback: AsyncCallback\): void -获取指定流的最小音量,使用callback方式异步返回结果。 +获取音频场景模式,使用callback方式返回异步结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回最小音量。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :-------------------------------------------------- | :--- | :--------------------------- | +| callback | AsyncCallback<AudioScene> | 是 | 用于返回音频场景模式的回调。 | **示例:** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +let audioManager = audio.getAudioManager(); +audioManager.getAudioScene((err, value) => { if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); + console.error(`Failed to obtain the audio scene mode.​ ${err}`); return; } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); + console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`); }); ``` -### getMinVolume - -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -获取指定流的最小音量,使用Promise方式异步返回结果。 +### getAudioScene8+ -**系统能力:** SystemCapability.Multimedia.Audio.Volume +getAudioScene\(\): Promise -**参数:** +获取音频场景模式,使用Promise方式返回异步结果。 -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +**系统能力:** SystemCapability.Multimedia.Audio.Communication **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------- | -| Promise<number> | Promise回调返回最小音量。 | +| 类型 | 说明 | +| :-------------------------------------------- | :--------------------------- | +| Promise<AudioScene> | 用于返回音频场景模式的回调。 | **示例:** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); +let audioManager = audio.getAudioManager(); +audioManager.getAudioScene().then((value) => { + console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); +}).catch ((err) => { + console.error(`Failed to obtain the audio scene mode ${err}`); }); ``` -### getMaxVolume +### getVolumeManager9+ -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +getVolumeManager(): AudioVolumeManager -获取指定流的最大音量,使用callback方式异步返回结果。 +获取音频音量管理器。 **系统能力:** SystemCapability.Multimedia.Audio.Volume -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ---------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回最大音量大小。 | - **示例:** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); -}); +let audioVolumeManager = audioManager.getVolumeManager(); ``` -### getMaxVolume +### getStreamManager9+ -getMaxVolume(volumeType: AudioVolumeType): Promise<number> +getStreamManager(): AudioStreamManager -获取指定流的最大音量,使用Promise方式异步返回结果。 +获取音频流管理器。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Core -**参数:** +**示例:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +```js +let audioStreamManager = audioManager.getStreamManager(); +``` -**返回值:** +### getRoutingManager9+ -| 类型 | 说明 | -| --------------------- | ----------------------------- | -| Promise<number> | Promise回调返回最大音量大小。 | +getRoutingManager(): AudioRoutingManager + +获取音频路由设备管理器。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **示例:** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); -}); +let audioRoutingManager = audioManager.getRoutingManager(); ``` -### mute +## AudioVolumeManager9+ -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void +音量管理。在使用AudioVolumeManager的接口前,需要使用[getVolumeManager](#getvolumemanager9)获取AudioVolumeManager实例。 -设置指定音量流静音,使用callback方式异步返回结果。 +### getVolumeGroupInfos9+ -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +获取音量组信息列表,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 **系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | -| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | 是 | 设备的网络id。本地设备audio.LOCAL_NETWORK_ID。 | +| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | 是 | 回调,返回音量组信息列表。 | **示例:** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info('Callback invoked to indicate that the stream is muted.'); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); ``` -### mute +### getVolumeGroupInfos9+ -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> - -设置指定音量流静音,使用Promise方式异步返回结果。 +getVolumeGroupInfos(networkId: string\): Promise -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +获取音量组信息列表,使用promise方式异步返回结果。 -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +**系统接口:** 该接口为系统接口 **系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------| ---- | -------------------- | +| networkId | string | 是 | 设备的网络id。本地设备audio.LOCAL_NETWORK_ID。 | **返回值:** | 类型 | 说明 | | ------------------- | ----------------------------- | -| Promise<void> | Promise回调表示成功还是失败。 | +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | 音量组信息列表。 | **示例:** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); -}); +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} ``` +### getVolumeGroupManager9+ -### isMute +getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void - -获取指定音量流是否被静音,使用callback方式异步返回结果。 +获取音频组管理器,使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调返回流静音状态,true为静音,false为非静音。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| groupId | number | 是 | 音量组id。 | +| callback | AsyncCallback< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | 是 | 回调,返回一个音量组实例。 | **示例:** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { if (err) { - console.error(`Failed to obtain the mute status. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); -``` +``` -### isMute +### getVolumeGroupManager9+ -isMute(volumeType: AudioVolumeType): Promise<boolean> +getVolumeGroupManager(groupId: number\): Promise -获取指定音量流是否被静音,使用Promise方式异步返回结果。 +获取音频组管理器,使用promise方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | 是 | 音量组id。 | **返回值:** -| 类型 | 说明 | -| ---------------------- | ------------------------------------------------------ | -| Promise<boolean> | Promise回调返回流静音状态,true为静音,false为非静音。 | +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | 音量组实例。 | **示例:** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); -}); +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +let audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); +console.info('Callback invoked to indicate that the volume group infos list is obtained.'); ``` -### isActive +### on('volumeChange')9+ -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +on(type: 'volumeChange', callback: Callback\): void -获取指定音量流是否为活跃状态,使用callback方式异步返回结果。 +监听系统音量变化事件,使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调返回流的活跃状态,true为活跃,false为不活跃。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'volumeChange'。 | +| callback | Callback<[VolumeEvent](#volumeevent8)> | 是 | 回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); +audioVolumeManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### isActive +## AudioVolumeGroupManager9+ -isActive(volumeType: AudioVolumeType): Promise<boolean> +管理音频组音量。在调用AudioVolumeGroupManager的接口前,需要先通过 [getVolumeGroupManager](#getvolumegroupmanager9) 创建实例。 -获取指定音量流是否为活跃状态,使用Promise方式异步返回结果。 +**系统接口:** 该接口为系统接口 **系统能力:** SystemCapability.Multimedia.Audio.Volume -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------------- | -------------------------------------------------------- | -| Promise<boolean> | Promise回调返回流的活跃状态,true为活跃,false为不活跃。 | - -**示例:** - -```js -audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); -}); -``` - -### setRingerMode +### setVolume9+ -setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void -设置铃声模式,使用callback方式异步返回结果。 +设置指定流的音量,使用callback方式异步返回结果。 **需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -仅在静音和非静音状态切换时需要该权限。 +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------- | ---- | ------------------------ | -| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | -| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | +| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | **示例:** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { - console.error(`Failed to set the ringer mode.​ ${err}`); + console.error(`Failed to set the volume. ${err}`); return; } - console.info('Callback invoked to indicate a successful setting of the ringer mode.'); + console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### setRingerMode +### setVolume9+ -setRingerMode(mode: AudioRingMode): Promise<void> +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -设置铃声模式,使用Promise方式异步返回结果。 +设置指定流的音量,使用Promise方式异步返回结果。 **需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -仅在静音和非静音状态切换时需要该权限。 +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------- | ---- | -------------- | -| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ------------------------------- | -| Promise<void> | Promise回调返回设置成功或失败。 | +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise<void> | Promise回调表示成功还是失败。 | **示例:** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.info('Promise returned to indicate a successful setting of the ringer mode.'); +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); }); ``` +### getVolume9+ -### getRingerMode - -getRingerMode(callback: AsyncCallback<AudioRingMode>): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -获取铃声模式,使用callback方式异步返回结果。 +获取指定流的音量,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | 是 | 回调返回系统的铃声模式。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<number> | 是 | 回调返回音量大小。 | **示例:** ```js -audioManager.getRingerMode((err, value) => { +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the ringer mode.​ ${err}`); + console.error(`Failed to obtain the volume. ${err}`); return; } - console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` +### getVolume9+ -### getRingerMode +getVolume(volumeType: AudioVolumeType): Promise<number> -getRingerMode(): Promise<AudioRingMode> +获取指定流的音量,使用Promise方式异步返回结果。 -获取铃声模式,使用Promise方式异步返回结果。 +**系统能力:** SystemCapability.Multimedia.Audio.Volume -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------------------- | ------------------------------- | -| Promise<[AudioRingMode](#audioringmode)> | Promise回调返回系统的铃声模式。 | +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<number> | Promise回调返回音量大小。 | **示例:** ```js -audioManager.getRingerMode().then((value) => { - console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value}.`); }); ``` -### setAudioParameter - -setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void - -音频参数设置,使用callback方式异步返回结果。 +### getMinVolume9+ -本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -**需要权限:** ohos.permission.MODIFY_AUDIO_SETTINGS +获取指定流的最小音量,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------ | -| key | string | 是 | 被设置的音频参数的键。 | -| value | string | 是 | 被设置的音频参数的值。 | -| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<number> | 是 | 回调返回最小音量。 | **示例:** ```js -audioManager.setAudioParameter('key_example', 'value_example', (err) => { +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the audio parameter. ${err}`); + console.error(`Failed to obtain the minimum volume. ${err}`); return; } - console.info('Callback invoked to indicate a successful setting of the audio parameter.'); + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` -### setAudioParameter - -setAudioParameter(key: string, value: string): Promise<void> - -音频参数设置,使用Promise方式异步返回结果。 +### getMinVolume9+ -本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 +getMinVolume(volumeType: AudioVolumeType): Promise<number> -**需要权限:** ohos.permission.MODIFY_AUDIO_SETTINGS +获取指定流的最小音量,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------- | -| key | string | 是 | 被设置的音频参数的键。 | -| value | string | 是 | 被设置的音频参数的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ------------------------------- | -| Promise<void> | Promise回调返回设置成功或失败。 | +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<number> | Promise回调返回最小音量。 | **示例:** ```js -audioManager.setAudioParameter('key_example', 'value_example').then(() => { - console.info('Promise returned to indicate a successful setting of the audio parameter.'); +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); }); ``` -### getAudioParameter - -getAudioParameter(key: string, callback: AsyncCallback<string>): void +### getMaxVolume9+ -获取指定音频参数值,使用callback方式异步返回结果。 +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 +获取指定流的最大音量,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ---------------------------- | -| key | string | 是 | 待获取的音频参数的键。 | -| callback | AsyncCallback<string> | 是 | 回调返回获取的音频参数的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<number> | 是 | 回调返回最大音量大小。 | **示例:** ```js -audioManager.getAudioParameter('key_example', (err, value) => { +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the value of the audio parameter. ${err}`); + console.error(`Failed to obtain the maximum volume. ${err}`); return; } - console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`); + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getAudioParameter - -getAudioParameter(key: string): Promise<string> +### getMaxVolume9+ -获取指定音频参数值,使用Promise方式异步返回结果。 +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。 +获取指定流的最大音量,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------- | -| key | string | 是 | 待获取的音频参数的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ----------------------------------- | -| Promise<string> | Promise回调返回获取的音频参数的值。 | +| 类型 | 说明 | +| --------------------- | ----------------------------- | +| Promise<number> | Promise回调返回最大音量大小。 | **示例:** ```js -audioManager.getAudioParameter('key_example').then((value) => { - console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`); +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### getDevices +### mute9+ + +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +设置指定音量流静音,使用callback方式异步返回结果。 -获取音频设备列表,使用callback方式异步返回结果。 +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -**系统能力:** SystemCapability.Multimedia.Audio.Device +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回设备列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | +| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | **示例:** + ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { - console.error(`Failed to obtain the device list. ${err}`); + console.error(`Failed to mute the stream. ${err}`); return; } - console.info('Callback invoked to indicate that the device list is obtained.'); + console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### getDevices +### mute9+ -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -获取音频设备列表,使用Promise方式异步返回结果。 +设置指定音量流静音,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------------------------------ | ------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise回调返回设备列表。 | +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise<void> | Promise回调表示成功还是失败。 | **示例:** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### setDeviceActive +### isMute9+ -setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -设置设备激活状态,使用callback方式异步返回结果。 +获取指定音量流是否被静音,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | -| active | boolean | 是 | 设备激活状态。 | -| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回流静音状态,true为静音,false为非静音。 | **示例:** ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the active status of the device. ${err}`); + console.error(`Failed to obtain the mute status. ${err}`); return; } - console.info('Callback invoked to indicate that the device is set to the active status.'); + console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### setDeviceActive +### isMute9+ -setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> +isMute(volumeType: AudioVolumeType): Promise<boolean> -设置设备激活状态,使用Promise方式异步返回结果。 +获取指定音量流是否被静音,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------- | ---- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | -| active | boolean | 是 | 设备激活状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ------------------------------- | -| Promise<void> | Promise回调返回设置成功或失败。 | +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise回调返回流静音状态,true为静音,false为非静音。 | **示例:** - ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### isDeviceActive +### setRingerMode9+ -isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -获取指定设备的激活状态,使用callback方式异步返回结果。 +设置铃声模式,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅在静音和非静音状态切换时需要该权限。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调返回设备的激活状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | **示例:** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); + console.error(`Failed to set the ringer mode.​ ${err}`); return; } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` +### setRingerMode9+ -### isDeviceActive +setRingerMode(mode: AudioRingMode): Promise<void> -isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> +设置铃声模式,使用Promise方式异步返回结果。 -获取指定设备的激活状态,使用Promise方式异步返回结果。 +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -**系统能力:** SystemCapability.Multimedia.Audio.Device +仅在静音和非静音状态切换时需要该权限。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------- | ---- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | **返回值:** -| Type | Description | -| ---------------------- | ------------------------------- | -| Promise<boolean> | Promise回调返回设备的激活状态。 | +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | **示例:** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); +}); +``` + +### getRingerMode9+ + +getRingerMode(callback: AsyncCallback<AudioRingMode>): void + +获取铃声模式,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | 是 | 回调返回系统的铃声模式。 | + +**示例:** + +```js +audioVolumeGroupManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; + } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); +}); +``` + +### getRingerMode9+ + +getRingerMode(): Promise<AudioRingMode> + +获取铃声模式,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise回调返回系统的铃声模式。 | + +**示例:** + +```js +audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` -### setMicrophoneMute +### on('ringerModeChange')9+ + +on(type: 'ringerModeChange', callback: Callback\): void + +监听铃声模式变化事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。 | +| callback | Callback<[AudioRingMode](#audioringmode)> | 是 | 回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | + +**示例:** + +```js +audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); +``` +### setMicrophoneMute9+ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void 设置麦克风静音状态,使用callback方式异步返回结果。 -**需要权限:** ohos.permission.MICROPHONE +**需要权限:** ohos.permission.MANAGE_AUDIO_CONFIG -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** @@ -1705,7 +1779,7 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void **示例:** ```js -audioManager.setMicrophoneMute(true, (err) => { +audioVolumeGroupManager.setMicrophoneMute(true, (err) => { if (err) { console.error(`Failed to mute the microphone. ${err}`); return; @@ -1714,15 +1788,15 @@ audioManager.setMicrophoneMute(true, (err) => { }); ``` -### setMicrophoneMute +### setMicrophoneMute9+ setMicrophoneMute(mute: boolean): Promise<void> 设置麦克风静音状态,使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.MICROPHONE +**需要权限:** ohos.permission.MANAGE_AUDIO_CONFIG -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** @@ -1739,20 +1813,18 @@ setMicrophoneMute(mute: boolean): Promise<void> **示例:** ```js -audioManager.setMicrophoneMute(true).then(() => { +audioVolumeGroupManager.setMicrophoneMute(true).then(() => { console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -### isMicrophoneMute +### isMicrophoneMute9+ isMicrophoneMute(callback: AsyncCallback<boolean>): void 获取麦克风静音状态,使用callback方式异步返回结果。 -**需要权限:** ohos.permission.MICROPHONE - -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** @@ -1763,7 +1835,7 @@ isMicrophoneMute(callback: AsyncCallback<boolean>): void **示例:** ```js -audioManager.isMicrophoneMute((err, value) => { +audioVolumeGroupManager.isMicrophoneMute((err, value) => { if (err) { console.error(`Failed to obtain the mute status of the microphone. ${err}`); return; @@ -1772,15 +1844,13 @@ audioManager.isMicrophoneMute((err, value) => { }); ``` -### isMicrophoneMute +### isMicrophoneMute9+ isMicrophoneMute(): Promise<boolean> 获取麦克风静音状态,使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.MICROPHONE - -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **返回值:** @@ -1790,20 +1860,17 @@ isMicrophoneMute(): Promise<boolean> **示例:** - ```js -audioManager.isMicrophoneMute().then((value) => { +audioVolumeGroupManager.isMicrophoneMute().then((value) => { console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### on('volumeChange')8+ - -on(type: 'volumeChange', callback: Callback\): void +### on('micStateChange')9+ -监听系统音量变化事件。 +on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void -**系统接口:** 该接口为系统接口 +监听系统麦克风状态更改事件。 目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。 @@ -1813,3675 +1880,4125 @@ on(type: 'volumeChange', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'volumeChange'(系统音量变化事件,检测到系统音量改变时,触发该事件)。 | -| callback | Callback<[VolumeEvent](#volumeevent8)> | 是 | 回调方法。 | +| type | string | 是 | 事件回调类型,支持的事件为:'micStateChange'(系统麦克风状态变化事件,检测到系统麦克风状态改变时,触发该事件)。 | +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | 是 | 回调方法,返回变更后的麦克风状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -audioManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); }); ``` -### on('ringerModeChange')8+ +## AudioStreamManager9+ -on(type: 'ringerModeChange', callback: Callback\): void +管理音频流。在使用AudioStreamManager的API前,需要使用[getStreamManager](#getstreammanager9)获取AudioStreamManager实例。 -监听铃声模式变化事件。 +### getCurrentAudioRendererInfoArray9+ -**系统接口:** 该接口为系统接口 +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void -**系统能力:** SystemCapability.Multimedia.Audio.Communication +获取当前音频渲染器的信息。使用callback异步回调。 + +**系统能力**: SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。 | -| callback | Callback<[AudioRingMode](#audioringmode)> | 是 | 回调方法。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数,返回当前音频渲染器的信息。 | **示例:** ```js -audioManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { + console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + } else { + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + } }); ``` -### on('deviceChange') +### getCurrentAudioRendererInfoArray9+ -on(type: 'deviceChange', callback: Callback): void +getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> -设备更改。音频设备连接状态变化。 +获取当前音频渲染器的信息。使用Promise异步回调。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | +| 类型 | 说明 | +| ---------------------------------------------------------------------------------| --------------------------------------- | +| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise对象,返回当前音频渲染器信息。 | **示例:** ```js -audioManager.on('deviceChange', (deviceChanged) => { - console.info(`device change type : ${deviceChanged.type} `); - console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); -}); +async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + }); +} ``` -### off('deviceChange') +### getCurrentAudioCapturerInfoArray9+ -off(type: 'deviceChange', callback?: Callback): void +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void -取消订阅音频设备连接变化事件。 +获取当前音频采集器的信息。使用callback异步回调。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 | +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数,返回当前音频采集器的信息。 | **示例:** ```js -audioManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); +audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { + console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + } else { + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + } }); ``` -### on('interrupt') +### getCurrentAudioCapturerInfoArray9+ -on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void +getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> -请求焦点并开始监听音频打断事件(当应用程序的音频被另一个播放事件中断,回调通知此应用程序) +获取当前音频采集器的信息。使用Promise异步回调。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。 | -| interrupt | AudioInterrupt | 是 | 音频打断事件类型的参数。 | -| callback | Callback<[InterruptAction](#interruptaction)> | 是 | 音频打断事件回调方法。 | +| 类型 | 说明 | +| -----------------------------------------------------------------------------| ----------------------------------- | +| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise对象,返回当前音频渲染器信息。 | **示例:** ```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to gain the audio focus starts.'); - console.info(`Focus gain event: ${InterruptAction} `); - } - if (InterruptAction.actionType === 1) { - console.info('An audio interruption event starts.'); - console.info(`Audio interruption event: ${InterruptAction} `); - } -}); +async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` -### off('interrupt') +### on('audioRendererChange')9+ -off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void -取消监听音频打断事件(删除监听事件,取消打断) +监听音频渲染器更改事件。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。 | -| interrupt | AudioInterrupt | 是 | 音频打断事件类型的参数。 | -| callback | Callback<[InterruptAction](#interruptaction)> | 否 | 音频打断事件回调方法。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------- | --------- | ------------------------------------------------------------------------ | +| type | string | 是 | 事件类型,支持的事件`'audioRendererChange'`:当音频渲染器发生更改时触发。 | +| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to release the audio focus starts.'); - console.info(`Focus release event: ${InterruptAction} `); +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } } }); ``` -### setAudioScene8+ +### off('audioRendererChange')9+ -setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void +off(type: "audioRendererChange"): void -设置音频场景模式,使用callback方式异步返回结果。 +取消监听音频渲染器更改事件。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ---------------- | +| type | string | 是 | 事件类型,支持的事件`'audioRendererChange'`:音频渲染器更改事件。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | + +**示例:** + +```js +audioStreamManager.off('audioRendererChange'); +console.info('######### RendererChange Off is called #########'); +``` + +### on('audioCapturerChange')9+ + +on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void + +监听音频采集器更改事件。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :----------------------------------- | :--- | :------------------- | -| scene | AudioScene | 是 | 音频场景模式。 | -| callback | AsyncCallback | 是 | 用于返回结果的回调。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | +| type | string | 是 | 事件类型,支持的事件`'audioCapturerChange'`:当音频采集器发生更改时触发。 | +| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { - if (err) { - console.error(`Failed to set the audio scene mode.​ ${err}`); - return; +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } } - console.info('Callback invoked to indicate a successful setting of the audio scene mode.'); }); ``` -### setAudioScene8+ - -setAudioScene\(scene: AudioScene\): Promise +### off('audioCapturerChange')9+ -设置音频场景模式,使用Promise方式返回异步结果。 +off(type: "audioCapturerChange"): void; -**系统接口:** 该接口为系统接口 +取消监听音频采集器更改事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----------------------------------- | :--- | :------------- | -| scene | AudioScene | 是 | 音频场景模式。 | - -**返回值:** - -| 类型 | 说明 | -| :------------- | :------------------- | -| Promise | 用于返回结果的回调。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |是 | 事件类型,支持的事件`'audioCapturerChange'`:音频采集器更改事件。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { - console.info('Promise returned to indicate a successful setting of the audio scene mode.'); -}).catch ((err) => { - console.error(`Failed to set the audio scene mode ${err}`); -}); +audioStreamManager.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); + ``` -### getAudioScene8+ +### isActive9+ -getAudioScene\(callback: AsyncCallback\): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -获取音频场景模式,使用callback方式返回异步结果。 +获取指定音量流是否为活跃状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :-------------------------------------------------- | :--- | :--------------------------- | -| callback | AsyncCallback<AudioScene> | 是 | 用于返回音频场景模式的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回流的活跃状态,true为活跃,false为不活跃。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getAudioScene((err, value) => { +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the audio scene mode.​ ${err}`); + console.error(`Failed to obtain the active status of the stream. ${err}`); return; } - console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`); + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` +### isActive9+ -### getAudioScene8+ +isActive(volumeType: AudioVolumeType): Promise<boolean> -getAudioScene\(\): Promise +获取指定音量流是否为活跃状态,使用Promise方式异步返回结果。 -获取音频场景模式,使用Promise方式返回异步结果。 +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**参数:** -**返回值:** +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| 类型 | 说明 | -| :-------------------------------------------- | :--------------------------- | -| Promise<AudioScene> | 用于返回音频场景模式的回调。 | +**返回值:** + +| 类型 | 说明 | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise回调返回流的活跃状态,true为活跃,false为不活跃。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getAudioScene().then((value) => { - console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); -}).catch ((err) => { - console.error(`Failed to obtain the audio scene mode ${err}`); +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### getVolumeGroups9+ +## AudioRoutingManager9+ -getVolumeGroups(networkId: string, callback: AsyncCallback\): void +音频路由管理。在使用AudioRoutingManager的接口前,需要使用[getRoutingManager](#getroutingmanager9)获取AudioRoutingManager实例。 -获取音量组信息列表,使用callback方式异步返回结果。 +### getDevices9+ -**系统接口:** 该接口为系统接口 +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -**系统能力:** SystemCapability.Multimedia.Audio.Volume +获取音频设备列表,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | 是 | 设备的网络id。本地设备audio.LOCAL_NETWORK_ID ,也可以通过getRoutingManager().getDevices()获取全部networkId。 | -| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | 是 | 回调,返回音量组信息列表。 | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回设备列表。 | **示例:** + ```js -let audioManager = audio.getAudioManager(); -audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => { +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); + console.error(`Failed to obtain the device list. ${err}`); return; } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); + console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` -### getVolumeGroups9+ - -getVolumeGroups(networkId: string\): Promise +### getDevices9+ -获取音量组信息列表,使用promise方式异步返回结果。 +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -**系统接口:** 该接口为系统接口 +获取音频设备列表,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | 是 | 设备的网络id。本地设备audio.LOCAL_NETWORK_ID ,也可以通过getRoutingManager().getDevices()获取全部networkId。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | 音量组信息列表。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise回调返回设备列表。 | **示例:** ```js -async function getVolumeGroupInfos(){ - let volumegroupinfos = await audio.getAudioManager().getVolumeGroups(audio.LOCAL_NETWORK_ID); - console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) -} +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); +}); ``` -### getGroupManager9+ - -getGroupManager(groupId: number, callback: AsyncCallback\): void +### on9+ -获取音频组管理器,使用callback方式异步返回结果。 +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -**系统接口:** 该接口为系统接口 +设备更改。音频设备连接状态变化。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| groupId | number | 是 | 音量组id。 | -| callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | 是 | 回调,返回一个音量组实例。 | - -**示例:** - -```js -let audioManager = audio.getAudioManager(); -let audioGroupManager; -async function getGroupManager(){ - let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); - if (value.length > 0) { - let groupid = value[0].groupId; - audioManager.getGroupManager(groupid, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - audioGroupManager = value - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); - }); - } -} -``` - -### getGroupManager9+ - -getGroupManager(groupId: number\): Promise - -获取音频组管理器,使用promise方式异步返回结果。 - -**系统接口:** 该接口为系统接口 - -**系统能力:** SystemCapability.Multimedia.Audio.Volume - -**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------------------- | ---- | ---------------- | -| groupId | number | 是 | 音量组id。 | +**错误码:** -**返回值:** +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise< [AudioGroupManager](#audiogroupmanager9) > | 音量组实例。 | +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -let audioManager = audio.getAudioManager(); -async function getGroupManager(){ - let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); - if (value.length > 0) { - let groupid = value[0].groupId; - let audioGroupManager = await audioManager.getGroupManager(groupid) - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); - } -} +audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type : ' + deviceChanged.type); + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); +}); ``` -### getStreamManager9+ +### off9+ -getStreamManager(callback: AsyncCallback\): void +off(type: 'deviceChange', callback?: Callback): void -获取音频流管理器实例。使用callback方式异步返回结果。 +取消订阅音频设备连接变化事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | 是 | 返回音频流管理器实例。 | - -**示例:** - -```js -let audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); -``` - -### getStreamManager9+ - -getStreamManager(): Promise - -获取音频流管理器实例。使用Promise方式异步返回结果。 +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 | -**系统能力:** SystemCapability.Multimedia.Audio.Core +**错误码:** -**返回值:** +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 -| 类型 | 说明 | -| ---------------------------------------------------- | ---------------- | -| Promise<[AudioStreamManager](#audiostreammanager9)> | 返回音频流管理器实例。 | +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -let audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager().then((data) => { - audioStreamManager = data; - console.info('getStreamManager: Success!'); -}).catch((err) => { - console.error(`getStreamManager: ERROR : ${err}`); +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); - ``` -### requestIndependentInterrupt9+ +### selectInputDevice9+ -requestIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -申请独立焦点,获取独立SessionID,使用callback方式异步返回结果。 +选择音频输入设备,当前只能选择一个输入设备,使用callback方式异步返回结果。 **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------- | ---- | ----------------- | -| focusType | [FocusType](#focustype) | 是 | 焦点类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调,返回焦点申请成功/失败状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输入设备类。 | +| callback | AsyncCallback<void> | 是 | 回调,返回选择输入设备结果。 | **示例:** - ```js -async function requestIndependentInterrupt(){ - let value = await audioManager.requestIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING); - if (value) { - console.info('requestIndependentInterrupt interface for result callback: SUCCESS'); - } else { - console.error('Result ERROR'); - } +let inputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +async function selectInputDevice(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); } ``` -### requestIndependentInterrupt9+ -requestIndependentInterrupt(focusType: FocusType): Promise +### selectInputDevice9+ -申请独立焦点,获取独立SessionID,使用promise方式异步返回结果。 +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +选择音频输入设备,当前只能选择一个输入设备,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | ---- | -| focusType | [FocusType](#focustype) | 是 | 焦点类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输入设备类。 | **返回值:** -| 类型 | 说明 | -| --------------------------------------------------------- | ------------ | -| Promise<boolean> | 返回申请焦点成功/失败状态。 | +| 类型 | 说明 | +| --------------------- | --------------------------- | +| Promise<void> | Promise返回选择输入设备结果。 | **示例:** ```js -async function requestIndependentInterrupt(){ - audioManager.requestIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING).then((value) => { - console.info('Promise returned to succeed '); - }).catch ((err) => { - console.error('Failed to requestIndependentInterrupt'); - }); +let inputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +async function getRoutingManager(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); } ``` -### abandonIndependentInterrupt9+ -abandonIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void +### setCommunicationDevice9+ -废除独立焦点,使用callback方式异步返回结果。 +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void -**系统接口:** 该接口为系统接口 +设置通信设备激活状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------- | ---- | ----------------- | -| focusType | [FocusType](#focustype) | 是 | 焦点类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调,返回废除焦点成功/失败状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | 是 | 音频设备类型。 | +| active | boolean | 是 | 设备激活状态。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | **示例:** ```js -async function abandonIndependentInterrupt(){ - let value = await audioManager.abandonIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING); - if (value) { - console.info('abandonIndependentInterrupt interface for result callback: SUCCESS'); - } else { - console.error('Result ERROR'); +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { + if (err) { + console.error(`Failed to set the active status of the device. ${err}`); + return; } -} + console.info('Callback invoked to indicate that the device is set to the active status.'); +}); ``` -### abandonIndependentInterrupt9+ -abandonIndependentInterrupt(focusType: FocusType): Promise +### setCommunicationDevice9+ -废除独立焦点,使用promise方式异步返回结果。 +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> -**系统接口:** 该接口为系统接口 +设置通信设备激活状态,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---- | ---- | ---- | -| focusType | [FocusType](#focustype) | 是 | 焦点类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | 是 | 活跃音频设备类型。 | +| active | boolean | 是 | 设备激活状态。 | **返回值:** -| 类型 | 说明 | -| --------------------------------------------------------- | ------------ | -| Promise<boolean> | 返回废除焦点成功/失败状态。 | +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | **示例:** ```js -async function abandonIndependentInterrupt(){ - audioManager.abandonIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING).then((value) => { - console.info('Promise returned to succeed'); - }).catch ((err) => { - console.error('Failed to abandonIndependentInterrupt'); - }); -} +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); +}); ``` -## AudioGroupManager9+ -管理音频组音量。在调用AudioGroupManager的接口前,需要先通过 [getGroupManager](#getgroupmanager9) 创建实例。 - -**系统接口:** 该接口为系统接口 - -**系统能力:** SystemCapability.Multimedia.Audio.Volume - -### setVolume9+ -setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void - -设置指定流的音量,使用callback方式异步返回结果。 - -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +### isCommunicationDeviceActive9+ -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void -**系统接口:** 该接口为系统接口 +获取指定通信设备的激活状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | -| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | 是 | 活跃音频设备类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回设备的激活状态。 | **示例:** ```js -audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { if (err) { - console.error(`Failed to set the volume. ${err}`); + console.error(`Failed to obtain the active status of the device. ${err}`); return; } - console.info('Callback invoked to indicate a successful volume setting.'); + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### setVolume9+ - -setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> - -设置指定流的音量,使用Promise方式异步返回结果。 - -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +### isCommunicationDeviceActive9+ -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> -**系统接口:** 该接口为系统接口 +获取指定通信设备的激活状态,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | 是 | 活跃音频设备类型。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<void> | Promise回调表示成功还是失败。 | +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise回调返回设备的激活状态。 | **示例:** ```js -audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` -### getVolume9+ +### selectOutputDevice9+ -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -获取指定流的音量,使用callback方式异步返回结果。 +选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。 **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回音量大小。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | +| callback | AsyncCallback<void> | 是 | 回调,返回获取输出设备结果。 | **示例:** - ```js -audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume is obtained.'); -}); +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); +} ``` -### getVolume9+ - -getVolume(volumeType: AudioVolumeType): Promise<number> +### selectOutputDevice9+ -获取指定流的音量,使用Promise方式异步返回结果。 +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------- | -| Promise<number> | Promise回调返回音量大小。 | +| 类型 | 说明 | +| --------------------- | --------------------------- | +| Promise<void> | Promise返回选择输出设备结果。 | **示例:** ```js -audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value}.`); -}); -``` +let outputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; -### getMinVolume9+ +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} +``` -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### selectOutputDeviceByFilter9+ -获取指定流的最小音量,使用callback方式异步返回结果。 +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回最小音量。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | +| callback | AsyncCallback<void> | 是 | 回调,返回获取输出设备结果。 | **示例:** - ```js -audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); -}); -``` +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; -### getMinVolume9+ +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); +} +``` -getMinVolume(volumeType: AudioVolumeType): Promise<number> +### selectOutputDeviceByFilter9+ -获取指定流的最小音量,使用Promise方式异步返回结果。 +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------- | -| Promise<number> | Promise回调返回最小音量。 | +| 类型 | 说明 | +| --------------------- | --------------------------- | +| Promise<void> | Promise返回选择输出设备结果。 | **示例:** ```js -audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); -}); +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) +} ``` -### getMaxVolume9+ +## AudioRendererChangeInfoArray9+ -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +数组类型,AudioRenderChangeInfo数组,只读。 -获取指定流的最大音量,使用callback方式异步返回结果。 +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**系统接口:** 该接口为系统接口 +## AudioRendererChangeInfo9+ -**系统能力:** SystemCapability.Multimedia.Audio.Volume +描述音频渲染器更改信息。 -**参数:** +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ---------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回最大音量大小。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | +| streamId | number | 是 | 否 | 音频流唯一id。 | +| clientUid | number | 是 | 否 | 音频渲染器客户端应用程序的Uid。
此接口为系统接口。 | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 是 | 否 | 音频渲染器信息。 | +| rendererState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口。| **示例:** ```js -audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +import audio from '@ohos.multimedia.audio'; + +let audioStreamManager; +let resultFlag = false; +let audioManager = audio.getAudioManager(); + +audioManager.getStreamManager((err, data) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; + console.error(`Get AudioStream Manager : ERROR : ${err}`); + } else { + audioStreamManager = data; + console.info('Get AudioStream Manager : Success'); } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); -``` - -### getMaxVolume9+ - -getMaxVolume(volumeType: AudioVolumeType): Promise<number> - -获取指定流的最大音量,使用Promise方式异步返回结果。 - -**系统接口:** 该接口为系统接口 - -**系统能力:** SystemCapability.Multimedia.Audio.Volume - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | ----------------------------- | -| Promise<number> | Promise回调返回最大音量大小。 | - -**示例:** -```js -audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); + console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); + console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); + let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for ${i} is: ${resultFlag}`); + } + } }); ``` -### mute9+ - -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -设置指定音量流静音,使用callback方式异步返回结果。 +## AudioCapturerChangeInfoArray9+ -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +数组类型,AudioCapturerChangeInfo数组,只读。 -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -**系统接口:** 该接口为系统接口 +## AudioCapturerChangeInfo9+ -**系统能力:** SystemCapability.Multimedia.Audio.Volume +描述音频采集器更改信息。 -**参数:** +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Capturer -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | -| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | +| streamId | number | 是 | 否 | 音频流唯一id。 | +| clientUid | number | 是 | 否 | 音频采集器客户端应用程序的Uid。
此接口为系统接口。 | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 否 | 音频采集器信息。 | +| capturerState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口。| **示例:** ```js -audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); - return; + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +let resultFlag = false; +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for element ${i} is: ${resultFlag}`); + } } - console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### mute9+ +## AudioDeviceDescriptors -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> +设备属性数组类型,为[AudioDeviceDescriptor](#audiodevicedescriptor)的数组,只读。 -设置指定音量流静音,使用Promise方式异步返回结果。 +## AudioDeviceDescriptor -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +描述音频设备。 -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------------------------- | -------------------------- | ---- | ---- | ---------- | +| deviceRole | [DeviceRole](#devicerole) | 是 | 否 | 设备角色。 | +| deviceType | [DeviceType](#devicetype) | 是 | 否 | 设备类型。 | +| id9+ | number | 是 | 否 | 设备id。 | +| name9+ | string | 是 | 否 | 设备名称。 | +| address9+ | string | 是 | 否 | 设备地址。 | +| sampleRates9+ | Array<number> | 是 | 否 | 支持的采样率。 | +| channelCounts9+ | Array<number> | 是 | 否 | 支持的通道数。 | +| channelMasks9+ | Array<number> | 是 | 否 | 支持的通道掩码。 | +| networkId9+ | string | 是 | 否 | 设备组网的ID。
此接口为系统接口。 | +| interruptGroupId9+ | number | 是 | 否 | 设备所处的焦点组ID。
此接口为系统接口。 | +| volumeGroupId9+ | number | 是 | 否 | 设备所处的音量组ID。
此接口为系统接口。 | + +**示例:** + +```js +import audio from '@ohos.multimedia.audio'; + +function displayDeviceProp(value) { + deviceRoleValue = value.deviceRole; + deviceTypeValue = value.deviceType; +} + +let deviceRoleValue = null; +let deviceTypeValue = null; +const promise = audio.getAudioManager().getDevices(1); +promise.then(function (value) { + console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); + value.forEach(displayDeviceProp); + if (deviceTypeValue != null && deviceRoleValue != null){ + console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); + } else { + console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); + } +}); +``` + +## AudioRendererFilter9+ + +过滤条件类。在调用selectOutputDeviceByFilter接口前,需要先创建AudioRendererFilter实例。 **系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +| 名称 | 类型 | 必填 | 说明 | +| -------------| ---------------------------------------- | ---- | -------------- | +| uid | number | 是 | 表示应用ID。
**系统能力:** SystemCapability.Multimedia.Audio.Core| +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 否 | 表示渲染器信息。
**系统能力:** SystemCapability.Multimedia.Audio.Renderer| +| rendererId | number | 否 | 音频流唯一id。
**系统能力:** SystemCapability.Multimedia.Audio.Renderer| + +**示例:** + +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +``` + +## AudioRenderer8+ + +提供音频渲染的相关接口。在调用AudioRenderer的接口前,需要先通过[createAudioRenderer](#audiocreateaudiorenderer8)创建实例。 + +### 属性 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | -------------------------- | ---- | ---- | ------------------ | +| state8+ | [AudioState](#audiostate8) | 是 | 否 | 音频渲染器的状态。 | + +**示例:** + +```js +let state = audioRenderer.state; +``` + +### getRendererInfo8+ + +getRendererInfo(callback: AsyncCallback): void + +获取当前被创建的音频渲染器的信息,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------------------------------------- | :--- | :--------------------- | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | 是 | 返回音频渲染器的信息。 | + +**示例:** + +```js +audioRenderer.getRendererInfo((err, rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); +}); +``` + +### getRendererInfo8+ + +getRendererInfo(): Promise + +获取当前被创建的音频渲染器的信息,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<void> | Promise回调表示成功还是失败。 | +| 类型 | 说明 | +| -------------------------------------------------- | ------------------------------- | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise用于返回音频渲染器信息。 | **示例:** ```js -audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); +audioRenderer.getRendererInfo().then((rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); }); ``` -### isMute9+ +### getStreamInfo8+ + +getStreamInfo(callback: AsyncCallback): void + +获取音频流信息,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | 是 | 回调返回音频流信息。 | + +**示例:** + +```js +audioRenderer.getStreamInfo((err, streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +}); +``` + +### getStreamInfo8+ + +getStreamInfo(): Promise + +获取音频流信息,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| :--------------------------------------------- | :--------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise返回音频流信息. | + +**示例:** + +```js +audioRenderer.getStreamInfo().then((streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### getAudioStreamId9+ + +getAudioStreamId(callback: AsyncCallback): void + +获取音频流id,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback | 是 | 回调返回音频流id。 | + +**示例:** + +```js +audioRenderer.getAudioStreamId((err, streamid) => { + console.info(`Renderer GetStreamId: ${streamid}`); +}); +``` + +### getAudioStreamId9+ + +getAudioStreamId(): Promise + +获取音频流id,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| :--------------------------------------------- | :--------------------- | +| Promise | Promise返回音频流id。 | + +**示例:** + +```js +audioRenderer.getAudioStreamId().then((streamid) => { + console.info(`Renderer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### start8+ + +start(callback: AsyncCallback): void + +启动音频渲染器。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | 是 | 回调函数。 | + +**示例:** + +```js +audioRenderer.start((err) => { + if (err) { + console.error('Renderer start failed.'); + } else { + console.info('Renderer start success.'); + } +}); +``` + +### start8+ + +start(): Promise + +启动音频渲染器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | + +**示例:** + +```js +audioRenderer.start().then(() => { + console.info('Renderer started'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### pause8+ + +pause(callback: AsyncCallback\): void + +暂停渲染。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | + +**示例:** + +```js +audioRenderer.pause((err) => { + if (err) { + console.error('Renderer pause failed'); + } else { + console.info('Renderer paused.'); + } +}); +``` + +### pause8+ + +pause(): Promise\ + +暂停渲染。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | + +**示例:** + +```js +audioRenderer.pause().then(() => { + console.info('Renderer paused'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### drain8+ + +drain(callback: AsyncCallback\): void + +检查缓冲区是否已被耗尽。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | + +**示例:** + +```js +audioRenderer.drain((err) => { + if (err) { + console.error('Renderer drain failed'); + } else { + console.info('Renderer drained.'); + } +}); +``` + +### drain8+ + +drain(): Promise\ + +检查缓冲区是否已被耗尽。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | + +**示例:** + +```js +audioRenderer.drain().then(() => { + console.info('Renderer drained successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### stop8+ + +stop(callback: AsyncCallback\): void + +停止渲染。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | + +**示例:** + +```js +audioRenderer.stop((err) => { + if (err) { + console.error('Renderer stop failed'); + } else { + console.info('Renderer stopped.'); + } +}); +``` + +### stop8+ + +stop(): Promise\ + +停止渲染。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | + +**示例:** + +```js +audioRenderer.stop().then(() => { + console.info('Renderer stopped successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### release8+ + +release(callback: AsyncCallback\): void + +释放音频渲染器。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | + +**示例:** + +```js +audioRenderer.release((err) => { + if (err) { + console.error('Renderer release failed'); + } else { + console.info('Renderer released.'); + } +}); +``` + +### release8+ + +release(): Promise\ + +释放渲染器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | + +**示例:** + +```js +audioRenderer.release().then(() => { + console.info('Renderer released successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` + +### write8+ + +write(buffer: ArrayBuffer, callback: AsyncCallback\): void + +写入缓冲区。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | --------------------------------------------------- | +| buffer | ArrayBuffer | 是 | 要写入缓冲区的数据。 | +| callback | AsyncCallback\ | 是 | 回调如果成功,返回写入的字节数,否则返回errorcode。 | + +**示例:** + +```js +let bufferSize; +audioRenderer.getBufferSize().then((data)=> { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); + }); +console.info(`Buffer size: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf, (err, writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); + } +}); +``` -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### write8+ -获取指定音量流是否被静音,使用callback方式异步返回结果。 +write(buffer: ArrayBuffer): Promise\ -**系统接口:** 该接口为系统接口 +写入缓冲区。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调返回流静音状态,true为静音,false为非静音。 | +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise返回结果,如果成功,返回写入的字节数,否则返回errorcode。 | **示例:** ```js -audioGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the mute status. ${err}`); - return; +let bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); + }); +console.info(`BufferSize: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf).then((writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### isMute9+ - -isMute(volumeType: AudioVolumeType): Promise<boolean> +### getAudioTime8+ -获取指定音量流是否被静音,使用Promise方式异步返回结果。 +getAudioTime(callback: AsyncCallback\): void -**系统接口:** 该接口为系统接口 +获取时间戳(从 1970 年 1 月 1 日开始)。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------------- | ------------------------------------------------------ | -| Promise<boolean> | Promise回调返回流静音状态,true为静音,false为非静音。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 回调返回时间戳。 | **示例:** ```js -audioGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); +audioRenderer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -## AudioStreamManager9+ - -管理音频流。在使用AudioStreamManager的API前,需要使用[getStreamManager](#getstreammanager9)获取AudioStreamManager实例。 - -### getCurrentAudioRendererInfoArray9+ +### getAudioTime8+ -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +getAudioTime(): Promise\ -获取当前音频渲染器的信息。使用callback异步回调。 +获取时间戳(从 1970 年 1 月 1 日开始)。使用Promise方式异步返回结果。 -**系统能力**: SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**参数:** +**返回值:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | -------- | --------------------------- | -| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数,返回当前音频渲染器的信息。 | +| 类型 | 描述 | +| ---------------- | ----------------------- | +| Promise\ | Promise回调返回时间戳。 | **示例:** ```js -audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); - if (err) { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - } else { - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } - } +audioRenderer.getAudioTime().then((timestamp) => { + console.info(`Current timestamp: ${timestamp}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### getCurrentAudioRendererInfoArray9+ +### getBufferSize8+ -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +getBufferSize(callback: AsyncCallback\): void -获取当前音频渲染器的信息。使用Promise异步回调。 +获取音频渲染器的最小缓冲区大小。使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer -**返回值:** +**参数:** -| 类型 | 说明 | -| ---------------------------------------------------------------------------------| --------------------------------------- | -| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise对象,返回当前音频渲染器信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 回调返回缓冲区大小。 | **示例:** ```js -async function getCurrentAudioRendererInfoArray(){ - await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - }); -} +let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { + if (err) { + console.error('getBufferSize error'); + } +}); ``` -### getCurrentAudioCapturerInfoArray9+ +### getBufferSize8+ -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +getBufferSize(): Promise\ -获取当前音频采集器的信息。使用callback异步回调。 +获取音频渲染器的最小缓冲区大小。使用Promise方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer -**参数:** +**返回值:** -| 名称 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | -| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数,返回当前音频采集器的信息。 | +| 类型 | 说明 | +| ---------------- | --------------------------- | +| Promise\ | promise回调返回缓冲区大小。 | **示例:** ```js -audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); - if (err) { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - } else { - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - } +let bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); ``` -### getCurrentAudioCapturerInfoArray9+ +### setRenderRate8+ -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void -获取当前音频采集器的信息。使用Promise异步回调。 +设置音频渲染速率。使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer -**返回值:** +**参数:** -| 类型 | 说明 | -| -----------------------------------------------------------------------------| ----------------------------------- | -| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise对象,返回当前音频渲染器信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | +| callback | AsyncCallback\ | 是 | 用于返回执行结果的回调。 | **示例:** - -```js -async function getCurrentAudioCapturerInfoArray(){ - await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - }); -} + +```js +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { + if (err) { + console.error('Failed to set params'); + } else { + console.info('Callback invoked to indicate a successful render rate setting.'); + } +}); ``` -### on('audioRendererChange')9+ +### setRenderRate8+ -on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void +setRenderRate(rate: AudioRendererRate): Promise\ -监听音频渲染器更改事件。 +设置音频渲染速率。使用Promise方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------- | --------- | ------------------------------------------------------------------------ | -| type | string | 是 | 事件类型,支持的事件`'audioRendererChange'`:当音频渲染器发生更改时触发。 | -| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------------------------------- | ---- | ------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise用于返回执行结果。 | **示例:** ```js -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { + console.info('setRenderRate SUCCESS'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### off('audioRendererChange')9+ +### getRenderRate8+ -off(type: "audioRendererChange"); +getRenderRate(callback: AsyncCallback\): void -取消监听音频渲染器更改事件。 +获取当前渲染速率。使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------- | ---- | ---------------- | -| type | string | 是 | 事件类型,支持的事件`'audioRendererChange'`:音频渲染器更改事件。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | 是 | 回调返回渲染速率。 | **示例:** ```js -audioStreamManager.off('audioRendererChange'); -console.info('######### RendererChange Off is called #########'); +audioRenderer.getRenderRate((err, renderrate) => { + console.info(`getRenderRate: ${renderrate}`); +}); ``` -### on('audioCapturerChange')9+ +### getRenderRate8+ -on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void +getRenderRate(): Promise\ -监听音频采集器更改事件。 +获取当前渲染速率。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**参数:** +**返回值:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------- | --------- | ----------------------------------------------------------------------- | -| type | string | 是 | 事件类型,支持的事件`'audioCapturerChange'`:当音频采集器发生更改时触发。 | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数。 | +| 类型 | 说明 | +| ------------------------------------------------- | ------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise回调返回渲染速率。 | **示例:** ```js -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } +audioRenderer.getRenderRate().then((renderRate) => { + console.info(`getRenderRate: ${renderRate}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` +### setInterruptMode9+ -### off('audioCapturerChange')9+ - -off(type: "audioCapturerChange"); +setInterruptMode(mode: InterruptMode): Promise<void> -取消监听音频采集器更改事件。 +设置应用的焦点模型。使用Promise异步回调。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------- | --- | ------------------------------------------------------------- | -| type | string |是 | 事件类型,支持的事件`'audioCapturerChange'`:音频采集器更改事件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------- | ------ | ---------- | +| mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise<void> | 以Promise对象返回结果,设置成功时返回undefined,否则返回error。 | **示例:** ```js -audioStreamManager.off('audioCapturerChange'); -console.info('######### CapturerChange Off is called #########'); - +let mode = 0; +audioRenderer.setInterruptMode(mode).then(data=>{ + console.info('setInterruptMode Success!'); +}).catch((err) => { + console.error(`setInterruptMode Fail: ${err}`); +}); ``` -## AudioRoutingManager9+ - -音频路由管理。在使用AudioRoutingManager的接口前,需要使用[getRoutingManager](#getroutingmanager9)获取AudioRoutingManager实例。 - -### getDevices9+ +### setInterruptMode9+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void -获取音频设备列表,使用callback方式异步返回结果。 +设置应用的焦点模型。使用Callback回调返回执行结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回设备列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------- | ------ | -------------- | +|mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。| +|callback | AsyncCallback\ | 是 |回调返回执行结果。| **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ - if (err) { - console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } else { - AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { - if (err) { - console.error(`Failed to obtain the device list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the device list is obtained.'); - }); +let mode = 1; +audioRenderer.setInterruptMode(mode, (err, data)=>{ + if(err){ + console.error(`setInterruptMode Fail: ${err}`); } -}) + console.info('setInterruptMode Success!'); +}); ``` -### getDevices9+ +### setVolume9+ -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +setVolume(volume: number): Promise<void> -获取音频设备列表,使用Promise方式异步返回结果。 +设置应用的音量。使用Promise异步回调。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ------ | ---------- | +| volume | number | 是 | 音量值。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------------------------------ | ------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise回调返回设备列表。 | +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise<void> | 以Promise对象返回结果,设置成功时返回undefined,否则返回error。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ - if (err) { - console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } - else { - AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); - }); +audioRenderer.setVolume(10).then(data=>{ + console.info('setVolume Success!'); +}).catch((err) => { + console.error(`setVolume Fail: ${err}`); +}); +``` +### setVolume9+ + +setVolume(volume: number, callback: AsyncCallback\): void + +设置应用的音量。使用Callback回调返回执行结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -----------| ------ | -------------- | +|volume | number | 是 | 音量值。| +|callback | AsyncCallback\ | 是 |回调返回执行结果。| + +**示例:** + +```js +audioRenderer.setVolume(10, (err, data)=>{ + if(err){ + console.error(`setVolume Fail: ${err}`); } + console.info('setVolume Success!'); }); ``` -### on9+ +### on('audioInterrupt')9+ -on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void +on(type: 'audioInterrupt', callback: Callback\): void -设备更改。音频设备连接状态变化。 +监听音频中断事件。使用callback获取中断事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +与[on('interrupt')](#oninterruptdeprecated)一致,该接口在AudioRenderer对象start、pause、stop等事件发生前已经主动获取焦点,不需要开发者主动发起焦点申请。 + +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'audioInterrupt'(中断事件被触发,音频播放被中断。) | +| callback | Callback<[InterruptEvent](#interruptevent9)> | 是 | 被监听的中断事件的回调。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ - if (err) { - console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } - else { - AudioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { - console.info('device change type : ' + deviceChanged.type); - console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); - }); +let isPlay; +let started; +audioRenderer.on('audioInterrupt', async(interruptEvent) => { + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Force paused. Stop writing'); + isPlay = false; + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.info('Force stopped. Stop writing'); + isPlay = false; + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + console.info('Resume force paused renderer or ignore'); + await audioRenderer.start().then(async function () { + console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); + started = true; + }).catch((err) => { + console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); + started = false; + }); + if (started) { + isPlay = true; + console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); + } else { + console.error('AudioInterruptMusic Renderer start failed'); + } + break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Choose to pause or ignore'); + if (isPlay == true) { + isPlay == false; + console.info('AudioInterruptMusic: Media PAUSE : TRUE'); + } else { + isPlay = true; + console.info('AudioInterruptMusic: Media PLAY : TRUE'); + } + break; + } } }); ``` -### off9+ +### on('markReach')8+ -off(type: 'deviceChange', callback?: Callback): void +on(type: "markReach", frame: number, callback: Callback<number>): void -取消订阅音频设备连接变化事件。 +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :---------------------------------------- | +| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | +| callback | Callback\ | 是 | 触发事件时调用的回调。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ - if (err) { - console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } else { - AudioRoutingManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); - }); +audioRenderer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### selectInputDevice9+ -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### off('markReach') 8+ -选择音频输入设备,当前只能选择一个输入设备,使用callback方式异步返回结果。 +off(type: 'markReach'): void -**系统接口:** 该接口为系统接口 +取消订阅标记事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输入设备类。 | -| callback | AsyncCallback<void> | 是 | 回调,返回选择输入设备结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :------------------------------------------------ | +| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'markReach'。 | **示例:** -```js -let audioManager = audio.getAudioManager(); -let inputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -let audioRoutingManager; -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select input devices result callback: SUCCESS'); } - }); - }); -} +```js +audioRenderer.off('markReach'); ``` -### on('micStateChange')9+ - -on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void +### on('periodReach') 8+ -监听系统麦克风状态更改事件 +on(type: "periodReach", frame: number, callback: Callback<number>): void -目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。 +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,触发回调并返回设定的值。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'micStateChange'(系统麦克风状态变化事件,检测到系统麦克风状态改变时,触发该事件)。 | -| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | 是 | 回调方法,返回变更后的麦克风状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | +| callback | Callback\ | 是 | 触发事件时调用的回调。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getRoutingManager.on('micStateChange', (micStateChange) => { - console.info(`Current microphone status is: ${micStateChange.mute} `); +audioRenderer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); + } }); ``` -### selectInputDevice9+ - -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> +### off('periodReach') 8+ -**系统接口:** 该接口为系统接口 +off(type: 'periodReach'): void -选择音频输入设备,当前只能选择一个输入设备,使用Promise方式异步返回结果。 +取消订阅标记事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输入设备类。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------- | -| Promise<void> | Promise返回选择输入设备结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :-------------------------------------------------- | +| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'periodReach'。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -let inputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -let audioRoutingManager; - -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { - console.info('Select input devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); - }); -} -``` - -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void - -选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。 - -**系统接口:** 该接口为系统接口 - -**系统能力:** SystemCapability.Multimedia.Audio.Device - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | -| callback | AsyncCallback<void> | 是 | 回调,返回获取输出设备结果。 | - -**示例:** -```js -let audioManager = audio.getAudioManager(); -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -let audioRoutingManager; - -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices result callback: SUCCESS'); } - }); - }); -} +audioRenderer.off('periodReach') ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> +### on('stateChange') 8+ -**系统接口:** 该接口为系统接口 +on(type: 'stateChange', callback: Callback): void -选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。 +订阅监听状态变化。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------- | -| Promise<void> | Promise返回选择输出设备结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'stateChange'。 | +| callback | [AudioState](#audiostate8) | 是 | 返回监听的状态。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -let outputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -let audioRoutingManager; - -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); - }); -} +audioRenderer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); + } +}); ``` -### selectOutputDeviceByFilter9+ - -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void - -**系统接口:** 该接口为系统接口 +## AudioCapturer8+ -根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。 +提供音频采集的相关接口。在调用AudioCapturer的接口前,需要先通过[createAudioCapturer](#audiocreateaudiocapturer8)创建实例。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +### 属性 -**参数:** +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | -| callback | AsyncCallback<void> | 是 | 回调,返回获取输出设备结果。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| :---- | :------------------------- | :--- | :--- | :--------------- | +| state8+ | [AudioState](#audiostate8) | 是 | 否 | 音频采集器状态。 | **示例:** -```js -let audioManager = audio.getAudioManager(); -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -let audioRoutingManager; -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices by filter result callback: SUCCESS'); } - }); - }); -} +```js +let state = audioCapturer.state; ``` -### selectOutputDeviceByFilter9+ - -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> - -**系统接口:** 该接口为系统接口 - -根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。 - -**系统能力:** SystemCapability.Multimedia.Audio.Device +### getCapturerInfo8+ -**参数:** +getCapturerInfo(callback: AsyncCallback): void -| 参数名 | 类型 | 必填 | 说明 | -| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | +获取采集器信息。使用callback方式异步返回结果。 -**返回值:** +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -| 类型 | 说明 | -| --------------------- | --------------------------- | -| Promise<void> | Promise返回选择输出设备结果。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :-------------------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回采集器信息。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -let audioRoutingManager; - -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices by filter result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }) - }); -} +audioCapturer.getCapturerInfo((err, capturerInfo) => { + if (err) { + console.error('Failed to get capture info'); + } else { + console.info('Capturer getCapturerInfo:'); + console.info(`Capturer source: ${capturerInfo.source}`); + console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); + } +}); ``` -## AudioRendererChangeInfo9+ -描述音频渲染器更改信息。 +### getCapturerInfo8+ -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer +getCapturerInfo(): Promise -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | -| streamId | number | 是 | 否 | 音频流唯一id。 | -| clientUid | number | 是 | 否 | 音频渲染器客户端应用程序的Uid。
此接口为系统接口,三方应用不支持调用。 | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 是 | 否 | 音频渲染器信息。 | -| rendererState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口,三方应用不支持调用。| +获取采集器信息。使用Promise方式异步返回结果。 -## AudioRendererChangeInfoArray9+ +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -AudioRenderChangeInfo数组,只读。 +**返回值:** -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +| 类型 | 说明 | +| :------------------------------------------------ | :---------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | 使用Promise方式异步返回采集器信息。 | **示例:** ```js -import audio from '@ohos.multimedia.audio'; - -let audioStreamManager; -let resultFlag = false; -let audioManager = audio.getAudioManager(); - -audioManager.getStreamManager((err, data) => { - if (err) { - console.error(`Get AudioStream Manager : ERROR : ${err}`); +audioCapturer.getCapturerInfo().then((audioParamsGet) => { + if (audioParamsGet != undefined) { + console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); + console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); + console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); } else { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); - } -}); - -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); - console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); - console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); - var devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for ${i} is: ${resultFlag}`); - } + console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); + console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); } +}).catch((err) => { + console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); ``` -## AudioCapturerChangeInfo9+ - -描述音频采集器更改信息。 +### getStreamInfo8+ -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Capturer +getStreamInfo(callback: AsyncCallback): void -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | -| streamId | number | 是 | 否 | 音频流唯一id。 | -| clientUid | number | 是 | 否 | 音频采集器客户端应用程序的Uid。
此接口为系统接口,三方应用不支持调用。 | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 否 | 音频采集器信息。 | -| capturerState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口,三方应用不支持调用。| +获取采集器流信息。使用callback方式异步返回结果。 -## AudioCapturerChangeInfoArray9+ +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -AudioCapturerChangeInfo数组,只读。 +**参数:** -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | 是 | 使用callback方式异步返回流信息。 | **示例:** ```js -import audio from '@ohos.multimedia.audio'; - -const audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { +audioCapturer.getStreamInfo((err, streamInfo) => { if (err) { - console.error(`getStreamManager : Error: ${err}`); + console.error('Failed to get stream info'); } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -let resultFlag = false; -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for element ${i} is: ${resultFlag}`); - } + console.info('Capturer GetStreamInfo:'); + console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Capturer channel: ${streamInfo.channels}`); + console.info(`Capturer format: ${streamInfo.sampleFormat}`); + console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } }); ``` -## AudioDeviceDescriptor +### getStreamInfo8+ -描述音频设备。 +getStreamInfo(): Promise -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device +获取采集器流信息。使用Promise方式异步返回结果。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----------------------------- | -------------------------- | ---- | ---- | ---------- | -| deviceRole | [DeviceRole](#devicerole) | 是 | 否 | 设备角色。 | -| deviceType | [DeviceType](#devicetype) | 是 | 否 | 设备类型。 | -| id9+ | number | 是 | 否 | 设备id。 | -| name9+ | string | 是 | 否 | 设备名称。 | -| address9+ | string | 是 | 否 | 设备地址。 | -| sampleRates9+ | Array<number> | 是 | 否 | 支持的采样率。 | -| channelCounts9+ | Array<number> | 是 | 否 | 支持的通道数。 | -| channelMasks9+ | Array<number> | 是 | 否 | 支持的通道掩码。 | -| networkId9+ | string | 是 | 否 | 设备组网的ID。
此接口为系统接口,三方应用不支持调用。 | -| interruptGroupId9+ | number | 是 | 否 | 设备所处的焦点组ID。
此接口为系统接口,三方应用不支持调用。 | -| volumeGroupId9+ | number | 是 | 否 | 设备所处的音量组ID。
此接口为系统接口,三方应用不支持调用。 | +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -## AudioDeviceDescriptors +**返回值:** -设备属性数组类型,为[AudioDeviceDescriptor](#audiodevicedescriptor)的数组,只读。 +| 类型 | 说明 | +| :--------------------------------------------- | :------------------------------ | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | 使用Promise方式异步返回流信息。 | **示例:** ```js -import audio from '@ohos.multimedia.audio'; - -function displayDeviceProp(value) { - deviceRoleValue = value.deviceRole; - deviceTypeValue = value.deviceType; -} - -let deviceRoleValue = null; -let deviceTypeValue = null; -const promise = audio.getAudioManager().getDevices(1); -promise.then(function (value) { - console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); - value.forEach(displayDeviceProp); - if (deviceTypeValue != null && deviceRoleValue != null){ - console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); - } else { - console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); - } +audioCapturer.getStreamInfo().then((audioParamsGet) => { + console.info('getStreamInfo:'); + console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); + console.info(`samplingRate: ${audioParamsGet.samplingRate}`); + console.info(`channels: ${audioParamsGet.channels}`); + console.info(`encodingType: ${audioParamsGet.encodingType}`); +}).catch((err) => { + console.error(`getStreamInfo :ERROR: ${err}`); }); ``` -## AudioRendererFilter9+ +### getAudioStreamId9+ -过滤条件类。在调用selectOutputDeviceByFilter接口前,需要先创建AudioRendererFilter实例。 +getAudioStreamId(callback: AsyncCallback): void -**系统接口:** 该接口为系统接口 +获取音频流id,使用callback方式异步返回结果。 -| 名称 | 类型 | 必填 | 说明 | -| -------------| ---------------------------------------- | ---- | -------------- | -| uid | number | 是 | 表示应用ID。
**系统能力:** SystemCapability.Multimedia.Audio.Core| -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 否 | 表示渲染器信息。
**系统能力:** SystemCapability.Multimedia.Audio.Renderer| -| rendererId | number | 否 | 音频流唯一id。
**系统能力:** SystemCapability.Multimedia.Audio.Renderer| +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback | 是 | 回调返回音频流id。 | **示例:** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; +audioCapturer.getAudioStreamId((err, streamid) => { + console.info(`audioCapturer GetStreamId: ${streamid}`); +}); ``` -## AudioRenderer8+ +### getAudioStreamId9+ -提供音频渲染的相关接口。在调用AudioRenderer的接口前,需要先通过[createAudioRenderer](#audiocreateaudiorenderer8)创建实例。 +getAudioStreamId(): Promise -### 属性 +获取音频流id,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----- | -------------------------- | ---- | ---- | ------------------ | -| state8+ | [AudioState](#audiostate8) | 是 | 否 | 音频渲染器的状态。 | +**返回值:** + +| 类型 | 说明 | +| :----------------| :--------------------- | +| Promise | Promise返回音频流id。 | **示例:** ```js -let state = audioRenderer.state; +audioCapturer.getAudioStreamId().then((streamid) => { + console.info(`audioCapturer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); ``` -### getRendererInfo8+ +### start8+ -getRendererInfo(callback: AsyncCallback): void +start(callback: AsyncCallback): void -获取当前被创建的音频渲染器的信息,使用callback方式异步返回结果。 +启动音频采集器。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------------------------------------------- | :--- | :--------------------- | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | 是 | 返回音频渲染器的信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -audioRenderer.getRendererInfo((err, rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); +audioCapturer.start((err) => { + if (err) { + console.error('Capturer start failed.'); + } else { + console.info('Capturer start success.'); + } }); ``` -### getRendererInfo8+ -getRendererInfo(): Promise +### start8+ -获取当前被创建的音频渲染器的信息,使用Promise方式异步返回结果。 +start(): Promise -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +启动音频采集器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **返回值:** -| 类型 | 说明 | -| -------------------------------------------------- | ------------------------------- | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise用于返回音频渲染器信息。 | +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -audioRenderer.getRendererInfo().then((rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) +audioCapturer.start().then(() => { + console.info('AudioFrameworkRecLog: ---------START---------'); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); + } }).catch((err) => { - console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); ``` -### getStreamInfo8+ +### stop8+ -getStreamInfo(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -获取音频流信息,使用callback方式异步返回结果。 +停止采集。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------------------------------------- | :--- | :------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | 是 | 回调返回音频流信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -audioRenderer.getStreamInfo((err, streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +audioCapturer.stop((err) => { + if (err) { + console.error('Capturer stop failed'); + } else { + console.info('Capturer stopped.'); + } }); ``` -### getStreamInfo8+ -getStreamInfo(): Promise +### stop8+ -获取音频流信息,使用Promise方式异步返回结果。 +stop(): Promise -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +停止采集。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **返回值:** -| 类型 | 说明 | -| :--------------------------------------------- | :--------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise返回音频流信息. | +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -audioRenderer.getStreamInfo().then((streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +audioCapturer.stop().then(() => { + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ + console.info('AudioFrameworkRecLog: State is Stopped:'); + } }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### start8+ +### release8+ -start(callback: AsyncCallback): void +release(callback: AsyncCallback): void -启动音频渲染器。使用callback方式异步返回结果。 +释放采集器。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :---------------------------------- | +| callback | AsyncCallback | 是 | Callback used to return the result. | **示例:** ```js -audioRenderer.start((err) => { +audioCapturer.release((err) => { if (err) { - console.error('Renderer start failed.'); + console.error('capturer release failed'); } else { - console.info('Renderer start success.'); + console.info('capturer released.'); } }); ``` -### start8+ -start(): Promise +### release8+ -启动音频渲染器。使用Promise方式异步返回结果。 +release(): Promise -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +释放采集器。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | Promise方式异步返回结果。 | +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -audioRenderer.start().then(() => { - console.info('Renderer started'); +let stateFlag; +audioCapturer.release().then(() => { + console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); + console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### pause8+ +### read8+ -pause(callback: AsyncCallback\): void +read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void -暂停渲染。使用callback方式异步返回结果。 +读入缓冲区。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | 是 | 返回回调的结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------------- | :-------------------------- | :--- | :------------------------------- | +| size | number | 是 | 读入的字节数。 | +| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | +| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区。 | **示例:** ```js -audioRenderer.pause((err) => { - if (err) { - console.error('Renderer pause failed'); - } else { - console.info('Renderer paused.'); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + }); +audioCapturer.read(bufferSize, true, async(err, buffer) => { + if (!err) { + console.info('Success in reading the buffer data'); } }); ``` -### pause8+ +### read8+ -pause(): Promise\ +read(size: number, isBlockingRead: boolean): Promise -暂停渲染。使用Promise方式异步返回结果。 +读入缓冲区。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------------- | :------ | :--- | :--------------- | +| size | number | 是 | 读入的字节数。 | +| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | Promise方式异步返回结果。 | +| 类型 | 说明 | +| :-------------------- | :----------------------------------------------------- | +| Promise | 如果操作成功,返回读取的缓冲区数据;否则返回错误代码。 | **示例:** ```js -audioRenderer.pause().then(() => { - console.info('Renderer paused'); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + }); +console.info(`Buffer size: ${bufferSize}`); +audioCapturer.read(bufferSize, true).then((buffer) => { + console.info('buffer read successfully'); }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`ERROR : ${err}`); }); ``` -### drain8+ +### getAudioTime8+ -drain(callback: AsyncCallback\): void +getAudioTime(callback: AsyncCallback): void -检查缓冲区是否已被耗尽。使用callback方式异步返回结果。 +获取时间戳(从1970年1月1日开始),单位为纳秒。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | 是 | 返回回调的结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -audioRenderer.drain((err) => { - if (err) { - console.error('Renderer drain failed'); - } else { - console.info('Renderer drained.'); - } +audioCapturer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -### drain8+ +### getAudioTime8+ -drain(): Promise\ +getAudioTime(): Promise -检查缓冲区是否已被耗尽。使用Promise方式异步返回结果。 +获取时间戳(从1970年1月1日开始),单位为纳秒。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | Promise方式异步返回结果。 | +| 类型 | 说明 | +| :--------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -audioRenderer.drain().then(() => { - console.info('Renderer drained successfully'); +audioCapturer.getAudioTime().then((audioTime) => { + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); ``` -### stop8+ +### getBufferSize8+ -stop(callback: AsyncCallback\): void +getBufferSize(callback: AsyncCallback): void -停止渲染。使用callback方式异步返回结果。 +获取采集器合理的最小缓冲区大小。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | 是 | 返回回调的结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区大小。 | **示例:** ```js -audioRenderer.stop((err) => { - if (err) { - console.error('Renderer stop failed'); - } else { - console.info('Renderer stopped.'); +audioCapturer.getBufferSize((err, bufferSize) => { + if (!err) { + console.info(`BufferSize : ${bufferSize}`); + audioCapturer.read(bufferSize, true).then((buffer) => { + console.info(`Buffer read is ${buffer}`); + }).catch((err) => { + console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + }); } }); ``` -### stop8+ +### getBufferSize8+ -stop(): Promise\ +getBufferSize(): Promise -停止渲染。使用Promise方式异步返回结果。 +获取采集器合理的最小缓冲区大小。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | Promise方式异步返回结果。 | +| 类型 | 说明 | +| :--------------- | :---------------------------------- | +| Promise | 使用Promise方式异步返回缓冲区大小。 | **示例:** ```js -audioRenderer.stop().then(() => { - console.info('Renderer stopped successfully'); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); + bufferSize = data; }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); ``` -### release8+ +### on('markReach')8+ -release(callback: AsyncCallback\): void +on(type: "markReach", frame: number, callback: Callback<number>): void -释放音频渲染器。使用callback方式异步返回结果。 +订阅标记到达的事件。 当采集的帧数达到 frame 参数的值时,回调被触发。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | 是 | 返回回调的结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :---------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于0。 | +| callback | Callback\ | 是 | 使用callback方式异步返回被触发事件的回调。 | **示例:** ```js -audioRenderer.release((err) => { - if (err) { - console.error('Renderer release failed'); - } else { - console.info('Renderer released.'); +audioCapturer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### release8+ +### off('markReach')8+ -release(): Promise\ +off(type: 'markReach'): void -释放渲染器。使用Promise方式异步返回结果。 +取消订阅标记到达的事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -**返回值:** +**参数:** -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | Promise方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :-------------------------------------------- | +| type | string | 是 | 取消事件回调类型,支持的事件为:'markReach'。 | **示例:** ```js -audioRenderer.release().then(() => { - console.info('Renderer released successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioCapturer.off('markReach'); ``` -### write8+ +### on('periodReach')8+ -write(buffer: ArrayBuffer, callback: AsyncCallback\): void +on(type: "periodReach", frame: number, callback: Callback<number>): void -写入缓冲区。使用callback方式异步返回结果。 +订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,触发回调并返回设定的值。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | --------------------------------------------------- | -| buffer | ArrayBuffer | 是 | 要写入缓冲区的数据。 | -| callback | AsyncCallback\ | 是 | 回调如果成功,返回写入的字节数,否则返回errorcode。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于0。 | +| callback | Callback\ | 是 | 使用callback方式异步返回被触发事件的回调 | **示例:** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data)=> { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf, (err, writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); +audioCapturer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### write8+ +### off('periodReach')8+ -write(buffer: ArrayBuffer): Promise\ +off(type: 'periodReach'): void -写入缓冲区。使用Promise方式异步返回结果。 +取消订阅标记到达的事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -**返回值:** +**参数:** -| 类型 | 说明 | -| ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise返回结果,如果成功,返回写入的字节数,否则返回errorcode。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :---------------------------------------------- | +| type | string | 是 | 取消事件回调类型,支持的事件为:'periodReach'。 | **示例:** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`BufferSize: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf).then((writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioCapturer.off('periodReach') ``` -### getAudioTime8+ +### on('stateChange') 8+ -getAudioTime(callback: AsyncCallback\): void +on(type: 'stateChange', callback: Callback): void -获取时间戳(从 1970 年 1 月 1 日开始)。使用callback方式异步返回结果。 +订阅监听状态变化。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | 是 | 回调返回时间戳。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'stateChange'。 | +| callback | [AudioState](#audiostate8) | 是 | 返回监听的状态。 | **示例:** ```js -audioRenderer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); +audioCapturer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio capturer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio capturer state is: STATE_RUNNING'); + } }); ``` -### getAudioTime8+ +## ToneType9+ -getAudioTime(): Promise\ +枚举,播放器的音调类型。 -获取时间戳(从 1970 年 1 月 1 日开始)。使用Promise方式异步返回结果。 +**系统接口:** 该接口为系统接口 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Tone -**返回值:** +| 名称 | 默认值 | 描述 | +| :------------------------------------------------ | :----- | :----------------------------| +| TONE_TYPE_DIAL_0 | 0 | 键0的DTMF音。 | +| TONE_TYPE_DIAL_1 | 1 | 键1的DTMF音。 | +| TONE_TYPE_DIAL_2 | 2 | 键2的DTMF音。 | +| TONE_TYPE_DIAL_3 | 3 | 键3的DTMF音。 | +| TONE_TYPE_DIAL_4 | 4 | 键4的DTMF音。 | +| TONE_TYPE_DIAL_5 | 5 | 键5的DTMF音。 | +| TONE_TYPE_DIAL_6 | 6 | 键6的DTMF音。 | +| TONE_TYPE_DIAL_7 | 7 | 键7的DTMF音。 | +| TONE_TYPE_DIAL_8 | 8 | 键8的DTMF音。 | +| TONE_TYPE_DIAL_9 | 9 | 键9的DTMF音。 | +| TONE_TYPE_DIAL_S | 10 | 键*的DTMF音。 | +| TONE_TYPE_DIAL_P | 11 | 键#的DTMF音。 | +| TONE_TYPE_DIAL_A | 12 | 键A的DTMF音。 | +| TONE_TYPE_DIAL_B | 13 | 键B的DTMF音。 | +| TONE_TYPE_DIAL_C | 14 | 键C的DTMF音。 | +| TONE_TYPE_DIAL_D | 15 | 键D的DTMF音。 | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | 呼叫监管音调,拨号音。 | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | 呼叫监管音调,忙。 | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | 呼叫监管音调,拥塞。 | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | 呼叫监管音调,无线电 ACK。 | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | 呼叫监管音调,无线电不可用。 | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | 呼叫监管音调,呼叫等待。 | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | 呼叫监管音调,铃声。 | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | 专有声调,一般蜂鸣声。 | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | 专有声调,ACK。 | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | 专有声调,PROMPT。 | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | 专有声调,双重蜂鸣声。 | -| 类型 | 描述 | -| ---------------- | ----------------------- | -| Promise\ | Promise回调返回时间戳。 | +## TonePlayer9+ -**示例:** +提供播放和管理DTMF(Dual Tone Multi Frequency,双音多频)音调的方法,包括各种系统监听音调、专有音调,如拨号音、通话回铃音等。 -```js -audioRenderer.getAudioTime().then((timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); -``` +**系统接口:** 该接口为系统接口 -### getBufferSize8+ +### load9+ -getBufferSize(callback: AsyncCallback\): void +load(type: ToneType, callback: AsyncCallback<void>): void -获取音频渲染器的最小缓冲区大小。使用callback方式异步返回结果。 +加载DTMF音调配置。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Tone **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | 是 | 回调返回缓冲区大小。 | +| 参数名 | 类型 | 必填 | 说明 | +| :--------------| :-------------------------- | :-----| :------------------------------ | +| type | [ToneType](#tonetype9) | 是 | 配置的音调类型。 | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { if (err) { - console.error('getBufferSize error'); + console.error(`callback call load failed error: ${err.message}`); + return; + } else { + console.info('callback call load success'); } }); ``` -### getBufferSize8+ +### load9+ -getBufferSize(): Promise\ +load(type: ToneType): Promise<void> -获取音频渲染器的最小缓冲区大小。使用Promise方式异步返回结果。 +加载DTMF音调配置。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Tone + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------------- | :--------------------- | :--- | ---------------- | +| type | [ToneType](#tonetype9) | 是 | 配置的音调类型。 | **返回值:** -| 类型 | 说明 | -| ---------------- | --------------------------- | -| Promise\ | promise回调返回缓冲区大小。 | +| 类型 | 说明 | +| :--------------| :-------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); }); ``` -### setRenderRate8+ +### start9+ -setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void +start(callback: AsyncCallback<void>): void -设置音频渲染速率。使用callback方式异步返回结果。 +启动DTMF音调播放。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Tone **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | -| callback | AsyncCallback\ | 是 | 用于返回执行结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { +tonePlayer.start((err) => { if (err) { - console.error('Failed to set params'); + console.error(`callback call start failed error: ${err.message}`); + return; } else { - console.info('Callback invoked to indicate a successful render rate setting.'); + console.info('callback call start success'); } }); ``` -### setRenderRate8+ - -setRenderRate(rate: AudioRendererRate): Promise\ - -设置音频渲染速率。使用Promise方式异步返回结果。 +### start9+ -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +start(): Promise<void> -**参数:** +启动DTMF音调播放。使用Promise方式异步返回结果。 -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------------------------------- | ---- | ------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | +**系统能力:** SystemCapability.Multimedia.Audio.Tone **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | Promise用于返回执行结果。 | +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.info('setRenderRate SUCCESS'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); }); ``` -### getRenderRate8+ +### stop9+ -getRenderRate(callback: AsyncCallback\): void +stop(callback: AsyncCallback<void>): void -获取当前渲染速率。使用callback方式异步返回结果。 +停止当前正在播放的音调。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Tone **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | 是 | 回调返回渲染速率。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -audioRenderer.getRenderRate((err, renderrate) => { - console.info(`getRenderRate: ${renderrate}`); +tonePlayer.stop((err) => { + if (err) { + console.error(`callback call stop error: ${err.message}`); + return; + } else { + console.error('callback call stop success '); + } }); ``` -### getRenderRate8+ +### stop9+ -getRenderRate(): Promise\ +stop(): Promise<void> -获取当前渲染速率。使用Promise方式异步返回结果。 +停止当前正在播放的音调。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Tone **返回值:** -| 类型 | 说明 | -| ------------------------------------------------- | ------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise回调返回渲染速率。 | +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -audioRenderer.getRenderRate().then((renderRate) => { - console.info(`getRenderRate: ${renderRate}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); }); ``` -### setInterruptMode9+ - -setInterruptMode(mode: InterruptMode): Promise<void> - -设置应用的焦点模型。使用Promise异步回调。 - -**系统能力:** SystemCapability.Multimedia.Audio.Renderer - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------------- | ------ | ---------- | -| mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<void> | 以Promise对象返回结果,设置成功时返回undefined,否则返回error。 | - -**示例:** -```js -let mode = 0; -audioRenderer.setInterruptMode(mode).then(data=>{ - console.info('setInterruptMode Success!'); -}).catch((err) => { - console.error(`setInterruptMode Fail: ${err}`); -}); -``` -### setInterruptMode9+ +### release9+ -setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void +release(callback: AsyncCallback<void>): void -设置应用的焦点模型。使用Callback回调返回执行结果。 +释放与此TonePlay对象关联的资源。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Tone **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ----------------------------------- | ------ | -------------- | -|mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。| -|callback | AsyncCallback\ | 是 |回调返回执行结果。| +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :---------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -let mode = 1; -audioRenderer.setInterruptMode(mode, (err, data)=>{ - if(err){ - console.error(`setInterruptMode Fail: ${err}`); +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); } - console.info('setInterruptMode Success!'); }); ``` -### on('interrupt')9+ -on(type: 'interrupt', callback: Callback\): void +### release9+ -监听音频中断事件。使用callback获取中断事件。 +release(): Promise<void> -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +释放与此TonePlay对象关联的资源。使用Promise方式异步返回结果。 -**参数:** +**系统能力:** SystemCapability.Multimedia.Audio.Tone -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'interrupt'(中断事件被触发,音频播放被中断。) | -| callback | Callback<[InterruptEvent](#interruptevent9)> | 是 | 被监听的中断事件的回调。 | +**返回值:** + +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -let isPlay; -let started; -audioRenderer.on('interrupt', async(interruptEvent) => { - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Force paused. Stop writing'); - isPlay = false; - break; - case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.info('Force stopped. Stop writing'); - isPlay = false; - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - console.info('Resume force paused renderer or ignore'); - await audioRenderer.start().then(async function () { - console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); - started = true; - }).catch((err) => { - console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); - started = false; - }); - if (started) { - isPlay = true; - console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); - } else { - console.error('AudioInterruptMusic Renderer start failed'); - } - break; - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Choose to pause or ignore'); - if (isPlay == true) { - isPlay == false; - console.info('AudioInterruptMusic: Media PAUSE : TRUE'); - } else { - isPlay = true; - console.info('AudioInterruptMusic: Media PLAY : TRUE'); - } - break; - } - } +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); }); ``` -### on('markReach')8+ +## ActiveDeviceType(deprecated) -on(type: "markReach", frame: number, callback: Callback<number>): void +枚举,活跃设备类型。 -订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用。 +> **说明:** +> 从 API version 9 开始废弃,建议使用[CommunicationDeviceType](#communicationdevicetype9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device -**参数:** +| 名称 | 默认值 | 描述 | +| ------------- | ------ | ---------------------------------------------------- | +| SPEAKER | 2 | 扬声器。 | +| BLUETOOTH_SCO | 7 | 蓝牙设备SCO(Synchronous Connection Oriented)连接。 | -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :----------------------- | :--- | :---------------------------------------- | -| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | -| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | -| callback | Callback\ | 是 | 触发事件时调用的回调。 | +## InterruptActionType(deprecated) -**示例:** +枚举,中断事件返回类型。 -```js -audioRenderer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } -}); -``` +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer -### off('markReach') 8+ +| 名称 | 默认值 | 描述 | +| -------------- | ------ | ------------------ | +| TYPE_ACTIVATED | 0 | 表示触发焦点事件。 | +| TYPE_INTERRUPT | 1 | 表示音频打断事件。 | -off(type: 'markReach'): void +## AudioInterrupt(deprecated) -取消订阅标记事件。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +音频监听事件传入的参数。 -**参数:** +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----- | :--- | :------------------------------------------------ | -| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'markReach'。 | +| 名称 | 类型 | 必填 | 说明 | +| --------------- | --------------------------- | ---- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | 是 | 音频流使用类型。 | +| contentType | [ContentType](#contenttype) | 是 | 音频打断媒体类型。 | +| pauseWhenDucked | boolean | 是 | 音频打断时是否可以暂停音频播放(true表示音频播放可以在音频打断期间暂停,false表示相反)。 | -**示例:** +## InterruptAction(deprecated) -```js -audioRenderer.off('markReach'); -``` +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 -### on('periodReach') 8+ +音频打断/获取焦点事件的回调方法。 -on(type: "periodReach", frame: number, callback: Callback<number>): void +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer + +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontype) | 是 | 事件返回类型。TYPE_ACTIVATED为焦点触发事件,TYPE_INTERRUPT为音频打断事件。 | +| type | [InterruptType](#interrupttype) | 否 | 打断事件类型。 | +| hint | [InterruptHint](#interrupthint) | 否 | 打断事件提示。 | +| activated | boolean | 否 | 获得/释放焦点。true表示焦点获取/释放成功,false表示焦点获得/释放失败。 | -订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被循环调用。 +### setVolume(deprecated) -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void + +设置指定流的音量,使用callback方式异步返回结果。 + +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setVolume](#setvolume9)替代。 + +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | -| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | -| callback | Callback\ | 是 | 触发事件时调用的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | +| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | **示例:** ```js -audioRenderer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { + if (err) { + console.error(`Failed to set the volume. ${err}`); + return; } + console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### off('periodReach') 8+ +### setVolume(deprecated) -off(type: 'periodReach'): void +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -取消订阅标记事件。 +设置指定流的音量,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setVolume](#setvolume9)替代。 + +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----- | :--- | :-------------------------------------------------- | -| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'periodReach'。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| volume | number | 是 | 音量等级,可设置范围通过getMinVolume和getMaxVolume获取。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise<void> | Promise回调表示成功还是失败。 | **示例:** ```js -audioRenderer.off('periodReach') +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); +}); ``` -### on('stateChange') 8+ +### getVolume(deprecated) -on(type: 'stateChange', callback: Callback): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -订阅监听状态变化。 +获取指定流的音量,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getVolume](#getvolume9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'stateChange'。 | -| callback | [AudioState](#audiostate8) | 是 | 返回监听的状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<number> | 是 | 回调返回音量大小。 | **示例:** ```js -audioRenderer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio renderer state is: STATE_RUNNING'); +audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the volume. ${err}`); + return; } + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -## AudioCapturer8+ +### getVolume(deprecated) -提供音频采集的相关接口。在调用AudioCapturer的接口前,需要先通过[createAudioCapturer](#audiocreateaudiocapturer8)创建实例。 +getVolume(volumeType: AudioVolumeType): Promise<number> -### 属性 +获取指定流的音量,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getVolume](#getvolume9)替代。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| :---- | :------------------------- | :--- | :--- | :--------------- | -| state8+ | [AudioState](#audiostate8) | 是 | 否 | 音频采集器状态。 | +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<number> | Promise回调返回音量大小。 | **示例:** ```js -let state = audioCapturer.state; +audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value} .`); +}); ``` -### getCapturerInfo8+ +### getMinVolume(deprecated) -getCapturerInfo(callback: AsyncCallback): void +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -获取采集器信息。使用callback方式异步返回结果。 +获取指定流的最小音量,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getMinVolume](#getminvolume9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :-------------------------------- | :--- | :----------------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回采集器信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<number> | 是 | 回调返回最小音量。 | **示例:** ```js -audioCapturer.getCapturerInfo((err, capturerInfo) => { +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to get capture info'); - } else { - console.info('Capturer getCapturerInfo:'); - console.info(`Capturer source: ${capturerInfo.source}`); - console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); + console.error(`Failed to obtain the minimum volume. ${err}`); + return; } + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` +### getMinVolume(deprecated) -### getCapturerInfo8+ +getMinVolume(volumeType: AudioVolumeType): Promise<number> -getCapturerInfo(): Promise +获取指定流的最小音量,使用Promise方式异步返回结果。 -获取采集器信息。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getMinVolume](#getminvolume9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| :------------------------------------------------ | :---------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | 使用Promise方式异步返回采集器信息。 | +| 类型 | 说明 | +| --------------------- | ------------------------- | +| Promise<number> | Promise回调返回最小音量。 | **示例:** ```js -audioCapturer.getCapturerInfo().then((audioParamsGet) => { - if (audioParamsGet != undefined) { - console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); - console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); - console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); - } else { - console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); - console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); - } -}).catch((err) => { - console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); }); ``` -### getStreamInfo8+ +### getMaxVolume(deprecated) -getStreamInfo(callback: AsyncCallback): void +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -获取采集器流信息。使用callback方式异步返回结果。 +获取指定流的最大音量,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getMaxVolume](#getmaxvolume9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------------------------------------- | :--- | :------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | 是 | 使用callback方式异步返回流信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<number> | 是 | 回调返回最大音量大小。 | **示例:** ```js -audioCapturer.getStreamInfo((err, streamInfo) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to get stream info'); - } else { - console.info('Capturer GetStreamInfo:'); - console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Capturer channel: ${streamInfo.channels}`); - console.info(`Capturer format: ${streamInfo.sampleFormat}`); - console.info(`Capturer encoding type: ${streamInfo.encodingType}`); + console.error(`Failed to obtain the maximum volume. ${err}`); + return; } + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getStreamInfo8+ +### getMaxVolume(deprecated) + +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -getStreamInfo(): Promise +获取指定流的最大音量,使用Promise方式异步返回结果。 -获取采集器流信息。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getMaxVolume](#getmaxvolume9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| :--------------------------------------------- | :------------------------------ | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | 使用Promise方式异步返回流信息。 | +| 类型 | 说明 | +| --------------------- | ----------------------------- | +| Promise<number> | Promise回调返回最大音量大小。 | **示例:** ```js -audioCapturer.getStreamInfo().then((audioParamsGet) => { - console.info('getStreamInfo:'); - console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); - console.info(`samplingRate: ${audioParamsGet.samplingRate}`); - console.info(`channels: ${audioParamsGet.channels}`); - console.info(`encodingType: ${audioParamsGet.encodingType}`); -}).catch((err) => { - console.error(`getStreamInfo :ERROR: ${err}`); +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### start8+ +### mute(deprecated) -start(callback: AsyncCallback): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -启动音频采集器。使用callback方式异步返回结果。 +设置指定音量流静音,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[mute](#mute9)替代。 + +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | +| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | **示例:** ```js -audioCapturer.start((err) => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { - console.error('Capturer start failed.'); - } else { - console.info('Capturer start success.'); + console.error(`Failed to mute the stream. ${err}`); + return; } + console.info('Callback invoked to indicate that the stream is muted.'); }); ``` +### mute(deprecated) -### start8+ +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -start(): Promise +设置指定音量流静音,使用Promise方式异步返回结果。 -启动音频采集器。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[mute](#mute9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | **返回值:** -| 类型 | 说明 | -| :------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +| 类型 | 说明 | +| ------------------- | ----------------------------- | +| Promise<void> | Promise回调表示成功还是失败。 | **示例:** + ```js -audioCapturer.start().then(() => { - console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); - } -}).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); +audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### stop8+ +### isMute(deprecated) -stop(callback: AsyncCallback): void +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -停止采集。使用callback方式异步返回结果。 +获取指定音量流是否被静音,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[isMute](#ismute9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回流静音状态,true为静音,false为非静音。 | **示例:** ```js -audioCapturer.stop((err) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Capturer stop failed'); - } else { - console.info('Capturer stopped.'); + console.error(`Failed to obtain the mute status. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` +### isMute(deprecated) -### stop8+ +isMute(volumeType: AudioVolumeType): Promise<boolean> -stop(): Promise +获取指定音量流是否被静音,使用Promise方式异步返回结果。 -停止采集。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[isMute](#ismute9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| :------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise回调返回流静音状态,true为静音,false为非静音。 | **示例:** ```js -audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info('AudioFrameworkRecLog: State is Stopped:'); - } -}).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); +audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### release8+ +### isActive(deprecated) -release(callback: AsyncCallback): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -释放采集器。使用callback方式异步返回结果。 +获取指定音量流是否为活跃状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioStreamManager中的[isActive](#isactive9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :---------------------------------- | -| callback | AsyncCallback | 是 | Callback used to return the result. | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回流的活跃状态,true为活跃,false为不活跃。 | **示例:** ```js -audioCapturer.release((err) => { +audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('capturer release failed'); - } else { - console.info('capturer released.'); + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` +### isActive(deprecated) -### release8+ +isActive(volumeType: AudioVolumeType): Promise<boolean> -release(): Promise +获取指定音量流是否为活跃状态,使用Promise方式异步返回结果。 -释放采集器。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioStreamManager中的[isActive](#isactive9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Volume + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| :------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +| 类型 | 说明 | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise回调返回流的活跃状态,true为活跃,false为不活跃。 | **示例:** ```js -let stateFlag; -audioCapturer.release().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); - console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); -}).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); +audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); ``` +### setRingerMode(deprecated) -### read8+ +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void +设置铃声模式,使用callback方式异步返回结果。 -读入缓冲区。使用callback方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setRingerMode](#setringermode9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅在静音和非静音状态切换时需要该权限。 + +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------------- | :-------------------------- | :--- | :------------------------------- | -| size | number | 是 | 读入的字节数。 | -| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | -| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | **示例:** ```js -let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); - }); -audioCapturer.read(bufferSize, true, async(err, buffer) => { - if (!err) { - console.info('Success in reading the buffer data'); +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { + if (err) { + console.error(`Failed to set the ringer mode.​ ${err}`); + return; } + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` +### setRingerMode(deprecated) -### read8+ +setRingerMode(mode: AudioRingMode): Promise<void> -read(size: number, isBlockingRead: boolean): Promise +设置铃声模式,使用Promise方式异步返回结果。 -读入缓冲区。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setRingerMode](#setringermode9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅在静音和非静音状态切换时需要该权限。 + +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------------- | :------ | :--- | :--------------- | -| size | number | 是 | 读入的字节数。 | -| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :----------------------------------------------------- | -| Promise | 如果操作成功,返回读取的缓冲区数据;否则返回错误代码。 | +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | **示例:** ```js -let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('buffer read successfully'); -}).catch((err) => { - console.info(`ERROR : ${err}`); +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); }); ``` +### getRingerMode(deprecated) -### getAudioTime8+ +getRingerMode(callback: AsyncCallback<AudioRingMode>): void -getAudioTime(callback: AsyncCallback): void +获取铃声模式,使用callback方式异步返回结果。 -获取时间戳(从1970年1月1日开始),单位为纳秒。使用callback方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getRingerMode](#getringermode9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Communication **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | 是 | 回调返回系统的铃声模式。 | **示例:** ```js -audioCapturer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); +audioManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; + } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` +### getRingerMode(deprecated) -### getAudioTime8+ +getRingerMode(): Promise<AudioRingMode> -getAudioTime(): Promise +获取铃声模式,使用Promise方式异步返回结果。 -获取时间戳(从1970年1月1日开始),单位为纳秒。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getRingerMode](#getringermode9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Communication **返回值:** -| 类型 | 说明 | -| :--------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +| 类型 | 说明 | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise回调返回系统的铃声模式。 | **示例:** ```js -audioCapturer.getAudioTime().then((audioTime) => { - console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); -}).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); +audioManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` +### getDevices(deprecated) -### getBufferSize8+ +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -getBufferSize(callback: AsyncCallback): void +获取音频设备列表,使用callback方式异步返回结果。 -获取采集器合理的最小缓冲区大小。使用callback方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[getDevices](#getdevices9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :--- | :----------------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区大小。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回设备列表。 | **示例:** - ```js -audioCapturer.getBufferSize((err, bufferSize) => { - if (!err) { - console.info(`BufferSize : ${bufferSize}`); - audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`Buffer read is ${buffer}`); - }).catch((err) => { - console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); - }); +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { + if (err) { + console.error(`Failed to obtain the device list. ${err}`); + return; } + console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` +### getDevices(deprecated) -### getBufferSize8+ +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -getBufferSize(): Promise +获取音频设备列表,使用Promise方式异步返回结果。 -获取采集器合理的最小缓冲区大小。使用Promise方式异步返回结果。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[getDevices](#getdevices9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | **返回值:** -| 类型 | 说明 | -| :--------------- | :---------------------------------- | -| Promise | 使用Promise方式异步返回缓冲区大小。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise回调返回设备列表。 | **示例:** ```js -let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); ``` +### setDeviceActive(deprecated) -### on('markReach')8+ +setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void -on(type: "markReach", frame: number, callback: Callback<number>): void +设置设备激活状态,使用callback方式异步返回结果。 -订阅标记到达的事件。 当采集的帧数达到 frame 参数的值时,回调被触发。 +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[setCommunicationDevice](#setcommunicationdevice9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :---------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | -| frame | number | 是 | 触发事件的帧数。 该值必须大于0。 | -| callback | Callback\ | 是 | 使用callback方式异步返回被触发事件的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | +| active | boolean | 是 | 设备激活状态。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | **示例:** ```js -audioCapturer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { + if (err) { + console.error(`Failed to set the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### off('markReach')8+ +### setDeviceActive(deprecated) -off(type: 'markReach'): void +setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> -取消订阅标记到达的事件。 +设置设备激活状态,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[setCommunicationDevice](#setcommunicationdevice9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----- | :--- | :-------------------------------------------- | -| type | string | 是 | 取消事件回调类型,支持的事件为:'markReach'。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | +| active | boolean | 是 | 设备激活状态。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | **示例:** + ```js -audioCapturer.off('markReach'); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); +}); ``` -### on('periodReach')8+ +### isDeviceActive(deprecated) -on(type: "periodReach", frame: number, callback: Callback<number>): void +isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void -订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,回调被循环调用。 +获取指定设备的激活状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[isCommunicationDeviceActive](#iscommunicationdeviceactive9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | -| frame | number | 是 | 触发事件的帧数。 该值必须大于0。 | -| callback | Callback\ | 是 | 使用callback方式异步返回被触发事件的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回设备的激活状态。 | **示例:** ```js -audioCapturer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { + if (err) { + console.error(`Failed to obtain the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### off('periodReach')8+ +### isDeviceActive(deprecated) -off(type: 'periodReach'): void +isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> -取消订阅标记到达的事件。 +获取指定设备的激活状态,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[isCommunicationDeviceActive](#iscommunicationdeviceactive9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----- | :--- | :---------------------------------------------- | -| type | string | 是 | 取消事件回调类型,支持的事件为:'periodReach'。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | 是 | 活跃音频设备类型。 | + +**返回值:** + +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise回调返回设备的激活状态。 | **示例:** ```js -audioCapturer.off('periodReach') +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); +}); ``` -### on('stateChange') 8+ +### setMicrophoneMute(deprecated) -on(type: 'stateChange', callback: Callback): void +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -订阅监听状态变化。 +设置麦克风静音状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setMicrophoneMute](#setmicrophonemute9)替代。 + +**需要权限:** ohos.permission.MICROPHONE + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'stateChange'。 | -| callback | [AudioState](#audiostate8) | 是 | 返回监听的状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | 是 | 待设置的静音状态,true为静音,false为非静音。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | **示例:** ```js -audioCapturer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio capturer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio capturer state is: STATE_RUNNING'); +audioManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; } + console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -## ToneType 9+ +### setMicrophoneMute(deprecated) -枚举,播放器的音调类型。 +setMicrophoneMute(mute: boolean): Promise<void> + +设置麦克风静音状态,使用Promise方式异步返回结果。 + +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setMicrophoneMute](#setmicrophonemute9)替代。 + +**需要权限:** ohos.permission.MICROPHONE + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | 是 | 待设置的静音状态,true为静音,false为非静音。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Tone +**示例:** -| 名称 | 默认值 | 描述 | -| :------------------------------------------------ | :----- | :----------------------------| -| TONE_TYPE_DIAL_0 | 0 | 键0的DTMF音。 | -| TONE_TYPE_DIAL_1 | 1 | 键1的DTMF音。 | -| TONE_TYPE_DIAL_2 | 2 | 键2的DTMF音。 | -| TONE_TYPE_DIAL_3 | 3 | 键3的DTMF音。 | -| TONE_TYPE_DIAL_4 | 4 | 键4的DTMF音。 | -| TONE_TYPE_DIAL_5 | 5 | 键5的DTMF音。 | -| TONE_TYPE_DIAL_6 | 6 | 键6的DTMF音。 | -| TONE_TYPE_DIAL_7 | 7 | 键7的DTMF音。 | -| TONE_TYPE_DIAL_8 | 8 | 键8的DTMF音。 | -| TONE_TYPE_DIAL_9 | 9 | 键9的DTMF音。 | -| TONE_TYPE_DIAL_S | 10 | 键*的DTMF音。 | -| TONE_TYPE_DIAL_P | 11 | 键#的DTMF音。 | -| TONE_TYPE_DIAL_A | 12 | 键A的DTMF音。 | -| TONE_TYPE_DIAL_B | 13 | 键B的DTMF音。 | -| TONE_TYPE_DIAL_C | 14 | 键C的DTMF音。 | -| TONE_TYPE_DIAL_D | 15 | 键D的DTMF音。 | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | 呼叫监管音调,拨号音。 | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | 呼叫监管音调,忙。 | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | 呼叫监管音调,拥塞。 | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | 呼叫监管音调,无线电 ACK。 | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | 呼叫监管音调,无线电不可用。 | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | 呼叫监管音调,呼叫等待。 | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | 呼叫监管音调,铃声。 | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | 专有声调,一般蜂鸣声。 | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | 专有声调,ACK。 | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | 专有声调,PROMPT。 | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | 专有声调,双重蜂鸣声。 | +```js +audioManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); +}); +``` -## TonePlayer9+ +### isMicrophoneMute(deprecated) -提供播放和管理DTMF(Dual Tone Multi Frequency,双音多频)音调的方法,包括各种系统监听音调、专有音调,如拨号音、通话回铃音等。 +isMicrophoneMute(callback: AsyncCallback<boolean>): void -### load9+ +获取麦克风静音状态,使用callback方式异步返回结果。 -load(type: ToneType, callback: AsyncCallback<void>): void +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[isMicrophoneMute](#ismicrophonemute9)替代。 -加载DTMF音调配置。使用callback方式异步返回结果。 +**需要权限:** ohos.permission.MICROPHONE -**系统能力:** SystemCapability.Multimedia.Audio.Tone +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :--------------| :-------------------------- | :-----| :------------------------------ | -| type | ToneType(#tonetype9) | 是 | 配置的音调类型。 | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | 是 | 回调返回系统麦克风静音状态,true为静音,false为非静音。 | **示例:** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { +audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error(`callback call load failed error: ${err.message}`); + console.error(`Failed to obtain the mute status of the microphone. ${err}`); return; - } else { - console.info('callback call load success'); } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### load9+ +### isMicrophoneMute(deprecated) -load(type: ToneType): Promise<void> +isMicrophoneMute(): Promise<boolean> -加载DTMF音调配置。使用Promise方式异步返回结果。 +获取麦克风静音状态,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[isMicrophoneMute](#ismicrophonemute9)替代。 -**参数:** +**需要权限:** ohos.permission.MICROPHONE -| 参数名 | 类型 | 必填 | 说明 | -| :------------- | :--------------------- | :--- | ---------------- | -| type | ToneType(#tonetype9) | 是 | 配置的音调类型。 | +**系统能力:** SystemCapability.Multimedia.Audio.Device **返回值:** -| 类型 | 说明 | -| :--------------| :-------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise回调返回系统麦克风静音状态,true为静音,false为非静音。 | **示例:** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { - console.info('promise call load '); -}).catch(() => { - console.error('promise call load fail'); +audioManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### start9+ +### on('volumeChange')(deprecated) -start(callback: AsyncCallback<void>): void +on(type: 'volumeChange', callback: Callback\): void -启动DTMF音调播放。使用callback方式异步返回结果。 +> **说明:** +> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeManager中的[on](#on9)替代。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +监听系统音量变化事件。 + +**系统接口:** 该接口为系统接口 + +目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'volumeChange'(系统音量变化事件,检测到系统音量改变时,触发该事件)。 | +| callback | Callback<[VolumeEvent](#volumeevent8)> | 是 | 回调方法。 | **示例:** ```js -tonePlayer.start((err) => { - if (err) { - console.error(`callback call start failed error: ${err.message}`); - return; - } else { - console.info('callback call start success'); - } +audioManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### start9+ +### on('ringerModeChange')(deprecated) -start(): Promise<void> +on(type: 'ringerModeChange', callback: Callback\): void -启动DTMF音调播放。使用Promise方式异步返回结果。 +监听铃声模式变化事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +> **说明:** +> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[on('ringerModeChange')](#onringermodechange9)替代。 -**返回值:** +**系统接口:** 该接口为系统接口 -| 类型 | 说明 | -| :------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +**系统能力:** SystemCapability.Multimedia.Audio.Communication + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。 | +| callback | Callback<[AudioRingMode](#audioringmode)> | 是 | 回调方法。 | **示例:** ```js -tonePlayer.start().then(() => { - console.info('promise call start'); -}).catch(() => { - console.error('promise call start fail'); +audioManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); }); ``` -### stop9+ +### on('deviceChange')(deprecated) -stop(callback: AsyncCallback<void>): void +on(type: 'deviceChange', callback: Callback): void -停止当前正在播放的音调。使用callback方式异步返回结果。 +设备更改。音频设备连接状态变化。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[on](#on9)替代。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | **示例:** ```js -tonePlayer.stop((err) => { - if (err) { - console.error(`callback call stop error: ${err.message}`); - return; - } else { - console.error('callback call stop success '); - } +audioManager.on('deviceChange', (deviceChanged) => { + console.info(`device change type : ${deviceChanged.type} `); + console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); }); ``` -### stop9+ +### off('deviceChange')(deprecated) -stop(): Promise<void> +off(type: 'deviceChange', callback?: Callback): void -停止当前正在播放的音调。使用Promise方式异步返回结果。 +取消订阅音频设备连接变化事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的[off](#off9)替代。 -**返回值:** +**系统能力:** SystemCapability.Multimedia.Audio.Device -| 类型 | 说明 | -| :------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 | **示例:** ```js -tonePlayer.stop().then(() => { - console.info('promise call stop finish'); -}).catch(() => { - console.error('promise call stop fail'); +audioManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); ``` -### release9+ +### on('interrupt')(deprecated) -release(callback: AsyncCallback<void>): void +on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void -释放与此TonePlay对象关联的资源。使用callback方式异步返回结果。 +请求焦点并开始监听音频打断事件(当应用程序的音频被另一个播放事件中断,回调通知此应用程序)。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +与[on('audioInterrupt')](#onaudiointerrupt9)作用一致,均用于监听焦点变化。为无音频流的场景(未曾创建AudioRenderer对象),比如FM、语音唤醒等提供焦点变化监听功能。 + +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :---------------------------- | -| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。 | +| interrupt | AudioInterrupt | 是 | 音频打断事件类型的参数。 | +| callback | Callback<[InterruptAction](#interruptaction)> | 是 | 音频打断事件回调方法。 | **示例:** ```js -tonePlayer.release((err) => { - if (err) { - console.error(`callback call release failed error: ${err.message}`); - return; - } else { - console.info('callback call release success '); +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to gain the audio focus starts.'); + console.info(`Focus gain event: ${InterruptAction} `); + } + if (InterruptAction.actionType === 1) { + console.info('An audio interruption event starts.'); + console.info(`Audio interruption event: ${InterruptAction} `); } }); ``` -### release9+ +### off('interrupt')(deprecated) -release(): Promise<void> +off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void -释放与此TonePlay对象关联的资源。使用Promise方式异步返回结果。 +取消监听音频打断事件(删除监听事件,取消打断)。 -**系统能力:** SystemCapability.Multimedia.Audio.Tone +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 -**返回值:** +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -| 类型 | 说明 | -| :------------- | :---------------------------- | -| Promise | 使用Promise方式异步返回结果。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。 | +| interrupt | AudioInterrupt | 是 | 音频打断事件类型的参数。 | +| callback | Callback<[InterruptAction](#interruptaction)> | 否 | 音频打断事件回调方法。 | **示例:** ```js -tonePlayer.release().then(() => { - console.info('promise call release'); -}).catch(() => { - console.error('promise call release fail'); +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to release the audio focus starts.'); + console.info(`Focus release event: ${InterruptAction} `); + } }); ``` 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 3a9f20cfc972f309de9fe12ff12557fa4e969b97..72bcc598e6f967702b6d9a473096bbfcfde5a593 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,15 +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; @@ -57,7 +55,9 @@ bundle.getBundleInstaller().then(installer=>{ }); ``` -## BundleInstaller.uninstall +## BundleInstaller.uninstall(deprecated) + +> 从API version 9开始不再维护,建议使用[uninstall](js-apis-installer.md)替代。 uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -104,7 +104,9 @@ bundle.getBundleInstaller().then(installer=>{ console.error('getBundleInstaller failed. Cause: ' + error.message); }); ``` -## BundleInstaller.recover8+ +## BundleInstaller.recover(deprecated) + +> 从API version 9开始不再维护,建议使用[recover](js-apis-installer.md)替代。 recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -153,20 +155,7 @@ bundle.getBundleInstaller().then(installer=>{ }); ``` -## HashParam9+ - -hap的哈希值参数。应用市场升级检测时,校验各版本哈希值是否一致。 - - **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - - **系统API:** 此接口为系统接口,三方应用不支持调用 - -| 名称 | 类型 | 可读|可写|说明 | -| ---------- | ------ | ---|---|---------------- | -| moduleName | string | 是|是 | 应用程序模块名称 | -| hashValue | string | 是|是 |hap包的sha256哈希值 | - -## InstallParam +## InstallParam(deprecated) 应用程序安装卸载信息 @@ -179,10 +168,9 @@ hap的哈希值参数。应用市场升级检测时,校验各版本哈希值 | userId | number | 是|是 |指示用户id,可以通过[账户子系统](js-apis-) | | installFlag | number | 是|是 |指示安装标志
0表示正常安装
1表示替代原有应用 | | isKeepData | boolean | 是|是 |指示应用删除后是否保留数据 | -| hashParams9+ | Array<[HashParam](#hashparam)> | 是|是 |哈希值参数 | -| crowdtestDeadline9+ | number | 是|是 |[众测](https://deveco.huawei.com/crowdtest)截止时间 | -## 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 c0571f3be7235215f5e0954fddc53b50c4c838d3..597753bb212ea897a8063ec36fc056d49e099794 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..099aef27744134e2adb0f69138f9b3a5caad5c44 --- /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 appsFlag = 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, userId); + 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..a53646225fcd2b3cf347b92e9dc42e78486e5d64 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -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-commonEvent.md b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md index bbde4a3e4780e0b2095107ed51474b0ff7a52210..88e95d6c483b03279b6e3ceeb67f2007c11611e9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,6 +1,6 @@ # 公共事件模块 -本模块提供了公共事件的能力,包括公共事件的权限列表,发布公共事件,订阅或取消订阅公共事件,获取或修改公共事件结果代码、结果数据等。 +本模块提供了公共事件的能力,包括公共事件的权限列表,发布公共事件,订阅或取消订阅公共事件,获取或修改公共事件结果代码、结果数据等。本模块将被commonEventManager模块取代,建议优先使用[commonEventManager](js-apis-commonEventManager.md)模块。 > **说明:** > @@ -1237,6 +1237,8 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventData +公共事件数据体。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -1250,6 +1252,8 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventPublishData +公共事件发送的数据体,包含公共事件内容和属性。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -1264,6 +1268,8 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventSubscribeInfo +订阅者信息。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent | 名称 | 可读 | 可写 | 类型 | 描述 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md new file mode 100644 index 0000000000000000000000000000000000000000..94f5a3e6aeff0f6822182a0962dc11d7b1e3b8a0 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @@ -0,0 +1,1420 @@ +# 公共事件模块 + +本模块提供了公共事件的能力,包括公共事件的权限列表,发布公共事件,订阅或取消订阅公共事件,获取或修改公共事件结果代码、结果数据等。本模块将会取代[commonEvent](js-apis-commonEvent.md)模块,建议优先使用本模块。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +import CommonEventManager from '@ohos.commonEventManager'; +``` + +## Support + +CommonEventManager模块支持的事件类型。名称指的是系统公共事件宏;值指的是系统公共事件。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +| 名称 | 值 | 订阅者所需权限 | 说明 | +| ------------ | ------------------ | ---------------------- | -------------------- | +| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示用户已完成引导并加载系统的公共事件的操作。 | +| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示用户已完成引导,系统已加载,但屏幕仍锁定的公共事件的操作。 | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | 无 | 表示设备正在关闭并将继续最终关闭的公共事件的操作。 | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | 无 | 表示电池充电状态、电平和其他信息发生变化的公共事件的动作。 | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | 无 | 表示电池电量低的普通事件的动作。 | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | 无 | 表示电池退出低电平状态的公共事件的动作。 | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | 无 | 设备连接到外部电源的公共事件的动作。 | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | 无 | 设备与外部电源断开的公共事件的动作。 | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | 无 | 表示设备屏幕关闭且设备处于睡眠状态的普通事件的动作。 | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | 无 | 表示设备屏幕打开且设备处于交互状态的公共事件的操作。 | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ | usual.event.THERMAL_LEVEL_CHANGED | 无 | 表示设备热状态的公共事件的动作。 | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | 无 | 用户解锁设备的公共事件的动作。 | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | 无 | 表示系统时间更改的公共事件的动作。 | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | 无 | 设置系统时间的公共事件的动作。 | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | 无 | 表示系统日期已更改的公共事件的动作。 | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | 无 | 表示系统时区更改的公共事件的动作。 | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | 无 | 表示用户关闭临时系统对话框的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | 无 | 设备上已安装新应用包的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | 无 | 表示已安装的应用程序包的新版本已替换设备上的旧版本的公共事件的操作。 | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | 无 | 表示应用程序包的新版本已取代前一个版本的公共事件的操作。 +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | 无 | 表示已从设备卸载已安装的应用程序,但应用程序数据保留的公共事件的操作。 | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | 无 | 表示已从设备中卸载已安装的捆绑包,但应用程序数据仍保留的公共事件的操作。 | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | 无 | 表示已从设备中完全卸载已安装的应用程序(包括应用程序数据和代码)的公共事件的操作。 | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | 无 | 表示应用包已更改的公共事件的动作(例如,包中的组件已启用或禁用)。 | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | 无 | 表示用户重启应用包并杀死其所有进程的普通事件的动作。 | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | 无 | 用户清除应用包数据的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | 无 | 用户清除应用包缓存数据的公共事件的动作。 | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | 无 | 表示应用包已挂起的公共事件的动作。 | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | 无 | 表示应用包未挂起的公共事件的动作。 | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | 无 | 应用包被挂起的公共事件的动作。 | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | 无 | 表示应用包未挂起的公共事件的动作。 | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | 无 | 表示用户ID已从系统中删除的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | 无 | 表示首次启动已安装应用程序的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | 无 | 表示应用需要系统校验的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | 无 | 表示应用已被系统校验的公共事件的动作。 | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | 无 | 表示安装在外部存储上的应用程序对系统可用的公共事件的操作。 | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | 无 | 表示安装在外部存储上的应用程序对系统不可用的公共事件的操作。 | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | 无 | 表示设备状态(例如,方向和区域设置)已更改的公共事件的操作。 | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | 无 | 表示设备区域设置已更改的公共事件的操作。 | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | 无 | 设备存储空间不足的公共事件的动作。 | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | 无 | 表示系统处于驾驶模式的公共事件的动作。 | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | 无 | 表示系统处于HOME模式的公共事件的动作。 | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | 无 | 表示系统处于办公模式的公共事件的动作。 | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | 无 | 表示用户已启动的公共事件的动作。 | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | 无 | 表示用户已被带到后台的公共事件的动作。 | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | 无 | 表示用户已被带到前台的公共事件的动作。 | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | 表示用户切换正在发生的公共事件的动作。 | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 表示要启动用户的公共事件的动作。 | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | 无 | 设备重启后解锁时,当前用户的凭据加密存储已解锁的公共事件的动作。 | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 表示要停止用户的公共事件的动作。 | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | 无 | 表示用户已停止的公共事件的动作。 | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | 无 | Wi-Fi状态公共事件的动作,如启用和禁用。 | +| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | 表示Wi-Fi接入点已被扫描并证明可用的公共事件的操作。 | +| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | 表示Wi-Fi信号强度(RSSI)改变的公共事件的动作。 | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | 无 | Wi-Fi连接状态发生改变的公共事件的动作。 | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | 无 | Wi-Fi热点状态的公共事件的动作,如启用或禁用。 | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | 客户端加入当前设备Wi-Fi热点的普通事件的动作。 | +| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |客户端已断开与当前设备Wi-Fi热点的连接的公共事件的动作。 | +| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | 表示MPLink(增强Wi-Fi功能)状态已更改的公共事件的动作。 | +| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Wi-Fi P2P连接状态改变的公共事件的动作。 | +| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P状态公共事件的动作,如启用和禁用。 | +| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P对等体状态变化。 | +| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P发现状态变化。 | +| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P当前设备状态变化。 | +| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P群组信息已更改。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙免提通信连接状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示连接到蓝牙免提的设备处于活动状态的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙A2DP连接状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示使用蓝牙A2DP连接的设备处于活动状态的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙A2DP播放状态改变的普通事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP的AVRCP连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP音频编解码状态更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | 表示发现远程蓝牙设备的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示远程蓝牙设备的蓝牙类别已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | 表示已与远程蓝牙设备建立低级别(ACL)连接的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | 表示低电平(ACL)连接已从远程蓝牙设备断开的普通事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | 表示远程蓝牙设备的友好名称首次被检索或自上次检索以来被更改的公共事件的操作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | 远程蓝牙设备连接状态更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示远程蓝牙设备的电池电量首次被检索或自上次检索以来被更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | 无 | 远程蓝牙设备SDP状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | 远程蓝牙设备UUID连接状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | 表示远程蓝牙设备配对请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | 无 | 取消蓝牙配对的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | 无 | 表示远程蓝牙设备连接请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | 无 | 表示远程蓝牙设备连接请求响应的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | 无 | 表示取消与远程蓝牙设备的连接的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | 无 | 表示蓝牙免提连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | 无 | 表示蓝牙免提音频状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | 无 | 表示蓝牙免提音频网关状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | 无 | 表示蓝牙免提呼叫状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙适配器状态已更改的公共事件的操作,例如蓝牙已打开或关闭。 | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | 无 | 表示用户允许扫描蓝牙请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | 表示用户打开蓝牙请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | 表示用户关闭蓝牙请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | 设备蓝牙扫描模式更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | 设备上已启动蓝牙扫描的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | 设备上蓝牙扫描完成的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | 表示设备蓝牙适配器名称已更改的公共事件的操作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP宿连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙A2DP宿播放状态改变的普通事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP宿的音频状态已更改的公共事件的动作。 | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | 无 | 表示设备NFC适配器状态已更改的公共事件的操作。 | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | 检测到NFC RF字段处于使能状态的公共事件的动作。 | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | 检测到NFC RF字段处于关闭状态的公共事件的动作。 | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | 无 | 表示系统停止为电池充电的公共事件的动作。 | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | 无 | 表示系统开始为电池充电的公共事件的动作。 | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | 无 | 表示系统空闲模式已更改的公共事件的动作。 | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | 无 | 表示系统节能模式更改的公共事件的动作。 | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | 表示用户已添加到系统中的公共事件的动作。 | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | 表示用户已从系统中删除的公共事件的动作。 | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | 表示已添加能力的公共事件的动作。 | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | 表示已删除能力的公共事件的动作。 | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | 表示能力已更新的公共事件的动作。 | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | 无 | 表示系统定位模式已更改的公共事件的动作。 | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | 无 | 表示表示车辆的车载信息娱乐(IVI)系统正在休眠的常见事件的动作。 | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | 无 | 表示IVI已休眠,并通知应用程序停止播放。 | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | 无 | 表示第三方应用暂停当前工作的公共事件的动作。 | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | 无 | 表示第三方应用保存其最后一个模式的公共事件的动作。 | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | 无 | 表示车辆电源系统电压异常的公共事件的动作。 | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | 无 | 表示IVI温度过高。 | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | 无 | 表示IVI温度极高。 | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | 无 | 表示车载系统具有极端温度的常见事件的动作。 | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | 无 | 表示车辆电源系统电压恢复正常的公共事件的动作。 | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | 无 | 表示车载系统温度恢复正常的公共事件的动作。 | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | 无 | 表示电池服务处于活动状态的公共事件的动作。 | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | 无 | 表示USB设备状态发生变化的公共事件。 | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | 无 | 表示用户设备的USB端口状态发生改变的公共事件。 | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | 无 | 当用户设备作为USB主机时,USB设备已挂载的公共事件的动作。 | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | 无 | 当用户设备作为USB主机时,USB设备被卸载的公共事件的动作。 | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | 无 | 表示已连接USB附件的公共事件的动作。 | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | 无 | 表示USB附件被卸载的公共事件的动作。 | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为移除时发送此公共事件。 | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为卸载时发送此公共事件。 | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载时发送此公共事件。 | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为插卡情况下无法挂载时发送此公共事件。 | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | 用户已表示希望删除外部存储介质时发送此公共事件。 | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为移除时发送此公共事件。 | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为卸载时发送此公共事件。 | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载时发送此公共事件。 | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | 用户已表示希望删除外部存储介质时发送此公共事件。 | +| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | 表示帐户可见更改的公共事件的动作。 | +| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 删除帐户的公共事件的动作。 | +| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示foundation已准备好的公共事件的动作。 | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | 无 | 表示设备飞行模式已更改的公共事件的动作。 | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | 表示分屏的公共事件的动作。 | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | 表示通知通道更新的动作。 | +| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | 无 | 表示spn显示信息已更新的公共事件的动作。 | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | 无 | 表示快速修复应用的动作。 | + + +## CommonEventManager.publish + +publish(event: string, callback: AsyncCallback\): void + +发布公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------- | +| event | string | 是 | 表示要发送的公共事件。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +以下错误码详细介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errcode-CommonEventService.md) + +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +//发布公共事件回调 +function PublishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +//发布公共事件 +try { + CommonEventManager.publish("event", PublishCallBack); +} catch(err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + +## CommonEventManager.publish + +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void + +发布公共事件指定发布信息(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | 是 | 表示要发布的公共事件。 | +| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| callback | syncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + + +```ts +//公共事件相关信息 +var options = { + code: 0, //公共事件的初始代码 + data: "initial data",//公共事件的初始数据 + isOrdered: true //有序公共事件 +} + +//发布公共事件回调 +function PublishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +//发布公共事件 +try { + CommonEventManager.publish("event", options, PublishCallBack); +} catch (err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, callback: AsyncCallback\): void + +向指定用户发布公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------------------- | +| event | string | 是 | 表示要发送的公共事件。 | +| userId | number | 是 | 表示指定向该用户ID发送此公共事件。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +//发布公共事件回调 +function PublishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +//指定发送的用户 +var userId = 100; + +//发布公共事件 +try { + CommonEventManager.publishAsUser("event", userId, PublishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void + +向指定用户发布公共事件并指定发布信息(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | 是 | 表示要发布的公共事件。 | +| userId | number | 是 | 表示指定向该用户ID发送此公共事件。 | +| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + + +```ts +//公共事件相关信息 +var options = { + code: 0, //公共事件的初始代码 + data: "initial data",//公共事件的初始数据 +} + +//发布公共事件回调 +function PublishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +//指定发送的用户 +var userId = 100; + +//发布公共事件 +try { + CommonEventManager.publishAsUser("event", userId, options, PublishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void + +创建订阅者(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | 是 | 表示订阅信息。 | +| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | 是 | 表示创建订阅者的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + + +```ts +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 + +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; + +//创建订阅者回调 +function CreateSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ + +创建订阅者(Promise形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------- | ----------------------------------------------------- | ---- | -------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | 是 | 表示订阅信息。 | + +**返回值:** +| 类型 | 说明 | +| --------------------------------------------------------- | ---------------- | +| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | 返回订阅者对象。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 + +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; + +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; +}).catch((err) => { + console.error("createSubscriber failed " + JSON.stringify(err)); +}); +} catch(err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} + +``` + + + +## CommonEventManager.subscribe + +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void + +订阅公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | 是 | 表示订阅者对象。 | +| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | 是 | 表示接收公共事件数据的回调函数。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +//订阅者信息 +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 + +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; + +//订阅公共事件回调 +function SubscribeCallBack(err, data) { + if (err.code) { + console.error("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe "); + } +} + +//创建订阅者回调 +function CreateSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + //订阅公共事件 + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch (err) { + console.error("createSubscriber failed " + JSON.stringify(err)); + } + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.unsubscribe + +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void + +取消订阅公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | 是 | 表示订阅者对象。 | +| callback | AsyncCallback\ | 否 | 表示取消订阅的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; +//订阅公共事件回调 +function SubscribeCallBack(err, data) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe"); + } +} +//创建订阅者回调 +function CreateSubscriberCallBack(err, commonEventSubscriber) { + if (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); + } else { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + //订阅公共事件 + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch(err) { + console.info("subscribe failed " + JSON.stringify(err)); + } + } +} +//取消订阅公共事件回调 +function UnsubscribeCallBack(err) { + if (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe"); + } +} +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +} catch (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); +} + +//取消订阅公共事件 +try { + CommonEventManager.unsubscribe(subscriber, UnsubscribeCallBack); +} catch (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); +} +``` + +## CommonEventSubscriber + +### getCode + +getCode(callback: AsyncCallback\): void + +获取公共事件的结果代码(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | 是 | 公共事件的结果代码。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取有序公共事件的结果代码回调 +function getCodeCallback(err, Code) { + if (err.code) { + console.error("getCode failed " + JSON.stringify(err)); + } else { + console.info("getCode " + JSON.stringify(Code)); + } +} +subscriber.getCode(getCodeCallback); +``` + +### getCode + +getCode(): Promise\ + +获取公共事件的结果代码(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 公共事件的结果代码。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getCode().then((Code) => { + console.info("getCode " + JSON.stringify(Code)); +}).catch((err) => { + console.error("getCode failed " + JSON.stringify(err)); +}); +``` + +### setCode + +setCode(code: number, callback: AsyncCallback\): void + +设置公共事件的结果代码(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | 是 | 公共事件的结果代码。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果代码回调 +function setCodeCallback(err) { + if (err.code) { + console.error("setCode failed " + JSON.stringify(err)); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCallback); +``` + +### setCode + +setCode(code: number): Promise\ + +设置公共事件的结果代码(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | ------------------ | +| code | number | 是 | 公共事件的结果代码。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error("setCode failed " + JSON.stringify(err)); +}); +``` + +### getData + +getData(callback: AsyncCallback\): void + +获取公共事件的结果数据(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 公共事件的结果数据。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取有序公共事件的结果数据回调 +function getDataCallback(err, Data) { + if (err.code) { + console.error("getData failed " + JSON.stringify(err)); + } else { + console.info("getData " + JSON.stringify(Data)); + } +} +subscriber.getData(getDataCallback); +``` + +### getData + +getData(): Promise\ + +获取公共事件的结果数据(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------ | +| Promise\ | 公共事件的结果数据。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getData().then((Data) => { + console.info("getData " + JSON.stringify(Data)); +}).catch((err) => { + console.error("getData failed " + JSON.stringify(err)); +}); +``` + +### setData + +setData(data: string, callback: AsyncCallback\): void + +设置公共事件的结果数据(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------- | +| data | string | 是 | 公共事件的结果数据。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果数据回调 +function setDataCallback(err) { + if (err.code) { + console.error("setData failed " + JSON.stringify(err)); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCallback); +``` + +### setData + +setData(data: string): Promise\ + +设置公共事件的结果数据(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | -------------------- | +| data | string | 是 | 公共事件的结果数据。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error("setData failed " + JSON.stringify(err)); +}); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string, callback:AsyncCallback\): void + +设置公共事件的结果代码和结果数据(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | 是 | 公共事件的结果代码。 | +| data | string | 是 | 公共事件的结果数据。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果代码和结果数据回调 +function setCodeDataCallback(err) { + if (err.code) { + console.error("setCodeAndData failed " + JSON.stringify(err)); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string): Promise\ + +设置公共事件的结果代码和结果数据(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | -------------------- | +| code | number | 是 | 公共事件的结果代码。 | +| data | string | 是 | 公共事件的结果数据。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.info("setCodeAndData failed " + JSON.stringify(err)); +}); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(callback: AsyncCallback\): void + +查询当前公共事件的是否为有序公共事件(callback形式)。 + +返回true代表是有序公共事件,false代表不是有序公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 当前公共事件的是否为有序公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取当前公共事件是否为有序事件的回调 +function isOrderedCallback(err, isOrdered) { + if (err.code) { + console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCallback); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(): Promise\ + +查询当前公共事件的是否为有序公共事件(Promise形式)。 + +返回true代表是有序公共事件,false代表不是有序公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------- | +| Promise\ | 当前公共事件的是否为有序公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error("isOrdered failed " + JSON.stringify(err)); +}); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +检查当前公共事件是否为一个粘性事件(callback形式)。 + +返回true代表是粘性公共事件,false代表不是粘性公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 当前公共事件的是否为粘性公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取当前公共事件是否为粘性事件的回调 +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(): Promise\ + +检查当前公共事件是否为一个粘性事件(Promise形式)。 + +返回true代表是粘性公共事件,false代表不是粘性公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------- | +| Promise\ | 当前公共事件的是否为粘性公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + +### abortCommonEvent + +abortCommonEvent(callback: AsyncCallback\): void + +取消当前的公共事件,仅对有序公共事件有效,取消后,公共事件不再向下一个订阅者传递(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 取消当前的公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//取消当前有序公共事件的回调 +function abortCallback(err) { + if (err.code) { + console.error("abortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCallback); +``` + +### abortCommonEvent + +abortCommonEvent(): Promise\ + +取消当前的公共事件,仅对有序公共事件有效,取消后,公共事件不再向下一个订阅者传递(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error("abortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(callback: AsyncCallback\): void + +清除当前公共事件的取消状态,仅对有序公共事件有效(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//清除当前公共事件取消状态的回调 +function clearAbortCallback(err) { + if (err.code) { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCallback); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(): Promise\ + +清除当前公共事件的取消状态,仅对有序公共事件有效(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(callback: AsyncCallback\): void + +获取当前有序公共事件是否取消的状态(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 表示当前有序公共事件是否取消的状态。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取当前有序公共事件是否取消的回调 +function getAbortCallback(err, AbortCommonEvent) { + if (err.code) { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("AbortCommonEvent " + AbortCommonEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCallback); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(): Promise\ + +获取当前有序公共事件是否取消的状态(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ---------------------------------- | +| Promise\ | 表示当前有序公共事件是否取消的状态。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { + console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +}).catch((err) => { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getSubscribeInfo + +getSubscribeInfo(callback: AsyncCallback\): void + +获取订阅者的订阅信息(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 是 | 表示订阅者的订阅信息。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取订阅者信息回调 +function getSubscribeInfoCallback(err, SubscribeInfo) { + if (err.code) { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); + } else { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + } +} +subscriber.getSubscribeInfo(getSubscribeInfoCallback); +``` + +### getSubscribeInfo + +getSubscribeInfo(): Promise\ + +获取订阅者的订阅信息(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 表示订阅者的订阅信息。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getSubscribeInfo().then((SubscribeInfo) => { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +}).catch((err) => { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); +}); +``` + +### finishCommonEvent9+ + +finishCommonEvent(callback: AsyncCallback\): void + +结束当前有序公共事件(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | 是 | 表示有序公共事件结束后的回调函数。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//结束当前有序公共事件的回调 +function finishCommonEventCallback(err) { + if (err.code) { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +} else { + console.info("FinishCommonEvent"); +} +} +subscriber.finishCommonEvent(finishCommonEventCallback); +``` + +### finishCommonEvent9+ + +finishCommonEvent(): Promise\ + +结束当前有序公共事件(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +}); +``` + +## CommonEventData + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent + +| 名称 | 可读 | 可写 | 类型 | 描述 | +| ---------- | ---- | ---- | -------------------- | ------------------------------------------------------- | +| event | 是 | 否 | string | 表示当前接收的公共事件名称。 | +| bundleName | 是 | 否 | string | 表示包名称。 | +| code | 是 | 否 | number | 表示公共事件的结果代码,用于传递int类型的数据。 | +| data | 是 | 否 | string | 表示公共事件的自定义结果数据,用于传递string类型的数据。 | +| parameters | 是 | 否 | {[key: string]: any} | 表示公共事件的附加信息。 | + + +## CommonEventPublishData + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent + +| 名称 | 可读 | 可写 | 类型 | 描述 | +| --------------------- | ---- | ---- | -------------------- | ---------------------------- | +| bundleName | 是 | 否 | string | 表示包名称。 | +| code | 是 | 否 | number | 表示公共事件的结果代码。 | +| data | 是 | 否 | string | 表示公共事件的自定义结果数据。 | +| subscriberPermissions | 是 | 否 | Array\ | 表示订阅者的权限。 | +| isOrdered | 是 | 否 | boolean | 表示是否是有序事件。 | +| isSticky | 是 | 否 | boolean | 表示是否是粘性事件。 | +| parameters | 是 | 否 | {[key: string]: any} | 表示公共事件的附加信息。 | + +## CommonEventSubscribeInfo + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent + +| 名称 | 可读 | 可写 | 类型 | 描述 | +| ------------------- | ---- | ---- | -------------- | ------------------------------------------------------------ | +| events | 是 | 否 | Array\ | 表示要发送的公共事件。 | +| publisherPermission | 是 | 否 | string | 表示发布者的权限。 | +| publisherDeviceId | 是 | 否 | string | 表示设备ID,该值必须是同一ohos网络上的现有设备ID。 | +| userId | 是 | 否 | number | 表示用户ID。此参数是可选的,默认值当前用户的ID。如果指定了此参数,则该值必须是系统中现有的用户ID。 | +| priority | 是 | 否 | number | 表示订阅者的优先级。值的范围是-100到1000。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md index ec0549cfff1c91b4395dbe479d6e4e418554e430..b9a2765552732a482ba053d47ec0751bb8a3c767 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md @@ -14,8 +14,53 @@ import convertxml from '@ohos.convertxml'; ## ConvertXML +### convertToJSObject9+ -### convert +convertToJSObject(xml: string, options?: ConvertOptions) : Object + +转换xml文本为JavaScript对象。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------------- | ---- | --------------- | +| xml | string | 是 | 传入的xml文本。 | +| options | [ConvertOptions](#convertoptions) | 否 | 转换选项。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| Object | 处理后返回的JavaScript对象。 | + +**示例:** + +```js +let xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let conv = new convertxml.convertToJSObject(); +let options = {trim : false, declarationKey:"_declaration", + instructionKey : "_instruction", attributesKey : "_attributes", + textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", + commentKey : "_comment", parentKey : "_parent", typeKey : "_type", + nameKey : "_name", elementsKey : "_elements"} +let result = JSON.stringify(conv.convert(xml, options)); +console.log(result); +// 输出(宽泛型) +// {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]} +``` + +### convert(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[convertToJSObject9+](#converttojsobject9)替代。 convert(xml: string, options?: ConvertOptions) : Object @@ -23,7 +68,6 @@ convert(xml: string, options?: ConvertOptions) : Object **系统能力:** SystemCapability.Utils.Lang - **参数:** | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-cooperate.md b/zh-cn/application-dev/reference/apis/js-apis-cooperate.md index 32d7490e912276ab087ebb35ad7bae37d5b195de..3e01d5ba83445c2915c3aca047a3d30fbfcd0920 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-cooperate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cooperate.md @@ -1,7 +1,6 @@ -# 键鼠穿越管理 +# 键鼠穿越 -键鼠穿越功能,即两台或多台设备组网协同后可以共用一套键盘鼠标。 -键鼠穿越管理模块,提供实现键盘、鼠标等外接输入设备的跨设备协同操作。在设备组网的情况下,提供多设备间共享键鼠的开关,设备穿越状态更新以及键鼠穿越光标自适应显示。 +键鼠穿越功能模块,提供两台或多台设备组网协同后键鼠共享能力,实现键鼠输入设备的跨设备协同操作。 > **说明** > @@ -15,18 +14,18 @@ import inputDeviceCooperate from '@ohos.multimodalInput.inputDeviceCooperate' ## inputDeviceCooperate.enable -enable(enable: boolean, callback: AsyncCallback\): void +enable(enable: boolean, callback: AsyncCallback<void>): void -键鼠穿越开关开启或关闭,使用callback异步回调。 +开启、关闭键鼠穿越,使用AsyncCallback异步方式返回结果。 **系统能力**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------------------------------- | -| enable | boolean | 是 | 键鼠穿越开关开启或关闭状态。true: 键鼠穿越开关开启; false: 键鼠穿越开关关闭。 -| callback | AsyncCallback\ | 是 | 异步回调函数。当键鼠穿越开关开启或关闭成功,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | --------------------------- | +| enable | boolean | 是 | 键鼠穿越使能状态。 | +| callback | AsyncCallback<void> | 是 |回调函数,异步返回键鼠穿越开启、关闭结果。 | @@ -34,23 +33,24 @@ enable(enable: boolean, callback: AsyncCallback\): void ```js try { - inputDeviceCooperate.enable(true, (err) => { - if (err) { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.enable(true, (error) => { + if (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Turn on the key mouse crossing switch success.`); + console.log(`Keyboard mouse crossing enable success.`); }); -} catch (err) { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## inputDeviceCooperate.enable -enable(enable: boolean): Promise\ +enable(enable: boolean): Promise<void> + +开启、关闭键鼠穿越,使用Promise异步方式返回结果。 -键鼠穿越开关开启或关闭,使用Promise方式作为异步方法。 **系统能力**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -58,7 +58,7 @@ enable(enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | --------- | ------- | ---- | ------------------------------------------------------------------- | -| enable | boolean | 是 | 键鼠穿越开关开启或关闭状态。true: 键鼠穿越开关开启; false: 键鼠穿越开关关闭。 | +| enable | boolean | 是 | 键鼠穿越使能状态。 | @@ -66,7 +66,7 @@ enable(enable: boolean): Promise\ | 参数 | 说明 | | ------------------- | ------------------------------- | -| Promise\ | Promise实例,用于异步获取结果。 | +| Promise<void> | Promise对象,异步返回键鼠穿越开启、关闭结果。 | @@ -74,13 +74,13 @@ enable(enable: boolean): Promise\ ```js try { - inputDeviceCooperate.enable(false).then((err) => { - console.log(`Turn on the key mouse crossing switch success`); - }, (err) => { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.enable(true).then(() => { + console.log(`Keyboard mouse crossing enable success.`); + }, (error) => { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -88,7 +88,7 @@ try { start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCallback\): void -启动键鼠穿越,使用callback异步回调。 +启动键鼠穿越,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -98,7 +98,7 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCal | -------- | ---------------------------- | ---- | ---------------------------- | | sinkDeviceDescriptor | string | 是 | 键鼠穿越目标设备描述符。 | | srcInputDeviceId | number | 是 | 键鼠穿越待穿越外设标识符。 | -| callback | AsyncCallback\ | 是 | 异步回调函数。当键鼠穿越启动成功,err为undefined,否则为错误对象。| +| callback | AsyncCallback\ | 是 | 回调函数,异步返回键鼠穿越启动、停止状态。| **错误码:** @@ -106,22 +106,22 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCal | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 4400001 | Incorrect descriptor for the target device. | -| 4400002 | Failed to operate the input device. | +| 4400001 | 当调用键鼠穿越接口传入无效的设备描述符参数时,系统会产生此错误码。 | +| 4400002 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | **示例**: ```js try { - inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (err) => { - if (err) { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => { + if (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Start key mouse crossing success.`); + console.log(`Start Keyboard mouse crossing success.`); }); -} catch (err) { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -129,7 +129,7 @@ try { start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ -启动键鼠穿越,使用Promise方式作为异步方法。 +启动键鼠穿越,使用Promise异步方式返回结果。 **系统能力**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -146,7 +146,7 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ | 参数名 | 说明 | | ---------------------- | ------------------------------- | -| Promise\ | Promise实例,用于异步获取结果。 | +| Promise\ | Promise对象,异步返回键鼠穿越启动、关闭结果。 | **错误码:** @@ -154,20 +154,20 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 4400001 | Incorrect descriptor for the target device. | -| 4400002 | Failed to operate the input device. | +| 4400001 | 当调用键鼠穿越接口传入无效的设备描述符参数时,系统会产生此错误码。 | +| 4400002 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | **示例**: ```js try { - inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then((err) => { - console.log(`Start key mouse crossing success.`); - }, (err) => { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => { + console.log(`Start Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -175,7 +175,7 @@ try { stop(callback: AsyncCallback\): void -停止键鼠穿越,使用callback异步回调。 +停止键鼠穿越,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -183,7 +183,7 @@ stop(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步回调函数,返回查询结果。 | +| callback | AsyncCallback\ | 是 | 回调函数,异步返回停止键鼠穿越结果。 | @@ -191,15 +191,15 @@ stop(callback: AsyncCallback\): void ```js try { - inputDeviceCooperate.stop((err) => { - if (err) { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.stop((error) => { + if (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Stop key mouse crossing success.`); + console.log(`Stop Keyboard mouse crossing success.`); }); -} catch (err) { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -207,7 +207,7 @@ try { stop(): Promise\ -停止键鼠穿越,使用Promise异步回调。 +停止键鼠穿越,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -215,19 +215,19 @@ stop(): Promise\ | 参数名 | 说明 | | -------- | ---------------------------- | -| Promise\ | Promise实例,用于异步获取结果。 | +| Promise\ | Promise对象,异步返回停止键鼠穿越结果。 | **示例**: ```js try { - inputDeviceCooperate.stop().then((err) => { - console.log(`Stop key mouse crossing success.`); - }, (err) => { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.stop().then(() => { + console.log(`Stop Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -235,7 +235,7 @@ try { getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): void -获取键鼠穿越开关的状态,使用callback异步回调。 +获取键鼠穿越开关的状态,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -244,21 +244,21 @@ getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------- | ---- | ---------------------------- | | deviceDescriptor | string | 是 | 键鼠穿越目标设备描述符。 | -| callback | AsyncCallback<{ state: boolean }> | 是 | 异步回调函数,接收键鼠穿越开关状态。 | +| callback | AsyncCallback<{ state: boolean }> | 是 | 回调函数,异步返回键鼠穿越开关状态。 | **示例**: ```js try { - inputDeviceCooperate.getState(deviceDescriptor, (err, data) => { - if (err) { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.getState(deviceDescriptor, (error, data) => { + if (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Get the status success. data=${JSON.stringify(data)}`); + console.log(`Get the status success, data: ${JSON.stringify(data)}`); }); -} catch (err) { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -266,7 +266,7 @@ try { getState(deviceDescriptor: string): Promise<{ state: boolean }> -获取键鼠穿越开关的状态,使用Promise异步回调。 +获取键鼠穿越开关的状态,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -282,7 +282,7 @@ getState(deviceDescriptor: string): Promise<{ state: boolean }> | 参数 | 说明 | | ------------------- | ------------------------------- | -| Promise<{ state: boolean }>| Promise实例,用于异步获取结果。 | +| Promise<{ state: boolean }>| Promise对象,异步返回键鼠穿越开关状态。 | @@ -291,12 +291,12 @@ getState(deviceDescriptor: string): Promise<{ state: boolean }> ```js try { inputDeviceCooperate.getState(deviceDescriptor).then((data) => { - console.log(`Get the status success. data=${JSON.stringify(data)}`); - }, (err) => { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + console.log(`Get the status success, data: ${JSON.stringify(data)}`); + }, (error) => { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -312,8 +312,8 @@ on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, even | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ---------------------------- | -| type | string | 是 | 注册类型,'cooperation'。 | -| callback | AsyncCallback<{ deviceDescriptor: string, eventMsg: [EventMsg](#eventmsg) }> | 是 | 异步回调函数,接收键鼠穿越事件消息。 | +| type | string | 是 | 注册类型,取值”cooperation“。 | +| callback | AsyncCallback<{ deviceDescriptor: string, eventMsg: [EventMsg](#eventmsg) }> | 是 | 回调函数,异步返回键鼠穿越事件。 | @@ -322,14 +322,10 @@ on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, even ```js try { inputDeviceCooperate.on('cooperation', (data) => { - if (data) { - console.log(`error: ${JSON.stringify(data)}`); - } else { - console.log(`cooperation: ${JSON.stringify(data)}`); - } + console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`); }); } catch (err) { - console.log(`Registered failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -345,24 +341,37 @@ off(type: 'cooperation', callback?: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ---------------------------- | -| type | string | 是 | 注册类型,'cooperation'。 | -| callback | AsyncCallback | 否 | 异步回调函数,用于返回结果。 | +| type | string | 是 | 注册类型,取值“cooperation”。 | +| callback | AsyncCallback | 否 | 需要取消注册的回调函数,若无此参数,则取消当前应用注册的所有回调函数。 | **示例**: ```js +// 取消注册单个回调函数 +callback: function(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +}, try { - inputDeviceCooperate.off('cooperation', (err) => { - if (err) { - console.log(`error: ${JSON.stringify(err)}`); - } else { - console.log(`Unregistered succeed`); - } - }); -} catch (err) { - console.log(`Unregistered failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.on('cooperation', this.callback); + inputDeviceCooperate.off("cooperation", this.callback); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` +```js +// 取消注册所有回调函数 +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`])}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md index 4db44625182dc2518deb9ab3a9309cca99a6bfb2..49111b648c5c66fa8846e16561160dfe97fee3a6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @@ -22,8 +22,8 @@ import data_preferences from '@ohos.data.preferences'; | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ---------------- | -------- | ---- | ---- | --------------------------------------- | -| MAX_KEY_LENGTH | string | 是 | 否 | Key的最大长度限制,需小于80个字节。 | -| MAX_VALUE_LENGTH | string | 是 | 否 | Value的最大长度限制,需小于8192个字节。 | +| MAX_KEY_LENGTH | number | 是 | 否 | Key的最大长度限制,需小于80个字节。 | +| MAX_VALUE_LENGTH | number | 是 | 否 | Value的最大长度限制,需小于8192个字节。 | ## data_preferences.getPreferences diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index 39465f70542b10799dcac16ccfe566fe8d989cc1..86cd8f8ebd6accc6ee41a7d01c2e40dc40e1c73e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -4,8 +4,8 @@ 该模块提供以下关系型数据库相关的常用功能: -- [RdbPredicates](#rdbpredicates): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 -- [RdbStore](#rdbstore):提供管理关系数据库(RDB)方法的接口。 +- [RdbPredicatesV9](#rdbpredicatesv99): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 +- [RdbStoreV9](#rdbstorev99):提供管理关系数据库(RDB)方法的接口。 > **说明:** > @@ -17,22 +17,304 @@ import data_rdb from '@ohos.data.rdb'; ``` -## data_rdb.getRdbStore +## data_rdb.getRdbStoreV99+ + +getRdbStoreV9(context: Context, config: StoreConfigV9, version: number, callback: AsyncCallback<RdbStoreV9>): void + +获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | +| callback | AsyncCallback<[RdbStoreV9](#rdbstorev9)> | 是 | 指定callback回调函数,返回RdbStoreV9对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | +| 14800011 | Database corrupted. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { + if (err) { + console.info("Get RdbStoreV9 failed, err: " + err) + return + } + console.log("Get RdbStoreV9 successfully.") +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { + if (err) { + console.info("Get RdbStoreV9 failed, err: " + err) + return + } + console.log("Get RdbStoreV9 successfully.") +}) +``` + +## data_rdb.getRdbStoreV99+ + +getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> + +获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | + +**返回值**: + +| 类型 | 说明 | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStoreV9](#rdbstorev99)> | Promise对象。返回RdbStoreV9对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | +| 14800011 | Database corrupted. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +let promise = data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1); +promise.then(async (rdbStoreV9) => { + console.log("Get RdbStoreV9 successfully.") +}).catch((err) => { + console.log("Get RdbStoreV9 failed, err: " + err) +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +let promise = data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1); +promise.then(async (rdbStoreV9) => { + console.log("Get RdbStoreV9 successfully.") +}).catch((err) => { + console.log("Get RdbStoreV9 failed, err: " + err) +}) +``` + +## data_rdb.deleteRdbStoreV99+ + +deleteRdbStoreV9(context: Context, name: string, callback: AsyncCallback<void>): void + +删除数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用deleteRdbStoreV9 +data_rdb.deleteRdbStoreV9(context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStorev9 failed, err: " + err) + return + } + console.log("Delete RdbStorev9 successfully.") +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用deleteRdbStoreV9 +data_rdb.deleteRdbStoreV9(context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStoreV9 failed, err: " + err) + return + } + console.log("Delete RdbStoreV9 successfully.") +}) +``` + +## data_rdb.deleteRdbStoreV99+ + +deleteRdbStoreV9(context: Context, name: string): Promise<void> + +使用指定的数据库文件配置删除数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用deleteRdbStoreV9 +let promise = data_rdb.deleteRdbStoreV9(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStoreV9 successfully.") +}).catch((err) => { + console.info("Delete RdbStoreV9 failed, err: " + err) +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用deleteRdbStoreV9 +let promise = data_rdb.deleteRdbStoreV9(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStoreV9 successfully.") +}).catch((err) => { + console.info("Delete RdbStoreV9 failed, err: " + err) +}) +``` + +## data_rdb.getRdbStore(deprecated) getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。| -| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | -| version | number | 是 | 数据库版本。 | -| callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回一个RdbStore。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回RdbStore对象。 | **示例:** @@ -41,7 +323,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db"} @@ -59,7 +341,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -76,27 +358,32 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { console.log("Get RdbStore successfully.") }) ``` -## data_rdb.getRdbStore + +## data_rdb.getRdbStore(deprecated) getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | -| version | number | 是 | 数据库版本。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<[RdbStore](#rdbstore)> | 指定Promise回调函数。返回一个RdbStore。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise对象。返回RdbStore对象。 | **示例:** @@ -105,7 +392,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db" } @@ -122,7 +409,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -139,21 +426,25 @@ promise.then(async (rdbStore) => { }) ``` -## data_rdb.deleteRdbStore +## data_rdb.deleteRdbStore(deprecated) deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void 删除数据库,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。| -| name | string | 是 | 数据库名称。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | **示例:** @@ -162,7 +453,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用deleteRdbStore data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { @@ -179,7 +470,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -196,26 +487,30 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { }) ``` -## data_rdb.deleteRdbStore +## data_rdb.deleteRdbStore(deprecated) deleteRdbStore(context: Context, name: string): Promise<void> 使用指定的数据库文件配置删除数据库,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。| -| name | string | 是 | 数据库名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** @@ -224,11 +519,11 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用deleteRdbStore let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ +promise.then(() => { console.log("Delete RdbStore successfully.") }).catch((err) => { console.info("Delete RdbStore failed, err: " + err) @@ -240,7 +535,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -256,162 +551,162 @@ promise.then(()=>{ }) ``` -## RdbPredicates +## RdbPredicatesV99+ 表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 -### constructor +### constructor9+ constructor(name: string) 构造函数。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| name | string | 是 | 数据库表名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| name | string | 是 | 数据库表名。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") ``` -### inDevices8+ +### inDevices9+ -inDevices(devices: Array<string>): RdbPredicates +inDevices(devices: Array<string>): RdbPredicatesV9 同步分布式数据库时连接到组网内指定的远程设备。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | -------------------------- | +| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inDevices(['12345678abcde']) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.inDevices(['12345678abcde']) ``` -### inAllDevices8+ +### inAllDevices9+ -inAllDevices(): RdbPredicates +inAllDevices(): RdbPredicatesV9 同步分布式数据库时连接到组网内所有的远程设备。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesv9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inAllDevices() +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.inAllDevices() ``` -### equalTo +### equalTo9+ -equalTo(field: string, value: ValueType): RdbPredicates +equalTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "lisi") ``` -### notEqualTo +### notEqualTo9+ -notEqualTo(field: string, value: ValueType): RdbPredicates +notEqualTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notEqualTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.notEqualTo("NAME", "lisi") ``` -### beginWrap +### beginWrap9+ -beginWrap(): RdbPredicates +beginWrap(): RdbPredicatesV9 向谓词添加左括号。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有左括号的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有左括号的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -419,25 +714,25 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -### endWrap +### endWrap9+ -endWrap(): RdbPredicates +endWrap(): RdbPredicatesV9 向谓词添加右括号。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有右括号的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有右括号的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -445,676 +740,677 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -### or +### or9+ -or(): RdbPredicates +or(): RdbPredicatesV9 将或条件添加到谓词中。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有或条件的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有或条件的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") ``` -### and +### and9+ -and(): RdbPredicates +and(): RdbPredicatesV9 向谓词添加和条件。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有和条件的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有和条件的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) ``` -### contains +### contains9+ -contains(field: string, value: string): RdbPredicates +contains(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且value包含指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.contains("NAME", "os") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.contains("NAME", "os") ``` -### beginsWith +### beginsWith9+ -beginsWith(field: string, value: string): RdbPredicates +beginsWith(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.beginsWith("NAME", "os") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.beginsWith("NAME", "os") ``` -### endsWith +### endsWith9+ -endsWith(field: string, value: string): RdbPredicates +endsWith(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.endsWith("NAME", "se") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.endsWith("NAME", "se") ``` -### isNull +### isNull9+ -isNull(field: string): RdbPredicates +isNull(field: string): RdbPredicatesV9 配置谓词以匹配值为null的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例**: + ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNull("NAME") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.isNull("NAME") ``` -### isNotNull +### isNotNull9+ -isNotNull(field: string): RdbPredicates +isNotNull(field: string): RdbPredicatesV9 配置谓词以匹配值不为null的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNotNull("NAME") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.isNotNull("NAME") ``` -### like +### like9+ -like(field: string, value: string): RdbPredicates +like(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.like("NAME", "%os%") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.like("NAME", "%os%") ``` -### glob +### glob9+ -glob(field: string, value: string): RdbPredicates +glob(field: string, value: string): RdbPredicatesV9 -配置RdbPredicates匹配数据字段为string的指定字段。 +配置RdbPredicatesV9匹配数据字段为string的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.glob("NAME", "?h*g") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.glob("NAME", "?h*g") ``` -### between +### between9+ -between(field: string, low: ValueType, high: ValueType): RdbPredicates +between(field: string, low: ValueType, high: ValueType): RdbPredicatesV9 将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | -| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.between("AGE", 10, 50) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.between("AGE", 10, 50) ``` -### notBetween +### notBetween9+ -notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicatesV9 -配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 +配置RdbPredicatesV9以匹配数据字段为ValueType且value超出给定范围的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | -| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notBetween("AGE", 10, 50) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.notBetween("AGE", 10, 50) ``` -### greaterThan +### greaterThan9+ -greaterThan(field: string, value: ValueType): RdbPredicates +greaterThan(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThan("AGE", 18) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.greaterThan("AGE", 18) ``` -### lessThan +### lessThan9+ -lessThan(field: string, value: ValueType): RdbPredicates +lessThan(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为valueType且value小于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThan("AGE", 20) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.lessThan("AGE", 20) ``` -### greaterThanOrEqualTo +### greaterThanOrEqualTo9+ -greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThanOrEqualTo("AGE", 18) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.greaterThanOrEqualTo("AGE", 18) ``` -### lessThanOrEqualTo +### lessThanOrEqualTo9+ -lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThanOrEqualTo("AGE", 20) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.lessThanOrEqualTo("AGE", 20) ``` -### orderByAsc +### orderByAsc9+ -orderByAsc(field: string): RdbPredicates +orderByAsc(field: string): RdbPredicatesV9 配置谓词以匹配其值按升序排序的列。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByAsc("NAME") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.orderByAsc("NAME") ``` -### orderByDesc +### orderByDesc9+ -orderByDesc(field: string): RdbPredicates +orderByDesc(field: string): RdbPredicatesV9 配置谓词以匹配其值按降序排序的列。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByDesc("AGE") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.orderByDesc("AGE") ``` -### distinct +### distinct9+ -distinct(): RdbPredicates +distinct(): RdbPredicatesV9 配置谓词以过滤重复记录并仅保留其中一个。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回可用于过滤重复记录的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------ | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于过滤重复记录的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").distinct() +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose").distinct() ``` -### limitAs +### limitAs9+ -limitAs(value: number): RdbPredicates +limitAs(value: number): RdbPredicatesV9 设置最大数据记录数的谓词。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| value | number | 是 | 最大数据记录数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------- | +| value | number | 是 | 最大数据记录数。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回可用于设置最大数据记录数的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于设置最大数据记录数的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").limitAs(3) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose").limitAs(3) ``` -### offsetAs +### offsetAs9+ -offsetAs(rowOffset: number): RdbPredicates +offsetAs(rowOffset: number): RdbPredicatesV9 -配置RdbPredicates以指定返回结果的起始位置。 +配置RdbPredicatesV9以指定返回结果的起始位置。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回具有指定返回结果起始位置的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回具有指定返回结果起始位置的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").offsetAs(3) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose").offsetAs(3) ``` -### groupBy +### groupBy9+ -groupBy(fields: Array<string>): RdbPredicates +groupBy(fields: Array<string>): RdbPredicatesV9 -配置RdbPredicates按指定列分组查询结果。 +配置RdbPredicatesV9按指定列分组查询结果。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| fields | Array<string> | 是 | 指定分组依赖的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | 是 | 指定分组依赖的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回分组查询列的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ---------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回分组查询列的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.groupBy(["AGE", "NAME"]) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.groupBy(["AGE", "NAME"]) ``` -### indexedBy +### indexedBy9+ -indexedBy(field: string): RdbPredicates +indexedBy(field: string): RdbPredicatesV9 -配置RdbPredicates以指定索引列。 +配置RdbPredicatesV9以指定索引列。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 索引列的名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------- | +| field | string | 是 | 索引列的名称。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回具有指定索引列的RdbPredicates。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回具有指定索引列的RdbPredicatesV9。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.indexedBy("SALARY_INDEX") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.indexedBy("SALARY_INDEX") ``` -### in +### in9+ -in(field: string, value: Array<ValueType>): RdbPredicates +in(field: string, value: Array<ValueType>): RdbPredicatesV9 -配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 +配置RdbPredicatesV9以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.in("AGE", [18, 20]) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.in("AGE", [18, 20]) ``` -### notIn +### notIn9+ -notIn(field: string, value: Array<ValueType>): RdbPredicates +notIn(field: string, value: Array<ValueType>): RdbPredicatesV9 -将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 +将RdbPredicatesV9配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notIn("NAME", ["Lisa", "Rose"]) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.notIn("NAME", ["Lisa", "Rose"]) ``` -## RdbStore +## RdbStoreV99+ 提供管理关系数据库(RDB)方法的接口。 在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 -### insert +### insert9+ insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void 向目标表中插入一行数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | **示例:** @@ -1125,7 +1421,7 @@ const valueBucket = { "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { +rdbStoreV9.insert("EMPLOYEE", valueBucket, function (status, rowId) { if (status) { console.log("Insert is failed"); return; @@ -1134,26 +1430,26 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { }) ``` -### insert +### insert9+ insert(table: string, values: ValuesBucket):Promise<number> 向目标表中插入一行数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。如果操作成功,返回行ID;否则返回-1。 | +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | **示例:** @@ -1164,7 +1460,7 @@ const valueBucket = { "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -let promise = rdbStore.insert("EMPLOYEE", valueBucket) +let promise = rdbStoreV9.insert("EMPLOYEE", valueBucket) promise.then((rowId) => { console.log("Insert is successful, rowId = " + rowId); }).catch((status) => { @@ -1178,15 +1474,15 @@ batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCal 向目标表中插入一组数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | **示例:** @@ -1210,8 +1506,8 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStoreV9.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { console.log("batchInsert is failed, status = " + status); return; @@ -1226,20 +1522,20 @@ batchInsert(table: string, values: Array<ValuesBucket>):Promise<number& 向目标表中插入一组数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | **示例:** @@ -1263,8 +1559,8 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStoreV9.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); }).catch((status) => { @@ -1272,21 +1568,21 @@ promise.then((insertNum) => { }) ``` -### update +### update9+ -update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void +update(values: ValuesBucket, predicates: RdbPredicatesV9, callback: AsyncCallback<number>):void -根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 +根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | -| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | **示例:** @@ -1297,9 +1593,9 @@ const valueBucket = { "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +rdbStoreV9.update(valueBucket, predicatesV9, function (err, ret) { if (err) { console.info("Updated failed, err: " + err) return @@ -1308,25 +1604,25 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { }) ``` -### update +### update9+ -update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> +update(values: ValuesBucket, predicates: RdbPredicatesV9):Promise<number> -根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 +根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicatesV9 | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | | Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | **示例:** @@ -1338,9 +1634,9 @@ const valueBucket = { "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update(valueBucket, predicates) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +let promise = rdbStoreV9.update(valueBucket, predicatesV9) promise.then(async (ret) => { console.log("Updated row count: " + ret) }).catch((err) => { @@ -1349,22 +1645,21 @@ promise.then(async (ret) => { ``` ### update9+ + update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void 根据DataSharePredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| 是 | DataSharePredicates的实例对象指定的更新条件。 | -| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | **示例:** @@ -1378,7 +1673,7 @@ const valueBucket = { } let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { +rdbStoreV9.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { if (err) { console.info("Updated failed, err: " + err) return @@ -1393,22 +1688,20 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data 根据DataSharePredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | | Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | **示例:** @@ -1423,7 +1716,7 @@ const valueBucket = { } let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +let promise = rdbStoreV9.update("EMPLOYEE", valueBucket, predicates) promise.then(async (ret) => { console.log("Updated row count: " + ret) }).catch((err) => { @@ -1431,27 +1724,27 @@ promise.then(async (ret) => { }) ``` -### delete +### delete9+ -delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void +delete(predicates: RdbPredicatesV9, callback: AsyncCallback<number>):void -根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 +根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.delete(predicates, function (err, rows) { +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +rdbStoreV9.delete(predicatesV9, function (err, rows) { if (err) { console.info("Delete failed, err: " + err) return @@ -1460,32 +1753,32 @@ rdbStore.delete(predicates, function (err, rows) { }) ``` -### delete +### delete9+ -delete(predicates: RdbPredicates):Promise<number> +delete(predicates: RdbPredicatesV9):Promise<number> -根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 +根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。返回受影响的行数。 | +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete(predicates) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +let promise = rdbStoreV9.delete(predicatesV9) promise.then((rows) => { console.log("Delete rows: " + rows) }).catch((err) => { @@ -1499,17 +1792,15 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callb 根据DataSharePredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | **示例:** @@ -1517,7 +1808,7 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callb import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { +rdbStoreV9.delete("EMPLOYEE", predicates, function (err, rows) { if (err) { console.info("Delete failed, err: " + err) return @@ -1532,22 +1823,20 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promi 根据DataSharePredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。返回受影响的行数。 | +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | **示例:** @@ -1555,7 +1844,7 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promi import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) +let promise = rdbStoreV9.delete("EMPLOYEE", predicates) promise.then((rows) => { console.log("Delete rows: " + rows) }).catch((err) => { @@ -1563,151 +1852,2196 @@ promise.then((rows) => { }) ``` -### query +### query9+ -query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void +query(predicates: RdbPredicatesV9, columns: Array<string>, callback: AsyncCallback<ResultSetV9>):void 根据指定条件查询数据库中的数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose") -rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose") +rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSetV9) { if (err) { console.info("Query failed, err: " + err) return } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) }) ``` -### query +### query9+ -query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> +query(predicates: RdbPredicatesV9, columns?: Array<string>):Promise<ResultSetV9> 根据指定条件查询数据库中的数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | **示例:** ```js - let predicates = new data_rdb.RdbPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose") - let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) - }).catch((err) => { - console.info("Query failed, err: " + err) - }) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose") +let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSetV9) => { + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) ``` ### query9+ -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSetV9>):void 根据指定条件查询数据库中的数据,使用callback异步回调。 -**系统接口:** 此接口为系统接口。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStoreV9.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSetV9) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}) +``` + +### query9+ + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSetV9> + +根据指定条件查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStoreV9.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSetV9) => { + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` + +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string> , callback: AsyncCallback<ResultSetV9>): void + +根据指定条件查询远程设备数据库中的数据。使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| device | string | 是 | 指定的远程设备的networkId。 | +| table | string | 是 | 指定的目标表名。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.greaterThan("id", 0) +rdbStoreV9.remoteQuery("deviceId", "EMPLOYEE", predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSetV9){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSetV9.columnNames) + console.info("ResultSet column count: " + resultSetV9.columnCount) +}) +``` + +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> + +根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| device | string | 是 | 指定的远程设备的networkId。 | +| table | string | 是 | 指定的目标表名。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------------ | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md#resultset)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.greaterThan("id", 0) +let promise = rdbStoreV9.remoteQuery("deviceId", "EMPLOYEE", predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSetV9) => { + console.info("ResultSet column names: " + resultSetV9.columnNames) + console.info("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + +### querySql9+ + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSetV9>):void + +根据指定SQL语句查询数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +rdbStoreV9.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSetV9) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}) +``` + +### querySql9+ + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSetV9> + +根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +let promise = rdbStoreV9.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +promise.then((resultSetV9) => { + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` + +### executeSql9+ + +executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void + +执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ---------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +rdbStoreV9.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.info("ExecuteSql failed, err: " + err) + return + } + console.info('Create table done.') +}) +``` + +### executeSql9+ + +executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> + +执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promise = rdbStoreV9.executeSql(SQL_CREATE_TABLE) +promise.then(() => { + console.info('Create table done.') +}).catch((err) => { + console.info("ExecuteSql failed, err: " + err) +}) +``` + +### beginTransaction9+ + +beginTransaction():void + +在开始执行SQL语句之前,开始事务。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { + rdbStoreV9.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + rdbStoreV9.commit() +}) +``` + +### commit9+ + +commit():void + +提交已执行的SQL语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { + rdbStoreV9.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + rdbStoreV9.commit() +}) +``` + +### rollBack9+ + +rollBack():void + +回滚已经执行的SQL语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { + try { + rdbStoreV9.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + rdbStoreV9.commit() + } catch (e) { + rdbStoreV9.rollBack() + } +}) +``` + +### backup9+ + +backup(destName:string, callback: AsyncCallback<void>):void + +以指定名称备份数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | 是 | 指定数据库的备份文件名。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStoreV9.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup9+ + +backup(destName:string): Promise<void> + +以指定名称备份数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| destName | string | 是 | 指定数据库的备份文件名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promiseBackup = rdbStoreV9.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore9+ + +restore(srcName:string, callback: AsyncCallback<void>):void + +从指定的数据库备份文件恢复数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | 是 | 指定数据库的备份文件名。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStoreV9.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore9+ + +restore(srcName:string): Promise<void> + +从指定的数据库备份文件恢复数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | 是 | 指定数据库的备份文件名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promiseRestore = rdbStoreV9.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` + +### setDistributedTables9+ + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void + +设置分布式列表,使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------- | +| tables | Array<string> | 是 | 要设置的分布式列表表名 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStoreV9.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.info('SetDistributedTables failed, err: ' + err) + return + } + console.info('SetDistributedTables successfully.') +}) +``` + +### setDistributedTables9+ + + setDistributedTables(tables: Array<string>): Promise<void> + +设置分布式列表,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | ------------------------ | +| tables | Array<string> | 是 | 要设置的分布式列表表名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promise = rdbStoreV9.setDistributedTables(["EMPLOYEE"]) +promise.then(() => { + console.info("SetDistributedTables successfully.") +}).catch((err) => { + console.info("SetDistributedTables failed, err: " + err) +}) +``` + +### obtainDistributedTableName9+ + +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void + +根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| device | string | 是 | 远程设备 。 | +| table | string | 是 | 本地表名。 | +| callback | AsyncCallback<string> | 是 | 指定的callback回调函数。如果操作成功,返回远程设备的分布式表名。 | + +**示例:** + +```js +rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { + if (err) { + console.info('ObtainDistributedTableName failed, err: ' + err) + return + } + console.info('ObtainDistributedTableName successfully, tableName=.' + tableName) +}) +``` + +### obtainDistributedTableName9+ + + obtainDistributedTableName(device: string, table: string): Promise<string> + +根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| device | string | 是 | 远程设备。 | +| table | string | 是 | 本地表名。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------- | +| Promise<string> | Promise对象。如果操作成功,返回远程设备的分布式表名。 | + +**示例:** + +```js +let promise = rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +promise.then((tableName) => { + console.info('ObtainDistributedTableName successfully, tableName= ' + tableName) +}).catch((err) => { + console.info('ObtainDistributedTableName failed, err: ' + err) +}) +``` + +### sync9+ + +sync(mode: SyncMode, predicates: RdbPredicatesV9, callback: AsyncCallback<Array<[string, number]>>): void + +在设备之间同步数据, 使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 | +| callback | AsyncCallback<Array<[string, number]>> | 是 | 指定的callback回调函数,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.inDevices(['12345678abcde']) +rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesV9, function (err, result) { + if (err) { + console.log('Sync failed, err: ' + err) + return + } + console.log('Sync done.') + for (let i = 0; i < result.length; i++) { + console.log('device=' + result[i][0] + ' status=' + result[i][1]) + } +}) +``` + +### sync9+ + + sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise<Array<[string, number]>> + +在设备之间同步数据,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------ | +| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 | + +**返回值**: + +| 类型 | 说明 | +| -------------------------------------------- | ------------------------------------------------------------ | +| Promise<Array<[string, number]>> | Promise对象,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.inDevices(['12345678abcde']) +let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesV9) +promise.then((resultSetV9) =>{ + console.log('Sync done.') + for (let i = 0; i < resultSetV9.length; i++) { + console.log('device=' + resultSetV9[i][0] + ' status=' + resultSetV9[i][1]) + } +}).catch((err) => { + console.log('Sync failed') +}) +``` + +### on('dataChange')9+ + +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | 是 | 取值为'dataChange',表示数据更改。 | +| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | +| observer | Callback<Array<string>> | 是 | 指分布式数据库中数据更改事件的观察者。 | + +**示例:** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Register observer failed') +} +``` + +### off('dataChange')9+ + +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +从数据库中删除指定类型的指定观察者, 使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | 是 | 取值为'dataChange',表示数据更改。 | +| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | +| observer | Callback<Array<string>> | 是 | 指已注册的数据更改观察者。 | + +**示例:** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStoreV9.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Unregister observer failed') +} +``` + +## StoreConfigV99+ + +管理关系数据库配置。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | 是 | 数据库文件名。 | +| securityLevel | SecurityLevel | 是 | 设置数据库安全级别 | +| encrypt | boolean | 否 | 指定数据库是否加密。
true:加密。
false:非加密。 | + +## SecurityLevel9+ + +数据库的安全级别枚举。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | +| S2 | 2 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | +| S3 | 3 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | +| S4 | 4 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | + +## ValueType + +用于表示允许的数据字段类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 类型 | 说明 | +| ------- | -------------------- | +| number | 表示值类型为数字。 | +| string | 表示值类型为字符。 | +| boolean | 表示值类型为布尔值。 | + + +## ValuesBucket + +用于存储键值对的类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 键类型 | 值类型 | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode8+ + +指数据库同步模式。 + +**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | 表示数据从本地设备推送到远程设备。 | +| SYNC_MODE_PULL | 1 | 表示数据从远程设备拉至本地设备。 | + +## SubscribeType8+ + +描述订阅类型。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | + +## RdbPredicates(deprecated) + +表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[RdbPredicatesV9](#rdbpredicatesv99)替代。 + + +### constructor(deprecated) + +constructor(name: string) + +构造函数。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[constructor](#constructor9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 数据库表名。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +``` + +### inDevices(deprecated) + +inDevices(devices: Array<string>): RdbPredicates + +同步分布式数据库时连接到组网内指定的远程设备。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inDevices](#indevices9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inDevices(['12345678abcde']) +``` + +### inAllDevices(deprecated) + +inAllDevices(): RdbPredicates + +同步分布式数据库时连接到组网内所有的远程设备。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inAllDevices](#inalldevices9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inAllDevices() +``` + +### equalTo(deprecated) + +equalTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[equalTo](#equalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") +``` + + +### notEqualTo(deprecated) + +notEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[notEqualTo](#notequalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notEqualTo("NAME", "lisi") +``` + + +### beginWrap(deprecated) + +beginWrap(): RdbPredicates + +向谓词添加左括号。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[beginWrap](#beginwrap9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有左括号的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap(deprecated) + +endWrap(): RdbPredicates + +向谓词添加右括号。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[endWrap](#endwrap9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有右括号的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or(deprecated) + +or(): RdbPredicates + +将或条件添加到谓词中。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[or](#or9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有或条件的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and(deprecated) + +and(): RdbPredicates + +向谓词添加和条件。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[and](#and9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有和条件的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains(deprecated) + +contains(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且value包含指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[contains](#contains9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.contains("NAME", "os") +``` + +### beginsWith(deprecated) + +beginsWith(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[beginsWith](#beginswith9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.beginsWith("NAME", "os") +``` + +### endsWith(deprecated) + +endsWith(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[endsWith](#endswith9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.endsWith("NAME", "se") +``` + +### isNull(deprecated) + +isNull(field: string): RdbPredicates + +配置谓词以匹配值为null的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNull](#isnull9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例**: +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNull("NAME") +``` + +### isNotNull(deprecated) + +isNotNull(field: string): RdbPredicates + +配置谓词以匹配值不为null的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNotNull](#isnotnull9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNotNull("NAME") +``` + +### like(deprecated) + +like(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[like](#like9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.like("NAME", "%os%") +``` + +### glob(deprecated) + +glob(field: string, value: string): RdbPredicates + +配置RdbPredicates匹配数据字段为string的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[glob](#glob9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.glob("NAME", "?h*g") +``` + +### between(deprecated) + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[between](#between9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.between("AGE", 10, 50) +``` + +### notBetween(deprecated) + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notBetween](#notbetween9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notBetween("AGE", 10, 50) +``` + +### greaterThan(deprecated) + +greaterThan(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThan](#greaterthan9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThan("AGE", 18) +``` + +### lessThan(deprecated) + +lessThan(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为valueType且value小于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThan](#lessthan9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThan("AGE", 20) +``` + +### greaterThanOrEqualTo(deprecated) + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThanOrEqualTo](#greaterthanorequalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThanOrEqualTo("AGE", 18) +``` + +### lessThanOrEqualTo(deprecated) + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThanOrEqualTo](#lessthanorequalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThanOrEqualTo("AGE", 20) +``` + +### orderByAsc(deprecated) + +orderByAsc(field: string): RdbPredicates + +配置谓词以匹配其值按升序排序的列。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByAsc](#orderbyasc9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByAsc("NAME") +``` + +### orderByDesc(deprecated) + +orderByDesc(field: string): RdbPredicates + +配置谓词以匹配其值按降序排序的列。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByDesc](#orderbydesc9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByDesc("AGE") +``` + +### distinct(deprecated) + +distinct(): RdbPredicates + +配置谓词以过滤重复记录并仅保留其中一个。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[distinct](#distinct9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回可用于过滤重复记录的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").distinct() +``` + +### limitAs(deprecated) + +limitAs(value: number): RdbPredicates + +设置最大数据记录数的谓词。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[limitAs](#limitas9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 最大数据记录数。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回可用于设置最大数据记录数的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").limitAs(3) +``` + +### offsetAs(deprecated) + +offsetAs(rowOffset: number): RdbPredicates + +配置RdbPredicates以指定返回结果的起始位置。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[offsetAs](#offsetas9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回具有指定返回结果起始位置的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").offsetAs(3) +``` + +### groupBy(deprecated) + +groupBy(fields: Array<string>): RdbPredicates + +配置RdbPredicates按指定列分组查询结果。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[groupBy](#groupby9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| fields | Array<string> | 是 | 指定分组依赖的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回分组查询列的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.groupBy(["AGE", "NAME"]) +``` + +### indexedBy(deprecated) + +indexedBy(field: string): RdbPredicates + +配置RdbPredicates以指定索引列。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[indexedBy](#indexedby9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 索引列的名称。 | + +**返回值**: + + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回具有指定索引列的RdbPredicates。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.indexedBy("SALARY_INDEX") +``` + +### in(deprecated) + +in(field: string, value: Array<ValueType>): RdbPredicates + +配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[in](#in9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.in("AGE", [18, 20]) +``` + +### notIn(deprecated) + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notIn](#notin9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## RdbStore(deprecated) + +提供管理关系数据库(RDB)方法的接口。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[RdbStoreV9](#rdbstorev99)替代。 + +在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 + +### insert(deprecated) + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +向目标表中插入一行数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Insert is failed"); + return; + } + console.log("Insert is successful, rowId = " + rowId); +}) +``` + +### insert(deprecated) + +insert(table: string, values: ValuesBucket):Promise<number> + +向目标表中插入一行数据,使用Promise异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket) +promise.then((rowId) => { + console.log("Insert is successful, rowId = " + rowId); +}).catch((status) => { + console.log("Insert is failed"); +}) +``` + +### batchInsert(deprecated) + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +向目标表中插入一组数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**示例:** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("batchInsert is failed, status = " + status); + return; + } + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert(deprecated) + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +向目标表中插入一组数据,使用Promise异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**示例:** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("batchInsert is failed, status = " + status); +}) +``` + +### update(deprecated) + +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, function (err, ret) { + if (err) { + console.info("Updated failed, err: " + err) + return + } + console.log("Updated row count: " + ret) +}) +``` + +### update(deprecated) + +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates) +promise.then(async (ret) => { + console.log("Updated row count: " + ret) +}).catch((err) => { + console.info("Updated failed, err: " + err) +}) +``` + +### delete(deprecated) + +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | **示例:** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.delete(predicates, function (err, rows) { if (err) { - console.info("Query failed, err: " + err) + console.info("Delete failed, err: " + err) return } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.log("Delete rows: " + rows) }) ``` -### query9+ +### delete(deprecated) -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> +delete(predicates: RdbPredicates):Promise<number> -根据指定条件查询数据库中的数据,使用Promise异步回调。 +根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 -**系统接口:** 此接口为系统接口。 +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-2)替代。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | **返回值**: | 类型 | 说明 | | -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| Promise<number> | Promise对象。返回受影响的行数。 | **示例:** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete(predicates) +promise.then((rows) => { + console.log("Delete rows: " + rows) }).catch((err) => { - console.info("Query failed, err: " + err) + console.info("Delete failed, err: " + err) }) ``` -### remoteQuery9+ +### query(deprecated) -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -根据指定条件查询远程设备数据库中的数据。使用callback异步回调。 +根据指定条件查询数据库中的数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-1)替代。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1715,33 +4049,34 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| device | string | 是 | 指定的远程设备的networkId。 | -| table | string | 是 | 指定的目标表名。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | | columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { if (err) { - console.info("Failed to remoteQuery, err: " + err) + console.info("Query failed, err: " + err) return } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }) ``` -### remoteQuery9+ +### query(deprecated) + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> +根据指定条件查询数据库中的数据,使用Promise异步回调。 -根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。 +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-2)替代。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1749,38 +4084,40 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| device | string | 是 | 指定的远程设备的networkId。 | -| table | string | 是 | 指定的目标表名。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | | columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | **返回值**: -| 类型 | 说明 | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSet对象。 | **示例:** -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` + ```js + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose") + let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) + }).catch((err) => { + console.info("Query failed, err: " + err) + }) + ``` -### querySql8+ +### querySql(deprecated) querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void 根据指定SQL语句查询数据库中的数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1803,13 +4140,17 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", }) ``` -### querySql8+ +### querySql(deprecated) querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1822,7 +4163,7 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | 类型 | 说明 | | -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSet对象。 | **示例:** @@ -1836,13 +4177,17 @@ promise.then((resultSet) => { }) ``` -### executeSql +### executeSql(deprecated) executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void 执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1865,13 +4210,17 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql +### executeSql(deprecated) executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> 执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1884,7 +4233,7 @@ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> | 类型 | 说明 | | -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** @@ -1898,19 +4247,23 @@ promise.then(() => { }) ``` -### beginTransaction8+ +### beginTransaction(deprecated) beginTransaction():void 在开始执行SQL语句之前,开始事务。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[beginTransaction](#begintransaction9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1925,19 +4278,23 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### commit8+ +### commit(deprecated) commit():void 提交已执行的SQL语句。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[commit](#commit9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1952,19 +4309,23 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### rollBack8+ +### rollBack(deprecated) rollBack():void 回滚已经执行的SQL语句。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[rollBack](#rollback9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { try { @@ -1984,131 +4345,19 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -以指定名称备份数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| destName | string | 是 | 指定数据库的备份文件名。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Backup failed, err: ' + err) - return - } - console.info('Backup success.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -以指定名称备份数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| destName | string | 是 | 指定数据库的备份文件名。 | - -**返回值**: - -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | - -**示例:** - -```js -let promiseBackup = rdbStore.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backup success.') -}).catch((err)=>{ - console.info('Backup failed, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -从指定的数据库备份文件恢复数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| srcName | string | 是 | 指定数据库的备份文件名。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Restore failed, err: ' + err) - return - } - console.info('Restore success.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -从指定的数据库备份文件恢复数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| srcName | string | 是 | 指定数据库的备份文件名。 | - -**返回值**: - -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | - -**示例:** - -```js -let promiseRestore = rdbStore.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restore success.') -}).catch((err)=>{ - console.info('Restore failed, err: ' + err) -}) -``` - -### setDistributedTables8+ +### setDistributedTables(deprecated) setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void 设置分布式列表,使用callback异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-1)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2129,15 +4378,19 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { }) ``` -### setDistributedTables8+ +### setDistributedTables(deprecated) setDistributedTables(tables: Array<string>): Promise<void> 设置分布式列表,使用Promise异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-2)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2149,7 +4402,7 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { | 类型 | 说明 | | -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** @@ -2162,15 +4415,19 @@ promise.then(() => { }) ``` -### obtainDistributedTableName8+ +### obtainDistributedTableName(deprecated) obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-1)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2192,15 +4449,19 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, }) ``` -### obtainDistributedTableName8+ +### obtainDistributedTableName(deprecated) obtainDistributedTableName(device: string, table: string): Promise<string> 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-2)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2213,7 +4474,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, | 类型 | 说明 | | -------- | -------- | -| Promise<string> | 指定Promise回调函数。如果操作成功,返回远程设备的分布式表名。 | +| Promise<string> | Promise对象。如果操作成功,返回远程设备的分布式表名。 | **示例:** @@ -2226,15 +4487,19 @@ promise.then((tableName) => { }) ``` -### sync8+ +### sync(deprecated) sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void 在设备之间同步数据, 使用callback异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-1)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2261,15 +4526,19 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul }) ``` -### sync8+ +### sync(deprecated) sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> 在设备之间同步数据,使用Promise异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-2)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2282,7 +4551,7 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul | 类型 | 说明 | | -------- | -------- | -| Promise<Array<[string, number]>> | 指定Promise回调函数,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | +| Promise<Array<[string, number]>> | Promise对象,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | **示例:** @@ -2300,15 +4569,17 @@ promise.then((result) =>{ }) ``` -### on('dataChange')8+ +### on('dataChange')(deprecated) on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[on](#ondatachange9)替代。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2333,15 +4604,17 @@ try { } ``` -### off('dataChange')8+ +### off('dataChange')(deprecated) off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void 从数据库中删除指定类型的指定观察者, 使用callback异步回调。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[off](#offdatachange9)替代。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2366,59 +4639,17 @@ try { } ``` -## StoreConfig +## StoreConfig(deprecated) 管理关系数据库配置。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 +**说明:** + +从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[StoreConfigV9](#storeconfigv99)替代。 + +**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | name | string | 是 | 数据库文件名。 | -| encrypt9+ | boolean | 否 | 指定数据库是否加密。
true:加密。
false:非加密。 | - -## ValueType - -用于表示允许的数据字段类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 - -| 类型 | 说明 | -| -------- | -------- | -| number | 表示值类型为数字。 | -| string | 表示值类型为字符。 | -| boolean | 表示值类型为布尔值。| - - -## ValuesBucket - -用于存储键值对的类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 - -| 键类型 | 值类型 | -| -------- | -------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | - -## SyncMode8+ - -指数据库同步模式。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 - -| 名称 | 默认值 | 说明 | -| -------- | ----- |----- | -| SYNC_MODE_PUSH | 0 | 表示数据从本地设备推送到远程设备。 | -| SYNC_MODE_PULL | 1 | 表示数据从远程设备拉至本地设备。 | - -## SubscribeType8+ - -描述订阅类型。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 -| 名称 | 默认值 | 说明 | -| -------- | ----- |---- | -| SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md index 19648104db323d6f2c89f71ce52e027cf317e7c8..33438f5bec8daf8bdb3225cc1f5c736bc97ffea6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @@ -6,7 +6,545 @@ > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -## 使用说明 +## ResultSetV99+ + +提供通过查询数据库生成的数据库结果集的访问方法。 + +### 使用说明 + +需要通过[RdbStoreV9.query()](js-apis-data-rdb.md#query)获取resultSetV9对象。 + +```js +import dataRdb from '@ohos.data.rdb'; +let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +predicatesV9.equalTo("AGE", 18); +let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSetV9) => { + console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); +}); +``` + +### 属性9+ + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | 是 | 获取结果集中所有列的名称。 | +| columnCount | number | 是 | 获取结果集中的列数。 | +| rowCount | number | 是 | 获取结果集中的行数。 | +| rowIndex | number | 是 | 获取结果集当前行的索引。 | +| isAtFirstRow | boolean | 是 | 检查结果集是否位于第一行。 | +| isAtLastRow | boolean | 是 | 检查结果集是否位于最后一行。 | +| isEnded | boolean | 是 | 检查结果集是否位于最后一行之后。 | +| isStarted | boolean | 是 | 检查指针是否移动过。 | +| isClosed | boolean | 是 | 检查当前结果集是否关闭。 | + +### getColumnIndex9+ + +getColumnIndex(columnName: string): number + +根据指定的列名获取列索引。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | 是 | 表示结果集中指定列的名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| number | 返回指定列的索引。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +resultSetV9.goToFirstRow(); +const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); +const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); +const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); +const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); + ``` + +### getColumnName9+ + +getColumnName(columnIndex: number): string + +根据指定的列索引获取列名。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | 是 | 表示结果集中指定列的索引。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| string | 返回指定列的名称。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const id = resultSetV9.getColumnName(0); +const name = resultSetV9.getColumnName(1); +const age = resultSetV9.getColumnName(2); + ``` + +### goTo9+ + +goTo(offset:number): boolean + +向前或向后转至结果集的指定行,相对于其当前位置偏移。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | 是 | 表示相对于当前位置的偏移量。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoto.then((resultSetV9) => { + resultSetV9.goTo(1); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToRow9+ + +goToRow(position: number): boolean + +转到结果集的指定行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| position | number | 是 | 表示要移动到的指定位置。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygotorow.then((resultSetV9) => { + resultSetV9.goToRow(5); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToFirstRow9+ + +goToFirstRow(): boolean + + +转到结果集的第一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoFirst.then((resultSetV9) => { + resultSetV9.goToFirstRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToLastRow9+ + +goToLastRow(): boolean + +转到结果集的最后一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoLast.then((resultSetV9) => { + resultSetV9.goToLastRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToNextRow9+ + +goToNextRow(): boolean + +转到结果集的下一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoNext.then((resultSetV9) => { + resultSetV9.goToNextRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToPreviousRow9+ + +goToPreviousRow(): boolean + +转到结果集的上一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoPrev.then((resultSetV9) => { + resultSetV9.goToPreviousRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### getBlob9+ + +getBlob(columnIndex: number): Uint8Array + +以字节数组的形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------------------- | +| Uint8Array | 以字节数组的形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); + ``` + +### getString9+ + +getString(columnIndex: number): string + +以字符串形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| string | 以字符串形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); + ``` + +### getLong9+ + +getLong(columnIndex: number): number + +以Long形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------------- | +| number | 以Long形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); + ``` + +### getDouble9+ + +getDouble(columnIndex: number): number + +以double形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| number | 以double形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); + ``` + +### isColumnNull9+ + +isColumnNull(columnIndex: number): boolean + +检查当前行中指定列的值是否为null。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------------------- | +| boolean | 如果当前行中指定列的值为null,则返回true,否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); + ``` + +### close9+ + +close(): void + +关闭结果集。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + + ```js +let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promiseClose.then((resultSetV9) => { + resultSetV9.close(); +}).catch((err) => { + console.log('resultset close failed'); +}); + ``` + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +## ResultSet(deprecated) + +提供通过查询数据库生成的数据库结果集的访问方法。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[ResultSetV9](#resultsetv99)替代。 + +### 使用说明 需要通过[RdbStore.query()](js-apis-data-rdb.md#query)获取resultSet对象。 @@ -21,13 +559,13 @@ promise.then((resultSet) => { }); ``` -## ResultSet - -提供通过查询数据库生成的数据库结果集的访问方法。 +### 属性(deprecated) -### 属性 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[属性](#属性9)替代。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -41,13 +579,17 @@ promise.then((resultSet) => { | isStarted | boolean | 是 | 检查指针是否移动过。 | | isClosed | boolean | 是 | 检查当前结果集是否关闭。 | -### getColumnIndex +### getColumnIndex(deprecated) getColumnIndex(columnName: string): number 根据指定的列名获取列索引。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnIndex](#getcolumnindex9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -71,13 +613,17 @@ getColumnIndex(columnName: string): number const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName +### getColumnName(deprecated) getColumnName(columnIndex: number): string 根据指定的列索引获取列名。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnName](#getcolumnname9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -99,13 +645,17 @@ getColumnName(columnIndex: number): string const age = resultSet.getColumnName(2); ``` -### goTo +### goTo(deprecated) goTo(offset:number): boolean 向前或向后转至结果集的指定行,相对于其当前位置偏移。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goTo](#goto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -124,7 +674,7 @@ goTo(offset:number): boolean ```js let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoto.then((resultSet) { + promisequerygoto.then((resultSet) => { resultSet.goTo(1); resultSet.close(); }).catch((err) => { @@ -132,13 +682,17 @@ goTo(offset:number): boolean }); ``` -### goToRow +### goToRow(deprecated) goToRow(position: number): boolean 转到结果集的指定行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToRow](#gotorow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -157,7 +711,7 @@ goToRow(position: number): boolean ```js let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygotorow.then((resultSet) { + promisequerygotorow.then((resultSet) => { resultSet.goToRow(5); resultSet.close(); }).catch((err) => { @@ -165,14 +719,17 @@ goToRow(position: number): boolean }); ``` -### goToFirstRow +### goToFirstRow(deprecated) goToFirstRow(): boolean - 转到结果集的第一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToFirstRow](#gotofirstrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -185,7 +742,7 @@ goToFirstRow(): boolean ```js let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoFirst.then((resultSet) { + promisequerygoFirst.then((resultSet) => { resultSet.goToFirstRow(); resultSet.close(); }).catch((err) => { @@ -193,13 +750,17 @@ goToFirstRow(): boolean }); ``` -### goToLastRow +### goToLastRow(deprecated) goToLastRow(): boolean 转到结果集的最后一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToLastRow](#gotolastrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -212,7 +773,7 @@ goToLastRow(): boolean ```js let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoLast.then((resultSet) { + promisequerygoLast.then((resultSet) => { resultSet.goToLastRow(); resultSet.close(); }).catch((err) => { @@ -220,13 +781,17 @@ goToLastRow(): boolean }); ``` -### goToNextRow +### goToNextRow(deprecated) goToNextRow(): boolean 转到结果集的下一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToNextRow](#gotonextrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -239,7 +804,7 @@ goToNextRow(): boolean ```js let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoNext.then((resultSet) { + promisequerygoNext.then((resultSet) => { resultSet.goToNextRow(); resultSet.close(); }).catch((err) => { @@ -247,13 +812,17 @@ goToNextRow(): boolean }); ``` -### goToPreviousRow +### goToPreviousRow(deprecated) goToPreviousRow(): boolean 转到结果集的上一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToPreviousRow](#gotopreviousrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -266,7 +835,7 @@ goToPreviousRow(): boolean ```js let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoPrev.then((resultSet) { + promisequerygoPrev.then((resultSet) => { resultSet.goToPreviousRow(); resultSet.close(); }).catch((err) => { @@ -274,13 +843,17 @@ goToPreviousRow(): boolean }); ``` -### getBlob +### getBlob(deprecated) getBlob(columnIndex: number): Uint8Array 以字节数组的形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getBlob](#getblob9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -300,13 +873,17 @@ getBlob(columnIndex: number): Uint8Array const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString +### getString(deprecated) getString(columnIndex: number): string 以字符串形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getString](#getstring9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -326,13 +903,17 @@ getString(columnIndex: number): string const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong +### getLong(deprecated) getLong(columnIndex: number): number 以Long形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getLong](#getlong9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -352,13 +933,17 @@ getLong(columnIndex: number): number const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble +### getDouble(deprecated) getDouble(columnIndex: number): number 以double形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getDouble](#getdouble9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -378,13 +963,17 @@ getDouble(columnIndex: number): number const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull +### isColumnNull(deprecated) isColumnNull(columnIndex: number): boolean 检查当前行中指定列的值是否为null。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[isColumnNull](#iscolumnnull9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -404,20 +993,24 @@ isColumnNull(columnIndex: number): boolean const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close +### close(deprecated) close(): void 关闭结果集。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**说明:** + +从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[close](#close9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promiseClose.then((resultSet) { + promiseClose.then((resultSet) => { resultSet.close(); }).catch((err) => { console.log('resultset close failed'); diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md index 2110b8065f4602a382bb1e1b339c9f968377239c..064669b6e3100d19ace8f95bb6656c96d598947d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md @@ -24,8 +24,8 @@ import data_storage from '@ohos.data.storage'; | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ---------------- | -------- | ---- | ---- | ------------------------------------- | -| MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,需小于80字节。 | -| MAX_VALUE_LENGTH | string | 是 | 否 | value的最大长度限制,需小于8192字节。 | +| MAX_KEY_LENGTH | number | 是 | 否 | key的最大长度限制,需小于80字节。 | +| MAX_VALUE_LENGTH | number | 是 | 否 | value的最大长度限制,需小于8192字节。 | ## data_storage.getStorageSync diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md b/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md similarity index 90% rename from zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md rename to zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md index 1508fd7c192fc20c0c38699176d3fe0b6c1206c3..9cf076295258de43d1dafa6938320b885bad9c74 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -9,7 +9,7 @@ ## 导入模块 ``` -import defaultAppMgr from '@ohos.bundle.defaultAppManager' +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; ``` ## defaultAppMgr.ApplicationType @@ -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)); @@ -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)); @@ -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)); @@ -170,7 +173,9 @@ 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; @@ -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.DefaultAppManager **系统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.DefaultAppManager **系统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.DefaultAppManager **系统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.DefaultAppManager **系统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.DefaultAppManager **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -525,6 +557,7 @@ resetDefaultApplication(type: string, callback: AsyncCallback\) : void; **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-deque.md b/zh-cn/application-dev/reference/apis/js-apis-deque.md index dd35648cacc70ea65dfb26aba8629e44c48d64d9..4fb4fcdb83c8df3a3c661a2abf7d8fe97f84894a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-deque.md +++ b/zh-cn/application-dev/reference/apis/js-apis-deque.md @@ -88,9 +88,10 @@ deque.insertFront(1); let b = [1, 2, 3]; deque.insertFront(b); let c = {name : "Dylon", age : "13"}; +deque.insertFront(c); deque.insertFront(false); try { - deque.insertFront.bind({}, "b")(); + deque.insertFront.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -127,9 +128,10 @@ deque.insertEnd(1); let b = [1, 2, 3]; deque.insertEnd(b); let c = {name : "Dylon", age : "13"}; +deque.insertEnd(c); deque.insertEnd(false); try { - deque.insertEnd.bind({}, "b")(); + deque.insertEnd.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -171,7 +173,7 @@ let result = deque.has("squirrel"); deque.insertFront("squirrel"); let result1 = deque.has("squirrel"); try { - deque.has.bind({}, "b")(); + deque.has.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -210,7 +212,7 @@ deque.insertFront(2); deque.insertFront(4); let result = deque.popFirst(); try { - deque.popFirst.bind({})(); + deque.popFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -249,7 +251,7 @@ deque.insertFront(2); deque.insertFront(4); let result = deque.popLast(); try { - deque.popLast.bind({})(); + deque.popLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -301,7 +303,7 @@ deque.forEach((value, index) => { try { deque.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -339,7 +341,7 @@ deque.insertFront(5); deque.insertFront(4); let result = deque.getFirst(); try { - deque.getFirst.bind({})(); + deque.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -377,7 +379,7 @@ deque.insertFront(5); deque.insertFront(4); let result = deque.getLast(); try { - deque.getLast.bind({})(); + deque.getLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -426,7 +428,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - deque[Symbol.iterator].bind({})(); + deque[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-effectKit.md b/zh-cn/application-dev/reference/apis/js-apis-effectKit.md index b6384526fa5648a24780890d5a8aaed46283f458..7231f0e6ed98c792dfdc695ae7fbad2bb86e07a4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-effectKit.md +++ b/zh-cn/application-dev/reference/apis/js-apis-effectKit.md @@ -4,7 +4,7 @@ 该模块提供以下图像效果相关的常用功能: -- [Filter](#filter):效果链,指各种图像处理效果的集合链表。 +- [Filter](#filter):效果类,用于添加指定效果到图像源。 - [Color](#color):颜色类,用于保存取色的结果。 - [ColorPicker](#colorpicker):智能取色器。 @@ -181,6 +181,7 @@ getMainColorSync(): Color let color = colorPicker.getMainColorSync(); console.log('get main color =' + color); ``` +![zh-ch_image_Main_Color.png](figures/zh-ch_image_Main_Color.png) ## Filter @@ -204,7 +205,7 @@ blur(radius: number): Filter | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [Filter](#filter) | 返回效果链表头。 | +| [Filter](#filter) | 返回已添加的图像效果。 | **示例:** @@ -221,6 +222,7 @@ image.createPixelMap(color, opts).then((pixelMap) => { } }) ``` +![zh-ch_image_Add_Blur.png](figures/zh-ch_image_Add_Blur.png) ### brightness @@ -240,7 +242,7 @@ brightness(bright: number): Filter | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [Filter](#filter) | 返回效果链表头。 | +| [Filter](#filter) | 返回已添加的图像效果。 | **示例:** @@ -257,6 +259,7 @@ image.createPixelMap(color, opts).then((pixelMap) => { } }) ``` +![zh-ch_image_Add_Brightness.png](figures/zh-ch_image_Add_Brightness.png) ### grayscale @@ -270,7 +273,7 @@ grayscale(): Filter | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [Filter](#filter) | 返回效果链表头。 | +| [Filter](#filter) | 返回已添加的图像效果。 | **示例:** @@ -286,10 +289,11 @@ image.createPixelMap(color, opts).then((pixelMap) => { } }) ``` +![zh-ch_image_Add_Grayscale.png](figures/zh-ch_image_Add_Grayscale.png) ### getPixelMap -getPixelMap(): image.PixelMap +getPixelMap(): [image.PixelMap](js-apis-image.md#pixelmap7) 获取已添加链表效果的源图像的image.PixelMap。 @@ -299,7 +303,7 @@ getPixelMap(): image.PixelMap | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [image.PixelMap](js-apis-image.md#pixelmap7) | 已添加链表效果的源图像的image.PixelMap。 | +| [image.PixelMap](js-apis-image.md#pixelmap7) | 已添加效果的源图像的image.PixelMap。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-extension-context.md index 1425107f97c162746ce4d71025124660ee2c131d..aab5d3f7ffefbbb3a778e2150d92cbd2c069c525 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-extension-context.md @@ -31,7 +31,7 @@ ExtensionContext主要用于查询所属Extension的信息、Module的配置信 三个Module内都定义一个相同名称的ServiceExtension: ``` js -import ServiceExtension from '@ohos.application.ServiceExtensionAbility' +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' import Want from '@ohos.application.Want' export default class TheServiceExtension extends ServiceExtension { onCreate(want:Want) { @@ -61,7 +61,7 @@ export default class TheServiceExtension extends ServiceExtension { 在entry的MainAbility的onCreate回调内启动ServiceExtension ``` js -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.app.ability.Ability' export default class MainAbility extends Ability { onCreate(want, launchParam) { console.log("[Demo] MainAbility onCreate"); diff --git a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md index 5d131e1dfcab25145571f4b9b41e615965c969d2..da0b5ea904f03fd13c5a39a04654d2c03560cdc9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md @@ -52,6 +52,9 @@ featureAbility.startAbility( uri: "" }, }, + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } ); ``` @@ -268,6 +271,9 @@ featureAbility.terminateSelfWithResult( } }, }, + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } ); ``` @@ -345,7 +351,11 @@ hasWindowFocus(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.hasWindowFocus() +featureAbility.hasWindowFocus( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.hasWindowFocus7+ @@ -389,7 +399,11 @@ getWant(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.getWant() +featureAbility.getWant( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.getWant @@ -455,7 +469,11 @@ terminateSelf(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.terminateSelf() +featureAbility.terminateSelf( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.terminateSelf7+ @@ -583,7 +601,7 @@ var connId = featureAbility.connectAbility( }, ); var result = featureAbility.disconnectAbility(connId, - (error,data) => { + (error, data) => { console.log('featureAbilityTest DisConnectJsSameBundleName result errCode : ' + error.code + " data: " + data) }, ); @@ -660,7 +678,11 @@ getWindow(callback: AsyncCallback\): void **示例:** ```javascript -featureAbility.getWindow() +featureAbility.getWindow( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.getWindow7+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md index 38b19761bb45edb344fac038c4dd78e11a075d82..80e01c8b59697f412eb6f10f1a8b0f844fae0b2f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @@ -77,10 +77,12 @@ createFileAccessHelper(context: Context, wants: Array<Want>) : FileAccessH let fileAccesssHelper = null; // wantInfo 从getFileAccessAbilityInfo()获取 // 创建只连接媒体库服务的helper对象 - let wantInfo = { - "bundleName": "com.ohos.medialibrary.medialibrarydata", - "abilityName": "FileExtensionAbility", - } + let wantInfos = [ + { + "bundleName": "com.ohos.medialibrary.medialibrarydata", + "abilityName": "FileExtensionAbility", + }, + ] try { fileAccesssHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); if (!fileAccesssHelper) @@ -211,7 +213,7 @@ listFile(filter?: Filter) : FileIterator let fileIterator = rootInfo.listFile(); // 含过滤器实现的listFile // let fileIterator = rootInfo.listFile(filter); - if (fileIterator) { + if (!fileIterator) { console.error("listFile interface returns an undefined object"); return; } @@ -261,7 +263,7 @@ scanFile(filter?: Filter) : FileIterator let fileIterator = rootInfo.scanFile(); // 含过滤器实现的scanFile // let fileIterator = rootInfo.scanFile(filter); - if (fileIterator) { + if (!fileIterator) { console.error("scanFile interface returns undefined object"); return; } @@ -311,7 +313,7 @@ listFile(filter?: Filter) : FileIterator let fileIterator = fileInfoDir.listFile(); // 含过滤器实现的listFile // let fileIterator = rootInfo.listFile(filter); - if (fileIterator) { + if (!fileIterator) { console.error("listFile interface returns an undefined object"); return; } @@ -362,7 +364,7 @@ scanFile(filter?: Filter) : FileIterator; let fileIterator = fileInfoDir.scanFile(); // 含过滤器实现的scanFile // let fileIterator = rootInfo.scanFile(filter); - if (fileIterator) { + if (!fileIterator) { console.error("scanFile interface returns an undefined object"); return; } @@ -451,12 +453,12 @@ mkDir(parentUri: string, displayName: string) : Promise<string> let dirName = "dirTest" let dirUri = null; try { - dirUri = await fileAccessHelper.mkDir(sourceUri, displayName) + dirUri = await fileAccessHelper.mkDir(sourceUri, dirName) if (!dirUri) { console.error("mkDir return undefined object"); return; } - console.log("mkDir sucess, fileUri: " + JSON.stringify(fileUri)); + console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri)); } catch (error) { console.error("mkDir failed, error " + error); }; 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 25d4499022f4a77670b49ac4f79ddae7d27316b1..9ba948beaccf86693e6d13fe257ab5554212659b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -68,7 +68,7 @@ stat(path: string): Promise<Stat> ```js let filePath = pathDir + "test.txt"; fileio.stat(filePath).then(function(stat){ - console.info("getFileInfo succeed:"+ JSON.stringify(stat)); + console.info("getFileInfo succeed, the size of file is " + stat.size); }).catch(function(err){ console.info("getFileInfo failed with error:"+ err); }); @@ -153,7 +153,7 @@ opendir(path: string): Promise<Dir> ```js let dirPath = pathDir + "/testDir"; fileio.opendir(dirPath).then(function(dir){ - console.info("opendir succeed:"+ JSON.stringify(dir)); + console.info("opendir succeed"); }).catch(function(err){ console.info("opendir failed with error:"+ err); }); @@ -1178,7 +1178,7 @@ fstat(fd: number): Promise<Stat> let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); fileio.fstat(fd).then(function(stat){ - console.info("fstat succeed:"+ JSON.stringify(stat)); + console.info("fstat succeed, the size of file is "+ stat.size); }).catch(function(err){ console.info("fstat failed with error:"+ err); }); @@ -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:"+ JSON.stringify(stat)); + 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); }); @@ -3166,7 +3166,7 @@ read(): Promise<Dirent> ```js dir.read().then(function (dirent){ - console.log("read succeed:"+JSON.stringify(dirent)); + console.log("read succeed, the name of dirent is " + dirent.name); }).catch(function(err){ console.info("read failed with error:"+ err); }); @@ -3193,7 +3193,7 @@ read(callback: AsyncCallback<Dirent>): void dir.read(function (err, dirent) { if (dirent) { // do something - console.log("read succeed:"+JSON.stringify(dirent)); + console.log("read succeed, the name of file is " + dirent.name); } }); ``` 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..571573a02743705f0d223670d74e4dc006124734 --- /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 upgradeFlag = freeInstall.UpgradeFlag.GET_PACK_INFO_ALL; +try { + freeInstall.getBundlePackInfo(bundleName, upgradeFlag, (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 upgradeFlag = freeInstall.UpgradeFlag.GET_PACK_INFO_ALL; +try { + freeInstall.getBundlePackInfo(bundleName, upgradeFlag).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 new file mode 100644 index 0000000000000000000000000000000000000000..b0e51a6b414bbdb2b3d6f23ffd3559eae266f144 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -0,0 +1,1279 @@ +# 位置服务 + +位置服务提供GNSS定位、网络定位、地理编码、逆地理编码、国家码和地理围栏等基本功能。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +```ts +import geoLocationManager from '@ohos.geoLocationManager'; +``` + + +## geoLocationManager.on('countryCodeChange') + +on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; + +订阅国家码信息变化事件。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示订阅国家码信息变化事件。 | + | callback | Callback<[CountryCode](#countrycode)> | 是 | 接收国家码信息上报。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + geoLocationManager.on('countryCodeChange', callback); + ``` + + +## geoLocationManager.off('countryCodeChange') + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; + +取消订阅国家码变化事件。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示取消订阅国家码信息变化事件。 | + | callback | Callback<[CountryCode](#countrycode)> | 是 | 接收国家码信息上报。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + geoLocationManager.on('countryCodeChange', callback); + geoLocationManager.off('countryCodeChange', callback); + ``` + + +## geoLocationManager.enableLocation + +enableLocation(callback: AsyncCallback<void>): void; + +打开位置服务,使用callback回调异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收错误码信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocation((err, data) => { + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.enableLocation + +enableLocation(): Promise<void> + +打开位置服务,使用Promise方式异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 返回错误码信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocation().then((result) => { + console.log('promise, enableLocation succeed'); + }) + .catch((error) => { + console.log('promise, enableLocation: error=' + JSON.stringify(error)); + }); + ``` + +## geoLocationManager.disableLocation + +disableLocation(callback: AsyncCallback<void>): void; + +关闭位置服务,使用callback回调异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收错误码的回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocation((err, data) => { + if (err) { + console.log('disableLocation: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.disableLocation + +disableLocation(): Promise<void> + +关闭位置服务,使用Promise方式异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 返回错误码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocation().then((result) => { + console.log('promise, disableLocation succeed'); + }) + .catch((error) => { + console.log('promise, disableLocation: error=' + JSON.stringify(error)); + }); + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>): void; + +查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype)| 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + | callback | AsyncCallback<boolean> | 是 | 表示用户是否同意定位服务隐私申明。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.isLocationPrivacyConfirmed(1, (err, result) => { + if (err) { + console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); + } + if (result) { + console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type : LocationPrivacyType,): Promise<boolean>; + +查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<boolean> | 表示用户是否同意定位服务隐私申明。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.isLocationPrivacyConfirmed(1).then((result) => { + console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); + }); + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<void>): void; + +设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | + | callback | AsyncCallback<void> | 是 | 接收错误码信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.setLocationPrivacyConfirmStatus(1, true, (err, result) => { + if (err) { + console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean): Promise<void>; + +设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 接收错误码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.setLocationPrivacyConfirmStatus(1, true).then((result) => { + console.log('promise, setLocationPrivacyConfirmStatus succeed'); + }) + .catch((error) => { + console.log('promise, disableLocation: error=' + JSON.stringify(error)); + }); + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(callback: AsyncCallback<CountryCode>): void; + +查询当前的国家码。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[CountryCode](#countrycode)> | 是 | 用来接收国家码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(): Promise<CountryCode>; + +查询当前的国家码。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<[CountryCode](#countrycode)> | 返回国家码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + ``` + + +## geoLocationManager.enableLocationMock + +enableLocationMock(callback: AsyncCallback<void>): void; + +使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocationMock((err, result) => { + if (err) { + console.log('enableLocationMock: err=' + JSON.stringify(err)); + } + }); + ``` + +## geoLocationManager.enableLocationMock + +enableLocationMock(): Promise<void>; + +使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocationMock() + .then((result) => { + console.log('promise, enableLocationMock: succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(callback: AsyncCallback<void>): void; + +去使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocationMock((err, result) => { + if (err) { + console.log('disableLocationMock: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(): Promise<void>; + +去使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocationMock() + .then((result) => { + console.log('promise, disableLocationMock succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>): void; + +设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | config | [LocationMockConfig](#locationmockconfig) | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations": locations}; + geoLocationManager.setMockedLocations(config, (err, data) => { + if (err) { + console.log('setMockedLocations: err=' + JSON.stringify(err)); + } + }); + ``` + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig): Promise<void>; + +设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | config | [LocationMockConfig](#locationmockconfig) | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations":locations}; + geoLocationManager.setMockedLocations(config) + .then((result) => { + console.log('promise, setMockedLocations succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(callback: AsyncCallback<void>): void; + +使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableReverseGeocodingMock((err, data) => { + if (err) { + console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(): Promise<void>; + +使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableReverseGeocodingMock() + .then((result) => { + console.log('promise, enableReverseGeocodingMock succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(callback: AsyncCallback<void>): void; + +去使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableReverseGeocodingMock((err, result) => { + if (err) { + console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(): Promise<void>; + +去使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableReverseGeocodingMock() + .then((result) => { + console.log('promise, disableReverseGeocodingMock succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>): void; + +设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | mockInfos | Array<[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)> | 是 | 指示逆地理编码模拟功能的配置参数数组。逆地理编码模拟功能的配置参数包含了一个位置和一个地名。 | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geoLocationManager.setReverseGeocodingMockInfo(mockInfos, (err, data) => { + if (err) { + console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): Promise<void>; + +设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | mockInfos | Array<[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)> | 是 | 指示逆地理编码模拟功能的配置信息数组。逆地理编码模拟功能的配置信息包含了一个位置和一个地名。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geoLocationManager.setReverseGeocodingMockInfo(mockInfos) + .then((result) => { + console.log('promise, setReverseGeocodingMockInfo succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); + } + }); + ``` + + +## LocationRequestPriority + +位置请求中位置信息优先级设置。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x200 | 表示未设置优先级。 | +| ACCURACY | 0x201 | 表示精度优先。 | +| LOW_POWER | 0x202 | 表示低功耗优先。 | +| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | + + +## LocationRequestScenario + + 位置请求中定位场景设置。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x300 | 表示未设置场景信息。 | +| NAVIGATION | 0x301 | 表示导航场景。 | +| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | +| CAR_HAILING | 0x303 | 表示打车场景。 | +| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | +| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | + + +## ReverseGeoCodeRequest + +逆地理编码请求接口。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 | +| maxItems | number | 否 | 指定返回位置信息的最大个数。 | + + +## GeoCodeRequest + +地理编码请求接口。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | +| maxItems | number | 否 | 表示返回位置信息的最大个数。 | +| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | +| minLongitude | number | 否 | 表示最小经度信息。 | +| maxLatitude | number | 否 | 表示最大纬度信息。 | +| maxLongitude | number | 否 | 表示最大经度信息。 | + + +## GeoAddress + +地理编码类型。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 | +| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| placeName | string | 否 | 表示地区信息。 | +| countryCode | string | 否 | 表示国家码信息。 | +| countryName | string | 否 | 表示国家信息。 | +| administrativeArea | string | 否 | 表示省份区域信息。 | +| subAdministrativeArea | string | 否 | 表示表示子区域信息。 | +| locality | string | 否 | 表示城市信息。 | +| subLocality | string | 否 | 表示子城市信息。 | +| roadName | string | 否 | 表示路名信息。 | +| subRoadName | string | 否 | 表示子路名信息。 | +| premises | string | 否 | 表示门牌号信息。 | +| postalCode | string | 否 | 表示邮政编码信息。 | +| phoneNumber | string | 否 | 表示联系方式信息。 | +| addressUrl | string | 否 | 表示位置信息附件的网址信息。 | +| descriptions | Array<string> | 否 | 表示附加的描述信息。 | +| descriptionsSize | number | 否 | 表示附加的描述信息数量。 | +| isFromMock | Boolean | 否 | 表示地名信息是否来自于逆地理编码模拟功能。 | + + +## LocationRequest + +位置信息请求类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 | +| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 | +| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 | +| maxAccuracy | number | 否 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | + + +## CurrentLocationRequest + +当前位置信息请求类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 | +| maxAccuracy | number | 否 | 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | +| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | + + +## SatelliteStatusInfo + +卫星状态信息。 + +**系统能力**:SystemCapability.Location.Location.Gnss + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | 是 | 表示卫星个数。 | +| satelliteIds | Array<number> | 是 | 表示每个卫星的ID,数组类型。 | +| carrierToNoiseDensitys | Array<number> | 是 | 表示载波噪声功率谱密度比,即cn0。 | +| altitudes | Array<number> | 是 | 表示高程信息。 | +| azimuths | Array<number> | 是 | 表示方位角。 | +| carrierFrequencies | Array<number> | 是 | 表示载波频率。 | + + +## CachedGnssLocationsRequest + +请求订阅GNSS缓存位置上报功能接口的配置参数。 + +**系统能力**:SystemCapability.Location.Location.Gnss + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | +| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | + + +## Geofence + +GNSS围栏的配置参数。目前只支持圆形围栏。 + +**系统能力**:SystemCapability.Location.Location.Geofence + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude | number | 是 | 表示纬度。 | +| longitude | number | 是 | 表示经度。 | +| radius | number | 是 | 表示圆形围栏的半径。 | +| expiration | number | 是 | 围栏存活的时间,单位是毫秒。 | + + +## GeofenceRequest + +请求添加GNSS围栏消息中携带的参数,包括定位优先级、定位场景和围栏信息。 + +**系统能力**:SystemCapability.Location.Location.Geofence + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 表示位置信息优先级。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | +| geofence | [Geofence](#geofence) | 是 | 表示围栏信息。 | + + +## LocationPrivacyType + +定位服务隐私协议类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| OTHERS | 0 | 其他场景。 | +| STARTUP | 1 | 开机向导场景下的隐私协议。 | +| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 | + + +## LocationCommand + +扩展命令结构体。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | +| command | string | 是 | 扩展命令字符串。 | + + +## Location + +位置信息类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 是 | 表示经度信息,正值表示东经,负值表是西经。 | +| altitude | number | 是 | 表示高度信息,单位米。 | +| accuracy | number | 是 | 表示精度信息,单位米。 | +| speed | number | 是 | 表示速度信息,单位米每秒。 | +| timeStamp | number | 是 | 表示位置时间戳,UTC格式。 | +| direction | number | 是 | 表示航向信息。 | +| timeSinceBoot | number | 是 | 表示位置时间戳,开机时间格式。 | +| additions | Array<string> | 否 | 附加信息。 | +| additionSize | number | 否 | 附加信息数量。 | +| isFromMock | Boolean | 否 | 表示位置信息是否来自于位置模拟功能。 | + + +## ReverseGeocodingMockInfo + +逆地理编码模拟功能的配置信息,包含一个位置信息和一个地名信息。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 表示经纬度信息。 | +| geoAddress | [GeoAddress](#geoaddress) | 是 | 表示地名信息。 | + + +## LocationMockConfig + +位置模拟功能的配置参数,包含了模拟位置上报的时间间隔和模拟位置数组。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| timeInterval | number | 是 | 表示模拟位置上报的时间间隔,单位是秒。 | +| locations | Array<Location> | 是 | 表示模拟位置数组。 | + + +## CountryCode + +国家码信息结构体,包含国家码字符串和国家码的来源信息。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| country | string | 是 | 表示国家码字符串。 | +| type | [CountryCodeType](#countrycodetype)| 是 | 表示国家码信息来源。 | + + +## CountryCodeType + +国家码来源类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | 从全球化模块的语言配置信息中获取到的国家码。 | +| COUNTRY_CODE_FROM_SIM | 2 | 从SIM卡中获取到的国家码。 | +| COUNTRY_CODE_FROM_LOCATION | 3 | 基于用户的位置信息,通过逆地理编码查询到的国家码。 | +| COUNTRY_CODE_FROM_NETWORK | 4 | 从蜂窝网络注册信息中获取到的国家码。 | \ No newline at end of file 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 3cd5bb1b94919b8e48c4b2c8b215254963bd05aa..ab2399b1884ecb3a015e2c25794c485b284d7260 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -8,15 +8,15 @@ ## 导入模块 -```js +```ts import geolocation from '@ohos.geolocation'; ``` ## geolocation.on('locationChange') -on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -开启位置变化订阅,并发起定位请求。 +开启位置变化订阅,并发起定位请求。定位结果按照[LocationRequest](#locationrequest)的属性进行上报, **需要权限**:ohos.permission.LOCATION @@ -27,14 +27,15 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 | - | request | LocationRequest | 是 | 设置位置请求参数。 | + | request | [LocationRequest](#locationrequest) | 是 | 设置位置请求参数。 | | callback | Callback<[Location](#location)> | 是 | 接收位置变化状态变化监听。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -45,7 +46,7 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ## geolocation.off('locationChange') -off(type: 'locationChange', callback?: Callback<Location>) : void +off(type: 'locationChange', callback?: Callback<Location>): void 关闭位置变化订阅,并删除对应的定位请求。 @@ -63,7 +64,8 @@ off(type: 'locationChange', callback?: Callback<Location>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -75,7 +77,7 @@ off(type: 'locationChange', callback?: Callback<Location>) : void ## geolocation.on('locationServiceState') -on(type: 'locationServiceState', callback: Callback<boolean>) : void +on(type: 'locationServiceState', callback: Callback<boolean>): void 订阅位置服务状态变化。 @@ -93,7 +95,8 @@ on(type: 'locationServiceState', callback: Callback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } @@ -103,7 +106,7 @@ on(type: 'locationServiceState', callback: Callback<boolean>) : void ## geolocation.off('locationServiceState') -off(type: 'locationServiceState', callback?: Callback<boolean>) : void; +off(type: 'locationServiceState', callback?: Callback<boolean>): void; 取消订阅位置服务状态变化。 @@ -121,7 +124,8 @@ off(type: 'locationServiceState', callback?: Callback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } @@ -132,7 +136,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>) : void; ## geolocation.on('cachedGnssLocationsReporting')8+ -on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; +on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; 订阅缓存GNSS定位结果上报事件。 @@ -145,13 +149,14 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 | - | request | CachedGnssLocationsRequest | 是 | GNSS缓存功能配置参数 | + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | 是 | GNSS缓存功能配置参数 | | callback | Callback<boolean> | 是 | 接收GNSS缓存位置上报。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -162,7 +167,7 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca ## geolocation.off('cachedGnssLocationsReporting')8+ -off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; +off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; 取消订阅缓存GNSS定位结果上报事件。 @@ -180,7 +185,8 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -192,7 +198,7 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati ## geolocation.on('gnssStatusChange')8+ -on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; +on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; 订阅GNSS卫星状态信息上报事件。 @@ -205,12 +211,13 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : vo | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<SatelliteStatusInfo> | 是 | 接收GNSS卫星状态信息上报。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 是 | 接收GNSS卫星状态信息上报。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -220,7 +227,7 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : vo ## geolocation.off('gnssStatusChange')8+ -off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; +off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; 取消订阅GNSS卫星状态信息上报事件。 @@ -233,11 +240,12 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<SatelliteStatusInfo> | 否 | 接收GNSS卫星状态信息上报。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 否 | 接收GNSS卫星状态信息上报。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -248,7 +256,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : ## geolocation.on('nmeaMessageChange')8+ -on(type: 'nmeaMessageChange', callback: Callback<string>) : void; +on(type: 'nmeaMessageChange', callback: Callback<string>): void; 订阅GNSS NMEA信息上报事件。 @@ -266,7 +274,8 @@ on(type: 'nmeaMessageChange', callback: Callback<string>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -276,7 +285,7 @@ on(type: 'nmeaMessageChange', callback: Callback<string>) : void; ## geolocation.off('nmeaMessageChange')8+ -off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; +off(type: 'nmeaMessageChange', callback?: Callback<string>): void; 取消订阅GNSS NMEA信息上报事件。 @@ -294,7 +303,8 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -305,7 +315,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; ## geolocation.on('fenceStatusChange')8+ -on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; 添加一个围栏,并订阅地理围栏事件。 @@ -318,13 +328,13 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 | - | request | GeofenceRequest | 是 | 围栏的配置参数。 | + | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **示例** - ```js + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -332,13 +342,13 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -350,7 +360,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; ## geolocation.off('fenceStatusChange')8+ -off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; 删除一个围栏,并取消订阅该围栏事件。 @@ -363,12 +373,12 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 | - | request | GeofenceRequest | 是 | 围栏的配置参数。 | + | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **示例** - ```js + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -376,7 +386,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], @@ -393,62 +403,9 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void ``` -## geolocation.on('countryCodeChange')9+ - -on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; - -订阅国家码信息上报事件。 - -**系统能力**:SystemCapability.Location.Location.Core - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示订阅国家码信息上报。 | - | callback | Callback<CountryCode> | 是 | 接收国家码信息上报。 | - - -**示例** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - ``` - - -## geolocation.off('countryCodeChange')9+ - -off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; - -取消订阅国家码上报事件。 - -**系统能力**:SystemCapability.Location.Location.Core - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示取消订阅国家码信息上报。 | - | callback | Callback<CountryCode> | 是 | 接收国家码信息上报。 | - - -**示例** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - geolocation.off('countryCodeChange', callback); - ``` - - ## geolocation.getCurrentLocation -getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void 获取当前位置,使用callback回调异步返回结果。 @@ -466,7 +423,8 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { if (err) { @@ -483,7 +441,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ## geolocation.getCurrentLocation -getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> 获取当前位置,使用Promise方式异步返回结果。 @@ -507,7 +465,8 @@ getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); @@ -517,7 +476,7 @@ getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> ## geolocation.getLastLocation -getLastLocation(callback: AsyncCallback<Location>) : void +getLastLocation(callback: AsyncCallback<Location>): void 获取上一次位置,使用callback回调异步返回结果。 @@ -534,7 +493,8 @@ getLastLocation(callback: AsyncCallback<Location>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { console.log('getLastLocation: err=' + JSON.stringify(err)); @@ -548,7 +508,7 @@ getLastLocation(callback: AsyncCallback<Location>) : void ## geolocation.getLastLocation -getLastLocation() : Promise<Location> +getLastLocation(): Promise<Location> 获取上一次位置,使用Promise方式异步返回结果。 @@ -565,7 +525,8 @@ getLastLocation() : Promise<Location> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -574,7 +535,7 @@ getLastLocation() : Promise<Location> ## geolocation.isLocationEnabled -isLocationEnabled(callback: AsyncCallback<boolean>) : void +isLocationEnabled(callback: AsyncCallback<boolean>): void 判断位置服务是否已经打开,使用callback回调异步返回结果。 @@ -591,7 +552,8 @@ isLocationEnabled(callback: AsyncCallback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { console.log('isLocationEnabled: err=' + JSON.stringify(err)); @@ -605,7 +567,7 @@ isLocationEnabled(callback: AsyncCallback<boolean>) : void ## geolocation.isLocationEnabled -isLocationEnabled() : Promise<boolean> +isLocationEnabled(): Promise<boolean> 判断位置服务是否已经开启,使用Promise方式异步返回结果。 @@ -621,7 +583,8 @@ isLocationEnabled() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); }); @@ -630,7 +593,7 @@ isLocationEnabled() : Promise<boolean> ## geolocation.requestEnableLocation -requestEnableLocation(callback: AsyncCallback<boolean>) : void +requestEnableLocation(callback: AsyncCallback<boolean>): void 请求打开位置服务,使用callback回调异步返回结果。 @@ -647,7 +610,8 @@ requestEnableLocation(callback: AsyncCallback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { console.log('requestEnableLocation: err=' + JSON.stringify(err)); @@ -661,7 +625,7 @@ requestEnableLocation(callback: AsyncCallback<boolean>) : void ## geolocation.requestEnableLocation -requestEnableLocation() : Promise<boolean> +requestEnableLocation(): Promise<boolean> 请求打开位置服务,使用Promise方式异步返回结果。 @@ -677,7 +641,8 @@ requestEnableLocation() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation().then((result) => { console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); @@ -686,7 +651,7 @@ requestEnableLocation() : Promise<boolean> ## geolocation.enableLocation -enableLocation(callback: AsyncCallback<boolean>) : void; +enableLocation(callback: AsyncCallback<boolean>): void; 打开位置服务,使用callback回调异步返回结果。 @@ -704,7 +669,8 @@ enableLocation(callback: AsyncCallback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.enableLocation((err, data) => { if (err) { console.log('enableLocation: err=' + JSON.stringify(err)); @@ -718,7 +684,7 @@ enableLocation(callback: AsyncCallback<boolean>) : void; ## geolocation.enableLocation -enableLocation() : Promise<boolean> +enableLocation(): Promise<boolean> 打开位置服务,使用Promise方式异步返回结果。 @@ -736,7 +702,8 @@ enableLocation() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.enableLocation().then((result) => { console.log('promise, enableLocation: ' + JSON.stringify(result)); }); @@ -744,7 +711,7 @@ enableLocation() : Promise<boolean> ## geolocation.disableLocation -disableLocation(callback: AsyncCallback<boolean>) : void; +disableLocation(callback: AsyncCallback<boolean>): void; 关闭位置服务,使用callback回调异步返回结果。 @@ -762,7 +729,8 @@ disableLocation(callback: AsyncCallback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.disableLocation((err, data) => { if (err) { console.log('disableLocation: err=' + JSON.stringify(err)); @@ -776,7 +744,7 @@ disableLocation(callback: AsyncCallback<boolean>) : void; ## geolocation.disableLocation -disableLocation() : Promise<boolean> +disableLocation(): Promise<boolean> 关闭位置服务,使用Promise方式异步返回结果。 @@ -794,7 +762,8 @@ disableLocation() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.disableLocation().then((result) => { console.log('promise, disableLocation: ' + JSON.stringify(result)); }); @@ -802,7 +771,7 @@ disableLocation() : Promise<boolean> ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void +isGeoServiceAvailable(callback: AsyncCallback<boolean>): void 判断(逆)地理编码服务状态,使用callback回调异步返回结果。 @@ -818,7 +787,8 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); @@ -832,7 +802,7 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable() : Promise<boolean> +isGeoServiceAvailable(): Promise<boolean> 判断(逆)地理编码服务状态,使用Promise方式异步返回结果。 @@ -848,7 +818,8 @@ isGeoServiceAvailable() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); @@ -857,7 +828,7 @@ isGeoServiceAvailable() : Promise<boolean> ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void 调用逆地理编码服务,将坐标转换为地理描述,使用callback回调异步返回结果。 @@ -874,7 +845,8 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -889,7 +861,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; 调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。 @@ -911,7 +883,8 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<G **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -921,7 +894,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<G ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void 调用地理编码服务,将地理描述转换为具体坐标,使用callback回调异步返回结果。 @@ -938,7 +911,8 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -953,7 +927,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> 调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。 @@ -975,7 +949,8 @@ getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoA **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -985,7 +960,7 @@ getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoA ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; 获取GNSS芯片缓存位置的个数。 @@ -1001,7 +976,8 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); @@ -1015,7 +991,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize() : Promise<number>; +getCachedGnssLocationsSize(): Promise<number>; 获取GNSS芯片缓存位置的个数。 @@ -1031,7 +1007,8 @@ getCachedGnssLocationsSize() : Promise<number>; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); @@ -1040,7 +1017,7 @@ getCachedGnssLocationsSize() : Promise<number>; ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; +flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; 读取并清空GNSS芯片所有缓存位置。 @@ -1056,7 +1033,8 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); @@ -1070,7 +1048,7 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations() : Promise<boolean>; +flushCachedGnssLocations(): Promise<boolean>; 读取并清空GNSS芯片所有缓存位置。 @@ -1086,7 +1064,8 @@ flushCachedGnssLocations() : Promise<boolean>; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); @@ -1095,7 +1074,7 @@ flushCachedGnssLocations() : Promise<boolean>; ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; +sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; 给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。 @@ -1107,12 +1086,13 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | command | LocationCommand | 是 | 指定目标场景,和将要发送的命令(字符串)。 | + | command | [LocationCommand](#locationcommand) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | | callback | AsyncCallback<boolean> | 是 | 用来接收命令发送的结果。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1127,7 +1107,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand) : Promise<boolean>; +sendCommand(command: LocationCommand): Promise<boolean>; 给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。 @@ -1139,7 +1119,7 @@ sendCommand(command: LocationCommand) : Promise<boolean>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | command | LocationCommand | 是 | 指定目标场景,和将要发送的命令(字符串)。 | + | command | [LocationCommand](#locationcommand) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | **返回值**: @@ -1149,7 +1129,8 @@ sendCommand(command: LocationCommand) : Promise<boolean>; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); @@ -1157,836 +1138,193 @@ sendCommand(command: LocationCommand) : Promise<boolean>; ``` -## geolocation.isLocationPrivacyConfirmed8+ - -isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; -查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 +## LocationRequestPriority -**系统API**:此接口为系统接口,三方应用不支持调用。 +位置请求中位置信息优先级设置。 **需要权限**:ohos.permission.LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x200 | 表示未设置优先级。 | +| ACCURACY | 0x201 | 表示精度优先。 | +| LOW_POWER | 0x202 | 表示低功耗优先。 | +| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | - | callback | AsyncCallback<boolean> | 是 | 表示用户是否同意定位服务隐私申明。 | -**示例** - - ```js - geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - if (err) { - console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); - } - if (result) { - console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); - } - }); - ``` +## LocationRequestScenario + + 位置请求中定位场景设置。 + +**需要权限**:ohos.permission.LOCATION +**系统能力**:SystemCapability.Location.Location.Core -## geolocation.isLocationPrivacyConfirmed8+ +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x300 | 表示未设置场景信息。 | +| NAVIGATION | 0x301 | 表示导航场景。 | +| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | +| CAR_HAILING | 0x303 | 表示打车场景。 | +| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | +| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | -isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 +## GeoLocationErrorCode -**系统API**:此接口为系统接口,三方应用不支持调用。 +位置服务中的错误码信息。 **需要权限**:ohos.permission.LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | 表示输入参数错误。 | +| REVERSE_GEOCODE_ERROR7+ | 102 | 表示逆地理编码接口调用失败。 | +| GEOCODE_ERROR7+ | 103 | 表示地理编码接口调用失败。 | +| LOCATOR_ERROR7+ | 104 | 表示定位失败。 | +| LOCATION_SWITCH_ERROR7+ | 105 | 表示定位开关。 | +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | 表示获取上次位置失败。 | +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | 表示单次定位,没有在指定时间内返回位置。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | -**返回值**: +## ReverseGeoCodeRequest - | 参数名 | 说明 | - | -------- | -------- | - | Promise<boolean> | 表示用户是否同意定位服务隐私申明。 | +逆地理编码请求接口。 -**示例** - - ```js - geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); - }); - ``` +**需要权限**:ohos.permission.LOCATION +**系统能力**:SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 | +| maxItems | number | 否 | 指定返回位置信息的最大个数。 | -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 +## GeoCodeRequest -**系统API**:此接口为系统接口,三方应用不支持调用。 +地理编码请求接口。 **需要权限**:ohos.permission.LOCATION -**系统能力**:SystemCapability.Location.Location.Core +**系统能力**:SystemCapability.Location.Location.Geocoder -**参数**: +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | +| maxItems | number | 否 | 表示返回位置信息的最大个数。 | +| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | +| minLongitude | number | 否 | 表示最小经度信息。 | +| maxLatitude | number | 否 | 表示最大纬度信息。 | +| maxLongitude | number | 否 | 表示最大经度信息。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | - | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | - | callback | AsyncCallback<boolean> | 是 | 表示操作是否成功。 | -**示例** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - if (err) { - console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); - } - if (result) { - console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); - } - }); - ``` +## GeoAddress + +地理编码类型。 +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude7+ | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude7+ | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 | +| locale7+ | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| placeName7+ | string | 否 | 表示地区信息。 | +| countryCode7+ | string | 否 | 表示国家码信息。 | +| countryName7+ | string | 否 | 表示国家信息。 | +| administrativeArea7+ | string | 否 | 表示省份区域信息。 | +| subAdministrativeArea7+ | string | 否 | 表示表示子区域信息。 | +| locality7+ | string | 否 | 表示城市信息。 | +| subLocality7+ | string | 否 | 表示子城市信息。 | +| roadName7+ | string | 否 | 表示路名信息。 | +| subRoadName7+ | string | 否 | 表示子路名信息。 | +| premises7+ | string | 否 | 表示门牌号信息。 | +| postalCode7+ | string | 否 | 表示邮政编码信息。 | +| phoneNumber7+ | string | 否 | 表示联系方式信息。 | +| addressUrl7+ | string | 否 | 表示位置信息附件的网址信息。 | +| descriptions7+ | Array<string> | 否 | 表示附加的描述信息。 | +| descriptionsSize7+ | number | 否 | 表示附加的描述信息数量。 | -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 +## LocationRequest -**系统API**:此接口为系统接口,三方应用不支持调用。 +位置信息请求类型。 **需要权限**:ohos.permission.LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 | +| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 | +| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 | +| maxAccuracy | number | 否 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | - | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | -**返回值**: +## CurrentLocationRequest - | 参数名 | 说明 | - | -------- | -------- | - | Promise<boolean> | 表示操作是否成功。 | +当前位置信息请求类型。 -**示例** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); - }); - ``` +**需要权限**:ohos.permission.LOCATION +**系统能力**:SystemCapability.Location.Location.Core -## geolocation.getCountryCode9+ +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 | +| maxAccuracy | number | 否 | 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | +| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | -getCountryCode(callback: AsyncCallback<CountryCode>) : void; -查询当前的国家码。 +## SatelliteStatusInfo8+ -**系统能力**:SystemCapability.Location.Location.Core +卫星状态信息。 -**参数**: +**需要权限**:ohos.permission.LOCATION - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<CountryCode> | 是 | 用来接收国家码。 | +**系统能力**:SystemCapability.Location.Location.Gnss -**示例** - - ```js - geolocation.getCountryCode((err, result) => { - if (err) { - console.log('getCountryCode: err=' + JSON.stringify(err)); - } - if (result) { - console.log('getCountryCode: result=' + JSON.stringify(result)); - } - }); - ``` +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | 是 | 表示卫星个数。 | +| satelliteIds | Array<number> | 是 | 表示每个卫星的ID,数组类型。 | +| carrierToNoiseDensitys | Array<number> | 是 | 表示载波噪声功率谱密度比,即cn0。 | +| altitudes | Array<number> | 是 | 表示高程信息。 | +| azimuths | Array<number> | 是 | 表示方位角。 | +| carrierFrequencies | Array<number> | 是 | 表示载波频率。 | -## geolocation.getCountryCode9+ +## CachedGnssLocationsRequest8+ -getCountryCode() : Promise<CountryCode>; +请求订阅GNSS缓存位置上报功能接口的配置参数。 -查询当前的国家码。 +**需要权限**:ohos.permission.LOCATION -**系统能力**:SystemCapability.Location.Location.Core +**系统能力**:SystemCapability.Location.Location.Gnss -**参数**: +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | +| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | -无 -**返回值**: +## Geofence8+ - | 参数名 | 说明 | - | -------- | -------- | - | Promise<CountryCode> | 返回国家码。 | - -**示例** - - ```js - geolocation.getCountryCode() - .then((result) => { - console.log('promise, getCountryCode: result=' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCountryCode: error=' + JSON.stringify(error)); - }); - ``` - - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -使能某个场景的位置模拟功能,同一时间只能使能一个场景的位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示在什么场景下使能位置模拟功能。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request, (err, result) => { - if (err) { - console.log('enableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('enableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -使能某个场景的位置模拟功能,同一时间只能使能一个场景的位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示使能什么场景的位置模拟功能。如果不携带该参数则表示使能所有场景的位置模拟功能。 | - - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -去使能位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示去使能某个场景的位置模拟功能。如果不携带该参数则表示去使能所有场景的位置模拟功能。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request, (err, result) => { - if (err) { - console.log('disableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -去使能位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示去使能某个场景的位置模拟功能。如果不携带该参数则表示去使能所有场景的位置模拟功能。 | - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; - -设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations": locations}; - geolocation.setMockedLocations(config, (err, data) => { - if (err) { - console.log('setMockedLocations: err=' + JSON.stringify(err)); - } - if (data) { - console.log('setMockedLocations: data=' + JSON.stringify(data)); - } - }); - ``` - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig) : Promise<void>; - -设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations":locations}; - geolocation.setMockedLocations(config) - .then((result) => { - if (result) { - console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); - } - }); - ``` - - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.enableReverseGeocodingMock((err, data) => { - if (err) { - console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock() : Promise<void>; - -使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - -无 - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.enableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -去使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.disableReverseGeocodingMock((err, result) => { - if (err) { - console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock() : Promise<void>; - -去使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - -无 - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.disableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; - -设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | 是 | 指示逆地理编码模拟功能的配置参数数组。逆地理编码模拟功能的配置参数包含了一个位置和一个地名。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { - if (err) { - console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); - } - if (data) { - console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; - -设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | 是 | 指示逆地理编码模拟功能的配置信息数组。逆地理编码模拟功能的配置信息包含了一个位置和一个地名。 | - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos) - .then((result) => { - if (result) { - console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); - } - }); - ``` - - -## LocationRequestPriority - -位置请求中位置信息优先级设置。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x200 | 表示未设置优先级。 | -| ACCURACY | 0x201 | 表示精度优先。 | -| LOW_POWER | 0x202 | 表示低功耗优先。 | -| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | - - -## LocationRequestScenario - - 位置请求中定位场景设置。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x300 | 表示未设置场景信息。 | -| NAVIGATION | 0x301 | 表示导航场景。 | -| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | -| CAR_HAILING | 0x303 | 表示打车场景。 | -| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | -| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | - - -## GeoLocationErrorCode - -位置服务中的错误码信息。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| NOT_SUPPORTED9+ | 100 | 表示该接口功能不支持。 | -| INPUT_PARAMS_ERROR7+ | 101 | 表示输入参数错误。 | -| REVERSE_GEOCODE_ERROR7+ | 102 | 表示逆地理编码接口调用失败。 | -| GEOCODE_ERROR7+ | 103 | 表示地理编码接口调用失败。 | -| LOCATOR_ERROR7+ | 104 | 表示定位失败。 | -| LOCATION_SWITCH_ERROR7+ | 105 | 表示定位开关。 | -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | 表示获取上次位置失败。 | -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | 表示单次定位,没有在指定时间内返回位置。 | -| QUERY_COUNTRY_CODE_ERROR9+ | 108 | 表示国家码查询失败。 | - - -## ReverseGeoCodeRequest - -逆地理编码请求接口。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 | -| maxItems | number | 否 | 指定返回位置信息的最大个数。 | - - -## GeoCodeRequest - -地理编码请求接口。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | -| maxItems | number | 否 | 表示返回位置信息的最大个数。 | -| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | -| minLongitude | number | 否 | 表示最小经度信息。 | -| maxLatitude | number | 否 | 表示最大纬度信息。 | -| maxLongitude | number | 否 | 表示最大经度信息。 | - - -## GeoAddress - -地理编码类型。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| latitude7+ | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude7+ | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 | -| locale7+ | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| placeName7+ | string | 否 | 表示地区信息。 | -| countryCode7+ | string | 否 | 表示国家码信息。 | -| countryName7+ | string | 否 | 表示国家信息。 | -| administrativeArea7+ | string | 否 | 表示省份区域信息。 | -| subAdministrativeArea7+ | string | 否 | 表示表示子区域信息。 | -| locality7+ | string | 否 | 表示城市信息。 | -| subLocality7+ | string | 否 | 表示子城市信息。 | -| roadName7+ | string | 否 | 表示路名信息。 | -| subRoadName7+ | string | 否 | 表示子路名信息。 | -| premises7+ | string | 否 | 表示门牌号信息。 | -| postalCode7+ | string | 否 | 表示邮政编码信息。 | -| phoneNumber7+ | string | 否 | 表示联系方式信息。 | -| addressUrl7+ | string | 否 | 表示位置信息附件的网址信息。 | -| descriptions7+ | Array<string> | 否 | 表示附加的描述信息。 | -| descriptionsSize7+ | number | 否 | 表示附加的描述信息数量。 | -| isFromMock9+ | Boolean | 否 | 表示地名信息是否来自于逆地理编码模拟功能。 | - - -## LocationRequest - -位置信息请求类型。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 | -| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 | -| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 | -| maxAccuracy | number | 否 | 表示精度信息。 | - - -## CurrentLocationRequest - -当前位置信息请求类型。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 | -| maxAccuracy | number | 否 | 表示精度信息,单位是米。 | -| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | - - -## SatelliteStatusInfo8+ - -卫星状态信息。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Gnss - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | 是 | 表示卫星个数。 | -| satelliteIds | Array<number> | 是 | 表示每个卫星的ID,数组类型。 | -| carrierToNoiseDensitys | Array<number> | 是 | 表示载波噪声功率谱密度比,即cn0。 | -| altitudes | Array<number> | 是 | 表示高程信息。 | -| azimuths | Array<number> | 是 | 表示方位角。 | -| carrierFrequencies | Array<number> | 是 | 表示载波频率。 | - - -## CachedGnssLocationsRequest8+ - -请求订阅GNSS缓存位置上报功能接口的配置参数。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Gnss - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | -| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | - - -## Geofence8+ - -GNSS围栏的配置参数。目前只支持圆形围栏。 +GNSS围栏的配置参数。目前只支持圆形围栏。 **需要权限**:ohos.permission.LOCATION @@ -2010,9 +1348,9 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | 是 | 表示位置信息优先级。 | -| scenario | LocationRequestScenario | 是 | 表示定位场景。 | -| geofence | Geofence | 是 | 表示围栏信息。 | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 表示位置信息优先级。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | +| geofence | [Geofence](#geofence)| 是 | 表示围栏信息。 | ## LocationPrivacyType8+ @@ -2040,7 +1378,7 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | 是 | 表示定位场景。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | | command | string | 是 | 扩展命令字符串。 | @@ -2063,59 +1401,4 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | direction7+ | number | 是 | 表示航向信息。 | | timeSinceBoot7+ | number | 是 | 表示位置时间戳,开机时间格式。 | | additions7+ | Array<string> | 否 | 附加信息。 | -| additionSize7+ | number | 否 | 附加信息数量。 | -| isFromMock9+ | Boolean | 否 | 表示位置信息是否来自于位置模拟功能。 | - - -## ReverseGeocodingMockInfo9+ - -逆地理编码模拟功能的配置信息,包含一个位置信息和一个地名信息。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| location | ReverseGeoCodeRequest | 是 | 表示经纬度信息。 | -| geoAddress | GeoAddress | 是 | 表示地名信息。 | - - -## LocationMockConfig9+ - -位置模拟功能的配置参数,包含了模拟位置上报的时间间隔和模拟位置数组。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| timeInterval | number | 是 | 表示模拟位置上报的时间间隔,单位是秒。 | -| locations | Array<Location> | 是 | 表示模拟位置数组。 | - - -## CountryCode9+ - -国家码信息结构体,包含国家码字符串和国家码的来源信息。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| country | string | 是 | 表示国家码字符串。 | -| type | CountryCodeType | 是 | 表示国家码信息来源。 | - - -## CountryCodeType9+ - -国家码来源类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | 从全球化模块的语言配置信息中获取到的国家码。 | -| COUNTRY_CODE_FROM_SIM | 2 | 从SIM卡中获取到的国家码。 | -| COUNTRY_CODE_FROM_LOCATION | 3 | 基于用户的位置信息,通过逆地理编码查询到的国家码。 | -| COUNTRY_CODE_FROM_NETWORK | 4 | 从蜂窝网络注册信息中获取到的国家码。 | \ No newline at end of file +| additionSize7+ | number | 否 | 附加信息数量。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md index 2aacdc18fe767d767b1323153f1446f560bb2f92..5e58073b79314e40bef7036dd829b2a51a738bc2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md @@ -88,7 +88,7 @@ isEmpty(): boolean const hashMap = new HashMap(); let result = hashMap.isEmpty(); try { - hashMap.isEmpty.bind({})(); + hashMap.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -131,7 +131,7 @@ let result = hashMap.hasKey("squirrel"); hashMap.set("squirrel", 123); let result1 = hashMap.hasKey("squirrel"); try { - hashMap.hasKey.bind({}, "squirrel")(); + hashMap.hasKey.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -174,7 +174,7 @@ let result = hashMap.hasValue(123); hashMap.set("squirrel", 123); let result1 = hashMap.hasValue(123); try { - hashMap.hasValue.bind({}, 123)(); + hashMap.hasValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -217,7 +217,7 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.get("sparrow"); try { - hashMap.get.bind({}, "sparrow")(); + hashMap.get.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -255,7 +255,7 @@ hashMap.set("sparrow", 356); let newHashMap = new HashMap(); hashMap.setAll(newHashMap); try { - hashMap.setAll.bind({}, newHashMap)(); + hashMap.setAll.bind({}, newHashMap)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -297,7 +297,7 @@ set(key: K, value: V): Object let hashMap = new HashMap(); let result = hashMap.set("squirrel", 123); try { - hashMap.set.bind({}, "squirrel", 123)(); + hashMap.set.bind({}, "squirrel", 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -340,7 +340,7 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.remove("sparrow"); try { - hashMap.remove.bind({}, "sparrow")(); + hashMap.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -371,7 +371,7 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); hashMap.clear(); try { - hashMap.clear.bind({})(); + hashMap.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -413,7 +413,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap.keys.bind({})(); + hashMap.keys.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -455,7 +455,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap.values.bind({})(); + hashMap.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -498,7 +498,7 @@ let hashMap = new HashMap(); hashMap.set("sparrow", 123); let result = hashMap.replace("sparrow", 357); try { - hashMap.replace.bind({}, "sparrow", 357)(); + hashMap.replace.bind({}, "sparrow", 357)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -547,7 +547,7 @@ hashMap.forEach((value, key) => { try { hashMap.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -590,7 +590,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap.entries.bind({})(); + hashMap.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -640,7 +640,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap[Symbol.iterator].bind({})(); + hashMap[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashset.md b/zh-cn/application-dev/reference/apis/js-apis-hashset.md index df7dde4d3dbed6fd5cbd132bfe2ccd07ef0daeef..5a270cec3dc83316db1eadfd6642c18dfd7695ea 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashset.md @@ -96,7 +96,7 @@ isEmpty(): boolean const hashSet = new HashSet(); let result = hashSet.isEmpty(); try { - hashSet.isEmpty.bind({})(); + hashSet.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -139,7 +139,7 @@ let result = hashSet.has("squirrel"); hashSet.add("squirrel"); let result1 = hashSet.has("squirrel"); try { - hashSet.has.bind({}, "squirrel")(); + hashSet.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -180,7 +180,7 @@ add(value: T): boolean let hashSet = new HashSet(); let result = hashSet.add("squirrel"); try { - hashSet.add.bind({}, "squirrel")(); + hashSet.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -223,7 +223,7 @@ hashSet.add("squirrel"); hashSet.add("sparrow"); let result = hashSet.remove("sparrow"); try { - hashSet.remove.bind({}, "sparrow")(); + hashSet.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -254,7 +254,7 @@ hashSet.add("squirrel"); hashSet.add("sparrow"); hashSet.clear(); try { - hashSet.remove.bind({})(); + hashSet.remove.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -296,7 +296,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashSet.values.bind({})(); + hashSet.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -345,7 +345,7 @@ hashSet.forEach((value, key) => { try { hashSet.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -387,7 +387,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashSet.entries.bind({})(); + hashSet.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -436,7 +436,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashSet[Symbol.iterator].bind({})(); + hashSet[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-image.md b/zh-cn/application-dev/reference/apis/js-apis-image.md index c1cc2bf3cca7cc10f4a968c407348676b5ea62d4..c9a086de0f56f1923cc9b0eb6d22ead477d877a5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-image.md +++ b/zh-cn/application-dev/reference/apis/js-apis-image.md @@ -1771,7 +1771,7 @@ createImageReceiver(width: number, height: number, format: number, capacity: num | -------- | ------ | ---- | ---------------------- | | width | number | 是 | 图像的默认宽度。 | | height | number | 是 | 图像的默认高度。 | -| format | number | 是 | 图像格式,取值为[ImageFormat](#imageformat9)常量。 | +| format | number | 是 | 图像格式,取值为[ImageFormat](#imageformat9)常量(目前该参数为使用者和camera约定的值,以后可能还有其他应用场景,receiver的作用只是传递)。 | | capacity | number | 是 | 同时访问的最大图像数。 | **返回值:** @@ -1783,7 +1783,7 @@ createImageReceiver(width: number, height: number, format: number, capacity: num **示例:** ```js -var receiver = image.createImageReceiver(8192, 8, 4, 8); +var receiver = image.createImageReceiver(8192, 8, 2000, 8); ``` ## ImageReceiver9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md b/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md index 2551e73891f1692e7589c807e52a2dc44cef6de9..7f9be5cf41f311e7f897d28c913dc166b7a2585f 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,6 +1,6 @@ # 组合按键 -InputConsumer模块提供对按键事件的监听。 +组合按键订阅模块,用于处理组合按键的订阅。 > **说明:** > @@ -21,7 +21,7 @@ import inputConsumer from '@ohos.multimodalInput.inputConsumer'; on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): void -开始监听组合按键事件, 当满足条件的组合按键输入事件发生时,将keyOptions回调到入参callback表示的回调函数上。 +订阅组合按键,当满足条件的组合按键输入事件发生时,使用Callback异步方式上报组合按键数据。 **系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer @@ -29,22 +29,21 @@ on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): v | 参数 | 类型 | 必填 | 说明 | | ---------- | -------------------------- | ---- | ---------------------------------------- | -| type | string | 是 | 监听输入事件类型,只支持“key”。 | -| keyOptions | [keyOptions](#keyoptions) | 是 | 组合键选项,用来指定组合键输入时应该符合的条件。 | -| callback | Callback<KeyOptions> | 是 | 回调函数。当满足条件的按键输入产生时,回调到此函数,以传入的KeyOptions为入参。 | +| type | string | 是 | 事件类型,目前只支持”key“。 | +| keyOptions | [keyOptions](#keyoptions) | 是 | 组合键选项。 | +| callback | Callback<KeyOptions> | 是 | 回调函数,当满足条件的组合按键输入事件发生时,异步上报组合按键数据。 | **示例:** ```js -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 leftAltKey = 2045; +let tabKey = 2049; try { - inputConsumer.on(inputConsumer.SubscribeType.KEY, keyOptions, callback); + inputConsumer.on("key", {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}, keyOptions => { + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); + }); } catch (error) { - console.info(`inputConsumer.on, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`); + console.log(`Subscribe failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -53,7 +52,7 @@ try { off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void -停止监听组合按键事件。 +取消订阅组合按键。 **系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer @@ -61,35 +60,55 @@ off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): | 参数 | 类型 | 必填 | 说明 | | ---------- | -------------------------- | ---- | ------------------------------- | -| type | string | 是 | 监听输入事件类型,只支持“key”。 | -| keyOptions | [keyOptions](#keyoptions) | 是 | 开始监听时传入的keyOptions。 | -| callback | Callback<KeyOptions> | 是 | 开始监听时与KeyOption一同传入的回调函数 。 | +| type | string | 是 | 事件类型,当前只支持”key“。 | +| keyOptions | [keyOptions](#keyoptions) | 是 | 组合键选项。 | +| callback | Callback<KeyOptions> | 否 | 需要取消订阅的回调函数,若无此参数,则取消当前应用的组合键选项已订阅的所有回调函数。 | **示例:** ```js -let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 } +let leftAltKey = 2045; +let tabKey = 2049; +// 取消订阅单个回调函数 +let callback = function (keyOptions) { + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); +} +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.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); } +let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}; try { - inputConsumer.off(inputConsumer.SubscribeType.KEY, keyOptions, callback); + inputConsumer.on("key", keyOption, callback); + inputConsumer.off("key", keyOption); + console.log(`Unsubscribe success`); } catch (error) { - console.info(`inputConsumer.off, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`); + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## KeyOptions -组合键输入事件发生时,组合键满足的选项。 +组合键选项。 **系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer | 参数 | 类型 | 必填 | 说明 | | -------------------- | ------- | ---- | ------------------------ | -| preKeys | Array | 是 | 组合键前置按键集合,可为空,前置按键无顺序要求。 | -| finalKey | Number | 是 | 组合键最后按键,不能为空。 | -| isFinalKeyDown | boolean | 是 | 组合键最后按键是按下还是抬起,默认是按下。 | -| finalKeyDownDuration | Number | 是 | 组合键最后按键按下持续时长,默认无时长要求。 | +| preKeys | Array | 是 | 前置按键集合,数量范围[0, 4],前置按键无顺序要求。 | +| finalKey | Number | 是 | 最终按键,此项必填,最终按键触发上报回调函数。 | +| isFinalKeyDown | boolean | 是 | 最终按键状态。 | +| finalKeyDownDuration | Number | 是 | 最终按键保持按下持续时间,为0时立即触发回调函数,大于0时,当isFinalKeyDown为true,则最终按键按下超过此时长后触发回调函数,当isFinalKeyDown为false,则最终按键按下到抬起时间小于此时长时触发回调函数。 | 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 b255b0a2f4a3fc86fb06170ae182267c33d3c339..ecd2d4b1968e32a6ab1c990538bc57c4e898e6f4 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputdevice.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @@ -1,7 +1,7 @@ # 输入设备 -输入设备管理模块,用于监听输入设备连接、断开和变化,并查看输入设备相关信息。比如监听鼠标插拔,并获取鼠标的id、name和指针移动速度等信息。 +输入设备管理模块,用于监听输入设备连接和断开状态,查询输入设备相关信息。 > **说明**: @@ -20,15 +20,15 @@ import inputDevice from '@ohos.multimodalInput.inputDevice'; getDeviceList(callback: AsyncCallback<Array<number>>): void -获取所有输入设备的id列表,使用callback方式作为异步方法。 +获取所有输入设备的id列表,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------- | -| callback | AsyncCallback<Array<number>> | 是 | 回调函数。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback<Array<number>> | 是 | 回调函数,异步返回所有输入设备的id列表。 | **示例**: @@ -36,15 +36,13 @@ getDeviceList(callback: AsyncCallback<Array<number>>): void 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)}`); + console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - this.data = ids; - console.log("The device ID list is: " + ids); + console.log(`Device id list: ${JSON.stringify(ids)}`); }); } catch (error) { - console.info("getDeviceList " + error.code + " " + error.message); + console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -52,25 +50,25 @@ try { getDeviceList(): Promise<Array<number>> -获取所有输入设备的id列表,使用Promise方式作为异步方法。 +获取所有输入设备的id列表,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice **返回值**: -| 参数 | 说明 | -| ---------------------------------- | ------------------------------- | -| Promise<Array<number>> | Promise实例,用于异步获取结果。 | +| 参数 | 说明 | +| ---------------------------------- | ------------------------------------------- | +| Promise<Array<number>> | Promise对象,异步返回所有输入设备的id列表。 | **示例**: ```js try { inputDevice.getDeviceList().then((ids) => { - console.log("The device ID list is: " + ids); + console.log(`Device id list: ${JSON.stringify(ids)}`); }); } catch (error) { - console.info("getDeviceList " + error.code + " " + error.message); + console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -78,7 +76,7 @@ try { getDeviceInfo(deviceId: number, callback: AsyncCallback<InputDeviceData>): void -获取输入设备的描述信息,使用callback方式作为异步方法。 +获取指定输入设备的信息,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice @@ -86,24 +84,23 @@ getDeviceInfo(deviceId: number, callback: AsyncCallback<InputDeviceData>): | 参数 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------------------- | ---- | --------------------------------------- | -| deviceId | number | 是 | 需要获取信息的设备id。 | -| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | 是 | 回调函数,异步返回InputDeviceData对象。 | +| deviceId | number | 是 | 输入设备id。 | +| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | 是 | 回调函数,异步返回输入设备信息。 | **示例**: ```js -// 示例获取设备id为1的设备name信息。 +// 获取输入设备id为1的设备信息。 try { - inputDevice.getDeviceInfo(1, (error, inputDevice) => { + inputDevice.getDeviceInfo(1, (error, deviceData) => { if (error) { - console.log(`Failed to get device information. - error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log("The device name is: " + inputDevice.name); + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); } catch (error) { - console.info("getDeviceInfo " + error.code + " " + error.message); + console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -111,7 +108,7 @@ try { getDeviceInfo(deviceId: number): Promise<InputDeviceData> -获取输入设备的描述信息,使用Promise方式作为异步方法。 +获取指定输入设备的信息,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice @@ -119,30 +116,30 @@ getDeviceInfo(deviceId: number): Promise<InputDeviceData> | 参数 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ---------------------- | -| deviceId | number | 是 | 需要获取信息的设备id。 | +| deviceId | number | 是 | 输入设备id。 | **返回值**: | 参数 | 说明 | | -------------------------------------------------- | ------------------------------- | -| Promise<[InputDeviceData](#inputdevicedata)> | Promise实例,用于异步获取结果。 | +| Promise<[InputDeviceData](#inputdevicedata)> | Promise对象,异步返回输入设备信息。 | **示例**: ```js -// 示例获取设备id为1的设备name信息。 +// 获取输入设备id为1的设备信息。 try { - inputDevice.getDeviceInfo(id).then((inputDevice) => { - console.log("The device name is: " + inputDevice.name); + inputDevice.getDeviceInfo(1).then((deviceData) => { + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); } catch (error) { - console.info("getDeviceInfo " + error.code + " " + error.message); + console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## inputDevice.on9+ -on(type: “change”, listener: Callback<DeviceListener>): void +on(type: "change", listener: Callback<DeviceListener>): void 监听输入设备的热插拔事件。 @@ -153,7 +150,7 @@ on(type: “change”, listener: Callback<DeviceListener>): void | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------- | | type | string | 是 | 输入设备的事件类型。 | -| listener | Callback<[DeviceListener](#devicelistener9)> | 是 | 可上报的输入设备事件。 | +| listener | Callback<[DeviceListener](#devicelistener9)> | 是 | 回调函数,异步上报输入设备热插拔事件。 | **示例**: @@ -161,13 +158,13 @@ on(type: “change”, listener: Callback<DeviceListener>): void let isPhysicalKeyboardExist = true; 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') { + console.log(`Device event info: ${JSON.stringify(data)}`); + inputDevice.getKeyboardType(data.deviceId, (err, type) => { + console.log("The keyboard type is: " + type); + if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // 监听物理键盘已连接。 isPhysicalKeyboardExist = true; - } else if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { + } else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { // 监听物理键盘已断开。 isPhysicalKeyboardExist = false; } @@ -175,13 +172,13 @@ try { }); // 根据isPhysicalKeyboardExist的值决定软键盘是否弹出。 } catch (error) { - console.info("oninputdevcie " + error.code + " " + error.message); + console.log(`Get device info failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## inputDevice.off9+ -off(type: “change”, listener?: Callback<DeviceListener>): void +off(type: "change", listener?: Callback<DeviceListener>): void 取消监听输入设备的热插拔事件。 @@ -192,42 +189,41 @@ off(type: “change”, listener?: Callback<DeviceListener>): void | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------- | | type | string | 是 | 输入设备的事件类型。 | -| listener | Callback<[DeviceListener](#devicelistener9)> | 否 | 可上报的输入设备事件。 | +| listener | Callback<[DeviceListener](#devicelistener9)> | 否 | 取消监听的回调函数。 | **示例**: ```js -callback: function(data) { - console.log("type: " + data.type + ", deviceId: " + data.deviceId); -} +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.info("oninputdevcie " + error.code + " " + error.message) + console.log(`Listen device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } -// 单独取消listener的监听。 +// 取消指定的监听。 try { - inputDevice.off("change", this.callback); + inputDevice.off("change", callback); } catch (error) { - console.info("offinputdevcie " + error.code + " " + error.message) + console.log(`Cancel listening device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } // 取消所有监听。 try { inputDevice.off("change"); } catch (error) { - console.info("offinputdevcie " + error.code + " " + error.message); + console.log(`Cancel all listening device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } -// 取消监听后,软键盘默认都弹出。 ``` ## inputDevice.getDeviceIds(deprecated) getDeviceIds(callback: AsyncCallback<Array<number>>): void -获取所有输入设备的id列表,使用callback方式作为异步方法。 +获取所有输入设备的id列表,使用AsyncCallback异步方式返回结果。 从API version 9 开始不再维护,建议使用[inputDevice.getDeviceList](#inputdevicegetdevicelist9)代替。 @@ -235,15 +231,19 @@ getDeviceIds(callback: AsyncCallback<Array<number>>): void **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ----- | -| callback | AsyncCallback<Array<number>> | 是 | 回调函数。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback<Array<number>> | 是 | 回调函数,异步返回所有输入设备的id列表。 | **示例**: ```js -inputDevice.getDeviceIds((ids)=>{ - console.log("The device ID list is: " + ids); +inputDevice.getDeviceList((error, ids) => { + if (error) { + console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Device id list: ${JSON.stringify(ids)}`); }); ``` @@ -251,7 +251,7 @@ inputDevice.getDeviceIds((ids)=>{ getDeviceIds(): Promise<Array<number>> -获取所有输入设备的id列表,使用Promise方式作为异步方法。 +获取所有输入设备的id列表,使用Promise异步方式返回结果。 从API version 9 开始不再维护,建议使用[inputDevice.getDeviceList](#inputdevicegetdevicelist9)代替。 @@ -259,15 +259,15 @@ getDeviceIds(): Promise<Array<number>> **返回值**: -| 参数 | 说明 | -| ---------------------------------- | ------------------- | -| Promise<Array<number>> | Promise实例,用于异步获取结果。 | +| 参数 | 说明 | +| ---------------------------------- | ------------------------------------------- | +| Promise<Array<number>> | Promise对象,异步返回所有输入设备的id列表。 | **示例**: ```js -inputDevice.getDeviceIds().then((ids)=>{ - console.log("The device ID list is: " + ids); +inputDevice.getDeviceList().then((ids) => { + console.log(`Device id list: ${JSON.stringify(ids)}`); }); ``` @@ -275,7 +275,7 @@ inputDevice.getDeviceIds().then((ids)=>{ getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void -获取输入设备的描述信息,使用callback方式作为异步方法。 +获取指定输入设备的信息,使用AsyncCallback异步方式返回结果。 从API version 9 开始不再维护,建议使用[inputDevice.getDeviceInfo](#inputdevicegetdeviceinfo9)代替。 @@ -283,17 +283,21 @@ getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): voi **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------------------------- | -| deviceId | number | 是 | 需要获取信息的设备id。 | -| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | 是 | 回调函数,异步返回InputDeviceData对象。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------------------- | ---- | -------------------------------- | +| deviceId | number | 是 | 输入设备id。 | +| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | 是 | 回调函数,异步返回输入设备信息。 | **示例**: ```js -// 示例获取设备id为1的设备name信息。 -inputDevice.getDevice(1, (inputDevice)=>{ - console.log("The device name is: " + inputDevice.name); +// 获取输入设备id为1的设备信息。 +inputDevice.getDeviceInfo(1, (error, deviceData) => { + if (error) { + console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); ``` @@ -301,7 +305,7 @@ inputDevice.getDevice(1, (inputDevice)=>{ getDevice(deviceId: number): Promise<InputDeviceData> -获取输入设备的描述信息,使用Promise方式作为异步方法。 +获取指定输入设备的信息,使用Promise异步方式返回结果。 从API version 9 开始不再维护,建议使用[inputDevice.getDeviceInfo](#inputdevicegetdeviceinfo9)代替。 @@ -309,22 +313,22 @@ getDevice(deviceId: number): Promise<InputDeviceData> **参数**: -| 参数 | 类型 | 必填 | 说明 | +| 参数 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------ | -| deviceId | number | 是 | 需要获取信息的设备id。 | +| deviceId | number | 是 | 输入设备id。 | **返回值**: -| 参数 | 说明 | -| ---------------------------------------- | ------------------- | -| Promise<[InputDeviceData](#inputdevicedata)> | Promise实例,用于异步获取结果。 | +| 参数 | 说明 | +| -------------------------------------------------- | ----------------------------------- | +| Promise<[InputDeviceData](#inputdevicedata)> | Promise对象,异步返回输入设备信息。 | **示例**: ```js -// 示例获取设备id为1的设备name信息。 -inputDevice.getDevice(1).then((inputDevice)=>{ - console.log("The device name is: " + inputDevice.name); +// 获取输入设备id为1的设备信息。 +inputDevice.getDeviceInfo(1).then((deviceData) => { + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); ``` @@ -332,28 +336,28 @@ inputDevice.getDevice(1).then((inputDevice)=>{ supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void -获取输入设备支持的键码值,使用callback方式作为异步方法。 +获取输入设备是否支持指定的键码值,使用Callback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------ | ---- | --------------------------------- | -| deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 | -| keys | Array<KeyCode> | 是 | 需要查询的键码值,最多支持5个按键查询。 | -| callback | Callback<Array<boolean>> | 是 | 回调函数,异步返回查询结果。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | +| deviceId | number | 是 | 输入设备id,同一个物理设备反复插拔,设备id会发生变化。 | +| keys | Array<KeyCode> | 是 | 需要查询的键码值,最多支持5个按键查询。 | +| callback | Callback<Array<boolean>> | 是 | 回调函数,异步返回查询结果。 | **示例**: ```js -// 示例查询id为1的设备对于17、22和2055按键的支持情况。 +// 查询id为1的输入设备对于17、22和2055按键的支持情况。 try { - inputDevice.supportKeys(1, [17, 22, 2055], (error, ret) => { - console.log("The query result is as follows: " + ret); + inputDevice.supportKeys(1, [17, 22, 2055], (error, supportResult) => { + console.log(`Query result: ${JSON.stringify(supportResult)}`); }); } catch (error) { - console.info("supportKeys " + error.code + " " + error.message); + console.log(`Query failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -361,33 +365,33 @@ try { supportKeys(deviceId: number, keys: Array<KeyCode>): Promise<Array<boolean>> -获取输入设备支持的键码值,使用Promise方式作为异步方法。 +获取输入设备是否支持指定的键码值,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | --------------------------------- | -| deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 | -| keys | Array<KeyCode> | 是 | 需要查询的键码值,最多支持5个按键查询。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------ | +| deviceId | number | 是 | 输入设备id,同一个物理设备反复插拔,设备id会发生变化。 | +| keys | Array<KeyCode> | 是 | 需要查询的键码值,最多支持5个按键查询。 | **返回值**: -| 参数 | 说明 | -| ----------------------------------- | ------------------- | -| Promise<Array<boolean>> | Promise实例,用于异步获取结果。 | +| 参数 | 说明 | +| ----------------------------------- | ------------------------------- | +| Promise<Array<boolean>> | Promise对象,异步返回查询结果。 | **示例**: ```js -// 示例查询id为1的设备对于17、22和2055按键的支持情况。 +// 查询id为1的输入设备对于17、22和2055按键的支持情况。 try { - inputDevice.supportKeys(1, [17, 22, 2055]).then((ret) => { - console.log("The query result is as follows: " + ret); + inputDevice.supportKeys(1, [17, 22, 2055]).then((supportResult) => { + console.log(`Query result: ${JSON.stringify(supportResult)}`); }); } catch (error) { - console.info("supportKeys " + error.code + " " + error.message); + console.log(`Query failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -395,32 +399,31 @@ try { getKeyboardType(deviceId: number, callback: AsyncCallback<KeyboardType>): void -查询输入设备的键盘类型,使用callback方式作为异步方法。 +获取输入设备的键盘类型,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------------------------------- | -| deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 | -| callback | AsyncCallback<[KeyboardType](#keyboardtype9)> | 是 | 回调函数,异步返回查询结果。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,设备id会发生变化。 | +| callback | AsyncCallback<[KeyboardType](#keyboardtype9)> | 是 | 回调函数,异步返回查询结果。 | **示例**: ```js -// 示例查询设备id为1的设备键盘类型。 +// 查询id为1的输入设备的键盘类型。 try { - inputDevice.getKeyboardType(1, (error, number) => { + inputDevice.getKeyboardType(1, (error, type) => { if (error) { - console.log(`Failed to get keyboardtype. - error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + console.log(`Failed to get keyboard type, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log("The keyboard type of the device is: " + number); + console.log(`Keyboard type: ${JSON.stringify(type)}`); }); } catch (error) { - console.info("getKeyboardType " + error.code + " " + error.message); + console.log(`Failed to get keyboard type, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -428,39 +431,45 @@ try { getKeyboardType(deviceId: number): Promise<KeyboardType> -查询输入设备的键盘类型,使用Promise方式作为异步方法。 +获取输入设备的键盘类型,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice +**参数**: + +| 参数 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,设备id会发生变化。 | + **返回值**: -| 参数 | 说明 | -| ---------------------------------------- | ------------------- | -| Promise<[KeyboardType](#keyboardtype9)> | Promise实例,用于异步获取结果。 | +| 参数 | 说明 | +| --------------------------------------------- | ------------------------------- | +| Promise<[KeyboardType](#keyboardtype9)> | Promise对象,异步返回查询结果。 | **示例**: ```js // 示例查询设备id为1的设备键盘类型。 try { - inputDevice.getKeyboardType(1).then((number) => { - console.log("The keyboard type of the device is: " + number); + inputDevice.getKeyboardType(1).then((type) => { + console.log(`Keyboard type: ${JSON.stringify(type)}`); }); } catch (error) { - console.info("getKeyboardType " + error.code + " " + error.message); + console.log(`Failed to get keyboard type, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## DeviceListener9+ -输入设备的描述信息。 +输入设备热插拔的描述信息。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice -| 名称 | 参数类型 | 说明 | -| -------- | --------------------------- | --------------------------------- | -| type | [ChangedType](#changedtype) | 表示输入设备插入或者移除。 | -| deviceId | number | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 | +| 名称 | 参数类型 | 说明 | +| -------- | --------------------------- | ------------------------------------------------------------ | +| type | [ChangedType](#changedtype) | 输入设备插入或者移除。 | +| deviceId | number | 输入设备的唯一标识,同一个物理设备反复插拔,设备id会发生变化。 | ## InputDeviceData @@ -468,18 +477,18 @@ try { **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice -| 名称 | 参数类型 | 说明 | -| -------------------- | -------------------------------------- | ---------------------------------------- | -| id | number | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 | -| name | string | 输入设备的名字。 | +| 名称 | 参数类型 | 说明 | +| -------------------- | -------------------------------------- | ------------------------------------------------------------ | +| id | number | 输入设备的唯一标识,同一个物理设备反复插拔,设备id会发生变化。 | +| name | string | 输入设备的名字。 | | sources | Array<[SourceType](#sourcetype)> | 输入设备支持的源类型。比如有的键盘上附带触摸板,则此设备有keyboard和touchpad两种输入源。 | -| axisRanges | Array<[axisRanges](#axisrange)> | 输入设备的轴信息。 | -| bus9+ | number | 输入设备的总线类型。 | -| product9+ | number | 输入设备的产品信息。 | -| vendor9+ | number | 输入设备的厂商信息。 | -| version9+ | number | 输入设备的版本信息。 | -| phys9+ | string | 输入设备的物理地址。 | -| uniq9+ | string | 输入设备的唯一标识。 | +| axisRanges | Array<[axisRanges](#axisrange)> | 输入设备的轴信息。 | +| bus9+ | number | 输入设备的总线类型。 | +| product9+ | number | 输入设备的产品信息。 | +| vendor9+ | number | 输入设备的厂商信息。 | +| version9+ | number | 输入设备的版本信息。 | +| phys9+ | string | 输入设备的物理地址。 | +| uniq9+ | string | 输入设备的唯一标识。 | ## AxisType9+ @@ -517,7 +526,7 @@ try { ## SourceType -定义这个轴的输入源类型。比如鼠标设备可上报x轴事件,则x轴的源就是鼠标。 +轴的输入源类型。比如鼠标设备可上报x轴事件,则x轴的输入源就是鼠标。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputevent.md b/zh-cn/application-dev/reference/apis/js-apis-inputevent.md index df973465e5b7341c60de3740e757d320dc3feed7..1d964e6d0bab941d4127557c6da6f91cd1f65881 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputevent.md @@ -1,6 +1,6 @@ # 输入事件 -InputEvent模块描述了设备上报的基本事件。 +设备上报的基本事件。 > **说明:** > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -17,7 +17,7 @@ import InputEvent from '@ohos.multimodalInput.inputEvent'; | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ---------- | ------ | ---- | ---- | -------------- | -| id | number | 是 | 否 | 由服务端生成全局唯一事件id | +| id | number | 是 | 否 | 事件id | | deviceId | number | 是 | 否 | 上报输入事件的设备id | | actionTime | number | 是 | 否 | 输入事件的上报时间 | | screenId | number | 是 | 否 | 目标屏幕id | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md b/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md index 9654433e873c5803fb1d52def20ecd00e5efea07..80d1a26688e276daea5ed1572764368ef93fb8ba 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,6 +1,6 @@ -# 注入按键 +# 按键注入 -InputEventClient模块提供了注入按键能力。 +按键注入模块,提供按键注入能力。 > **说明:** > @@ -21,7 +21,7 @@ import inputEventClient from '@ohos.multimodalInput.inputEventClient'; injectEvent({KeyEvent: KeyEvent}): void -注入按键,KeyEvent为注入按键的描述信息。 +按键注入,当前仅支持返回键(键值2)注入。 **系统能力:** SystemCapability.MultimodalInput.Input.InputSimulator @@ -29,41 +29,43 @@ injectEvent({KeyEvent: KeyEvent}): void | 参数 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | --------- | -| KeyEvent | [KeyEvent](#keyevent) | 是 | 注入按键的描述信息 | +| KeyEvent | [KeyEvent](#keyevent) | 是 | 按键注入描述信息。 | **示例:** ```js try { - var keyEvent = { + let backKeyDown = { isPressed: true, keyCode: 2, keyDownDuration: 0, isIntercepted: false } - inputEventClient.injectKeyEvent({ KeyEvent: keyEvent }); - var keyEvent1 = { + inputEventClient.injectKeyEvent({ KeyEvent: backKeyDown }); + + let backKeyUp = { isPressed: false, keyCode: 2, keyDownDuration: 0, isIntercepted: false }; - inputEventClient.injectKeyEvent({ KeyEvent: keyEvent1 }); + inputEventClient.injectKeyEvent({ KeyEvent: backKeyUp }); } catch (error) { - console.info("injectKeyEvent " + error.code + " " + error.message); + console.log(`Failed to inject KeyEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## KeyEvent -注入按键的描述信息。 +按键注入描述信息。 **系统能力:** SystemCapability.MultimodalInput.Input.InputSimulator -| 参数 | 类型 | 必填 | 说明 | -| --------------- | ------- | ---- | --------- | -| isPressed | boolean | 是 | 按键是否按下 | -| keyCode | number | 是 | 按键键值 | -| keyDownDuration | number | 是 | 按键按下持续时间 | -| isIntercepted | boolean | 是 | 按键是否可以被拦截 | +| 参数 | 类型 | 必填 | 说明 | +| --------------- | ------- | ---- | -------------------------- | +| isPressed | boolean | 是 | 按键是否按下。 | +| keyCode | number | 是 | 按键键值,当前只支持back键。 | +| keyDownDuration | number | 是 | 按键按下持续时间。 | +| isIntercepted | boolean | 是 | 按键是否可以被拦截。 | + 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 32b5e53b412e1a4c071ce7cfbcabf36c62ad0b82..6f381f501ab77c7b76e03734dd6311fe61801b7c 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 @@ -1,11 +1,10 @@ # InputMethodExtensionAbility -InputMethodExtensionAbility模块,提供生态输入法应用开发者通过InputMethodExtensionAbility、InputMethodExtensionContext接口创作输入法应用,并管理输入法应用生命周期。 +开发者可通过继承本模块开发自己的输入法应用并管理输入法应用生命周期。 > **说明:** -> -> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 +> +>本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -15,7 +14,7 @@ import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; ## 属性 -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | @@ -24,11 +23,11 @@ import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; ## InputMethodExtensionAbility.onCreate() -onCreate(want: Want): void; +onCreate(want: Want): void Extension生命周期回调,在拉起Extension输入法应用时调用,执行初始化输入法应用操作。 -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -38,29 +37,29 @@ Extension生命周期回调,在拉起Extension输入法应用时调用,执 **示例:** - ```js - class InputMethodExt extends InputMethodExtensionAbility { +```js +class InputMethodExt extends InputMethodExtensionAbility { onCreate(want) { - console.log('onCreate, want:' + want.abilityName); + console.log('onCreate, want:' + want.abilityName); } - } - ``` +} +``` ## InputMethodExtensionAbility.onDestroy() -onDestroy(): void; +onDestroy(): void Extension生命周期回调,在销毁输入法应用时回调,执行资源清理等操作。 -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **示例:** - ```js - class InputMethodExt extends InputMethodExtensionAbility { +```js +class InputMethodExt extends InputMethodExtensionAbility { onDestroy() { - console.log('onDestroy'); + console.log('onDestroy'); } - } - ``` +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index 3d7a9ad9e0ec73c4b87c35a0100192aeef9f46df..acd2a268fdec54a7e82e531b5345c25a1d62bf0f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -5,9 +5,8 @@ InputMethodExtensionContext模块是InputMethodExtensionAbility的上下文环 InputMethodExtensionContext模块提供InputMethodExtensionAbility具有的能力和接口,包括启动、停止、绑定、解绑Ability。 > **说明:** -> -> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 +> +>本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -20,151 +19,56 @@ import InputMethodExtensionContext from '@ohos.inputmethodextensioncontext'; 在使用InputMethodExtensionContext的功能前,需要通过InputMethodExtensionAbility子类实例获取。 ```js - import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; - class MainAbility extends InputMethodExtensionAbility { - onCreate() { - let context = this.context; - } - } +import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; +class MainAbility extends InputMethodExtensionAbility { + onCreate() { + let context = this.context; + } +} ``` -## InputMethodExtensionContext.startAbility +## InputMethodExtensionContext.destroy -startAbility(want: Want, callback: AsyncCallback<void>): void; +destroy(callback: AsyncCallback\): void -启动Ability,包含一个Want类型参数。callback形式返回启动结果。 +停止输入法应用自身。使用callback异步回调。 -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如ability名称,包名等。 | -| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\ | 是 | 回调函数。当停止输入法应用自身成功时,err为undefined;否则为错误对象。 | **示例:** - ```js - let want = { - 'bundleName': 'com.example.myapp', - 'abilityName': 'MyAbility' - }; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); - }); - ``` - -## InputMethodExtensionContext.startAbility - -startAbility(want: Want, options?: StartOptions): Promise\; - -启动Ability,包含Want类型参数,以及可选填的StartOption类型参数。通过Promise方法返回结果。 - -**系统能力**:SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如ability名称,包名等。 | -| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | - -**返回值:** - - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | 返回一个Promise,包含接口的结果。 | - -**示例:** - - ```js - let want = { - 'bundleName': 'com.example.myapp', - 'abilityName': 'MyAbility' - }; - this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - -## InputMethodExtensionContext.startAbility - -startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void - -启动Ability,包含有两个参数,Want类型和StartOption类型参数。callback形式返回启动结果。 - -**系统能力**:SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | -| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | - -**示例:** - - ```js - var want = { - 'deviceId': '', - 'bundleName': 'com.extreme.test', - 'abilityName': 'MainAbility' - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options, (error) => { - console.log('error.code = ' + error.code) - }) - ``` - -## InputMethodExtensionContext.terminateSelf - -terminateSelf(callback: AsyncCallback<void>): void; - -停止输入法应用自身,通过Callback方法返回接口调用是否成功。 - -**系统能力**:SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | - -**示例:** - - ```js -this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); +```js +this.context.destroy((err) => { + console.log('destroy result:' + JSON.stringify(err)); }); - ``` +``` -## InputMethodExtensionContext.terminateSelf +## InputMethodExtensionContext.destroy -terminateSelf(): Promise<void>; +destroy(): Promise { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` +```js +this.context.destroy().then((data) => { + console.log('success:' + JSON.stringify(data)); +}).catch((error) => { + console.log('failed:' + JSON.stringify(error)); +}); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md new file mode 100644 index 0000000000000000000000000000000000000000..fc8a1b1dbed1656eae864432eec81480fe96f55c --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @@ -0,0 +1,31 @@ +# 输入法子类型 + +本模块提供对输入法子类型的属性管理。 + +> **说明:** +> +>本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +``` +import inputMethodEngine from '@ohos.inputMethodSubtype'; +``` + +## 属性 + +属性值。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 参数类型 | 可读 | 可写 | 必选 | 说明 | +| -------- | -------- | -------- | -------- | -------- | -------- | +| label | string | 是 | 否 | 否 | 输入法子类型的标签。 | +| name | string | 是 | 否 | 是 | 输入法子类型的名字。 | +| id | string | 是 | 否 | 是 | 输入法子类型的id。 | +| mode | string | 是 | 否 | 否 | 输入法子类型的模式,包括upper(大写)和lower(小写)。 | +| locale | string | 是 | 否 | 是 | 输入法子类型的方言版本。 | +| language | string | 是 | 否 | 是 | 输入法子类型的语言。 | +| icon | string | 是 | 否 | 否 | 输入法子类型的图标。 | +| iconId | number | 是 | 否 | 否 | 输入法子类型的图标id。 | +| extra | object | 是 | 是 | 是 | 输入法子类型的其他信息。 | \ 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 91f8b10169a191b95599051b5a390ca0b12bc650..aa285044a0905a546983a48e157baf82b2ea4858 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @@ -2,9 +2,9 @@ 本模块提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框。 -> **说明:** +>**说明:** > -> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -13,35 +13,40 @@ import inputMethod from '@ohos.inputmethod'; ``` -## inputMethod8+ +## 常量8+ 常量值。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework - -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| MAX_TYPE_NUM | number | 是 | 否 | 可支持的最大输入法个数。 | +**系统能力:** SystemCapability.MiscServices.InputMethodFramework +| 参数名 | 参数类型 | 常量值 | 说明 | +| -------- | -------- | -------- | -------- | +| MAX_TYPE_NUM | number | 128 | 可支持的最大输入法个数。 | ## InputMethodProperty8+ 输入法应用属性。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| packageName | string | 是 | 否 | 包名。 | -| methodId | string | 是 | 否 | Ability名。 | +| packageName(deprecated) | string | 是 | 否 | 输入法包名。
**说明:** 从API8开始支持,从API9开始废弃,建议使用name替代。 | +| methodId(deprecated) | string | 是 | 否 | 输入法唯一标识。
**说明:** 从API8开始支持,从API9开始废弃,建议使用id替代。 | +| name9+ | string | 是 | 否 | 输入法内部名称。 | +| id9+ | string | 是 | 否 | 输入法唯一标识。 | +| label9+ | string | 是 | 否 | 输入法对外显示名称。 | +| icon9+ | string | 是 | 否 | 输入法图标数据。 | +| iconId9+ | number | 是 | 否 | 输入法图标资源号。 | +| extra9+ | object | 是 | 否 | 输入法扩展信息。 | -## inputMethod.getInputMethodController +## inputMethod.getController9+ -getInputMethodController(): InputMethodController +getController(): InputMethodController 获取客户端实例[InputMethodController](#inputmethodcontroller)。 -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -49,19 +54,27 @@ getInputMethodController(): InputMethodController | ----------------------------------------------- | ------------------------ | | [InputMethodController](#inputmethodcontroller) | 回调返回当前客户端实例。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800006 | Input method controller error. | + **示例:** ```js - var InputMethodController = inputMethod.getInputMethodController(); +let InputMethodController = inputMethod.getController(); ``` -## inputMethod.getInputMethodSetting8+ +## inputMethod.getSetting9+ -getInputMethodSetting(): InputMethodSetting +getSetting(): InputMethodSetting 获取客户端设置实例[InputMethodSetting](#inputmethodsetting8)。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -69,49 +82,73 @@ getInputMethodSetting(): InputMethodSetting | ----------------------------------------- | ---------------------------- | | [InputMethodSetting](#inputmethodsetting8) | 回调返回当前客户端设置实例。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800007 | Input method settings extension error. | **示例:** ```js - var InputMethodSetting = inputMethod.getInputMethodSetting(); +let InputMethodSetting = inputMethod.getSetting(); ``` + ## inputMethod.switchInputMethod9+ switchInputMethod(target: InputMethodProperty, callback: AsyncCallback<boolean>): void -切换输入法。此接口仅可在Stage模型下使用。使用callback形式返回结果。参数个数为2,否则抛出异常。 +切换输入法。使用callback异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - |target | [InputmethodProperty](#inputmethodproperty8) | 是 | 传入要切换的目标输入法。 | - | callback | AsyncCallback<boolean> | 是 | 返回输入法切换是否成功。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| target | [InputMethodProperty](#inputmethodproperty8) | 是 | 传入要切换的目标输入法。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当输入法切换成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method settings extension error. | **示例:** ```js -inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'} ,(err,result) => { - if (err) { - console.error('switchInputMethod err: ' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Success to switchInputMethod.(callback)'); - } else { - console.error('Failed to switchInputMethod.(callback)'); - } -}); +try{ + inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard', extra: {}}, (err, result) => { + if (err) { + console.error('switchInputMethod err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to switchInputMethod.(callback)'); + } else { + console.error('Failed to switchInputMethod.(callback)'); + } + }); +} catch(err) { + console.error('switchInputMethod err: ' + JSON.stringify(err)); +} ``` ## inputMethod.switchInputMethod9+ switchInputMethod(target: InputMethodProperty): Promise<boolean> -切换输入法。此接口仅可在Stage模型下使用。使用promise形式返回结果。参数个数为1,否则抛出异常。 +切换输入法。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -123,29 +160,42 @@ switchInputMethod(target: InputMethodProperty): Promise<boolean> | 类型 | 说明 | | ----------------------------------------- | ---------------------------- | - | Promise\ | 回调返回切换后的输入法。 | + | Promise\ | Promise对象。返回true表示切换输入法成功;返回false表示切换输入法失败。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method settings extension error. | + +**示例:** ```js -inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}).then((result) => { - if (result) { - console.info('Success to switchInputMethod.(promise)'); - } else { - console.error('Failed to switchInputMethod.(promise)'); - } -}).catch((err) => { - console.error('switchInputMethod promise err: ' + err); -}) +try { + inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard', extra: {}}).then((result) => { + if (result) { + console.info('Success to switchInputMethod.'); + } else { + console.error('Failed to switchInputMethod.'); + } + }).catch((err) => { + console.error('switchInputMethod err: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('switchInputMethod err: ' + JSON.stringify(err)); +} ``` + ## inputMethod.getCurrentInputMethod9+ getCurrentInputMethod(): InputMethodProperty -获取当前输入法扩展应用,提供同步接口,返回当前输入法属性对象。 +获取当前输入法扩展应用,提供同步接口,返回当前输入法属性。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -155,79 +205,413 @@ getCurrentInputMethod(): InputMethodProperty **示例:** +```js +let currentIme = inputMethod.getCurrentInputMethod(); +``` + +## inputMethod.switchCurrentInputMethodSubtype9+ + +switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallback\): void + +在当前输入法应用内切换子类型。使用callback异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| 是 | 传入要切换的目标输入法子类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当输入法子类型切换成功,err为undefined,data为true;否则为错误对象。| + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +let inputMethodSubtype = { + id: "com.example.kikainput", + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} +} +try { + inputMethod.switchCurrentInputMethodSubtype(inputMethodSubtype, (err, result) => { + if (err) { + console.error('switchCurrentInputMethodSubtype err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to switchCurrentInputMethodSubtype.(callback)'); + } else { + console.error('Failed to switchCurrentInputMethodSubtype.(callback)'); + } + }); +} catch(err) { + console.error('switchCurrentInputMethodSubtype err: ' + JSON.stringify(err)); +} +``` + +## inputMethod.switchCurrentInputMethodSubtype9+ + +switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean> + +在当前输入法应用内切换子类型。使用promise异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +|target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| 是 | 传入要切换的目标输入法子类型。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise对象。返回true表示在当前输入法应用内切换子类型成功;返回false表示在当前输入法应用内切换子类型失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +let inputMethodSubtype = { + id: "com.example.kikainput", + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} +} +try { + inputMethod.switchCurrentInputMethodSubtype(inputMethodSubtype).then((result) => { + if (result) { + console.info('Success to switchCurrentInputMethodSubtype.'); + } else { + console.error('Failed to switchCurrentInputMethodSubtype.'); + } + }).catch((err) => { + console.error('switchCurrentInputMethodSubtype err: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('switchCurrentInputMethodSubtype err: ' + JSON.stringify(err)); +} +``` + +## inputMethod.getCurrentInputMethodSubtype9+ + +getCurrentInputMethodSubtype(): InputMethodSubtype + +获取当前输入法子类型。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| -------------------------------------------- | ------------------------ | +| [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype) | 返回当前输入法子类型对象。 | + +**示例:** + +```js +let currentImeSubType = inputMethod.getCurrentInputMethodSubtype(); +``` + +## inputMethod.switchCurrentInputMethodAndSubtype9+ + +switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype, callback: AsyncCallback\): void + +切换至指定输入法应用的指定子类型,用于跨输入法应用切换子类型。使用callback异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +|inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| 是 | 传入要切换的目标输入法。 | +|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| 是 | 传入要切换的目标输入法子类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当输入法和子类型切换成功,err为undefined,data为获取到的切换子类型结果true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +let inputMethodProperty = { + packageName: "com.example.kikakeyboard", + methodId: "ServiceExtAbility", + extra: {} +} +let inputMethodSubProperty = { + id: "com.example.kikainput", + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} +} +try { + inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, inputMethodSubProperty, (err,result) => { + if (err) { + console.error('switchCurrentInputMethodAndSubtype err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to switchCurrentInputMethodAndSubtype.(callback)'); + } else { + console.error('Failed to switchCurrentInputMethodAndSubtype.(callback)'); + } + }); +} catch (err) { + console.error('switchCurrentInputMethodAndSubtype err: ' + JSON.stringify(err)); +} +``` + +## inputMethod.switchCurrentInputMethodAndSubtype9+ + +switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype): Promise<boolean> + +切换至指定输入法应用的指定子类型,用于跨输入法应用切换子类型。使用promise异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +|inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| 是 | 传入要切换的目标输入法。 | +|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| 是 | 传入要切换的目标输入法子类型。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise对象。返回true表示切换至指定输入法应用的指定子类型成功;返回false表示切换至指定输入法应用的指定子类型失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +let inputMethodProperty = { + name: "com.example.kikakeyboard", + id: "ServiceExtAbility" +} +let inputMethodSubProperty = { + id: "com.example.kikakeyboard", + name: "", + locale: "", + label: "ServiceExtAbility", + language: "", + extra : {} +} +try { + inputMethod.switchCurrentInputMethodAndSubtype(property, subType).then((result) => { + if (result) { + console.info('Success to switchCurrentInputMethodAndSubtype.'); + } else { + console.error('Failed to switchCurrentInputMethodAndSubtype.'); + } + }).catch((err) => { + console.error('switchCurrentInputMethodAndSubtype err: ' + err); + }) +} catch(err) { + console.error('switchCurrentInputMethodAndSubtype err: ' + err); +} +``` + +## inputMethod.getInputMethodController(deprecated) + +getInputMethodController(): InputMethodController + +获取客户端实例[InputMethodController](#inputmethodcontroller)。 + +> **说明:** +> +> 从API version 6开始支持,从API version 9开始废弃, 建议使用[getController()](#inputmethodgetcontroller9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------- | ------------------------ | +| [InputMethodController](#inputmethodcontroller) | 回调返回当前客户端实例。 | + +**示例:** + +```js +let InputMethodController = inputMethod.getInputMethodController(); +``` + +## inputMethod.getInputMethodSetting(deprecated) + +getInputMethodSetting(): InputMethodSetting + +获取客户端设置实例[InputMethodSetting](#inputmethodsetting8)。 + +> **说明:**
从API version 6开始支持,从API version 9开始废弃, 建议使用[getSetting()](#inputmethodgetsetting9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------- | ---------------------------- | +| [InputMethodSetting](#inputmethodsetting8) | 回调返回当前客户端设置实例。 | + +**示例:** ```js -var currentIme = inputMethod.getCurrentInputMethod(); +let InputMethodSetting = inputMethod.getInputMethodSetting(); ``` ## InputMethodController -下列API示例中都需使用[getInputMethodController](#inputmethodgetinputmethodcontroller)回调获取到InputMethodController实例,再通过此实例调用对应方法。 +下列API示例中都需使用[getController](#inputmethodgetcontroller9)回调获取到InputMethodController实例,再通过此实例调用对应方法。 -### stopInput +### stopInputSession9+ -stopInput(callback: AsyncCallback<boolean>): void +stopInputSession(callback: AsyncCallback<boolean>): void -隐藏输入法。使用callback形式返回结果。参数个数为1,否则抛出异常。 +结束输入会话。使用callback异步回调。 -**系统能力**:SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | 是 | 返回输入法隐藏是否成功。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当输入法隐藏成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method settings extension error. | **示例:** ```js -InputMethodController.stopInput((error, result) => { - if (error) { - console.error('failed to stopInput because: ' + JSON.stringify(error)); - return; - } - if (result) { - console.info('Success to stopInput.(callback)'); - } else { - console.error('Failed to stopInput.(callback)'); - } -}); +try { + InputMethodController.stopInputSession((error, result) => { + if (error) { + console.error('stopInputSession err: ' + JSON.stringify(error)); + return; + } + if (result) { + console.info('Success to stopInputSession.(callback)'); + } else { + console.error('Failed to stopInputSession.(callback)'); + } + }); +} catch(error) { + console.error('stopInputSession err: ' + JSON.stringify(error)); +} ``` -### stopInput +### stopInputSession9+ -stopInput(): Promise<boolean> +stopInputSession(): Promise<boolean> -隐藏输入法。使用promise形式返回结果。参数个数为0,否则抛出异常。 +结束输入会话。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** | 类型 | 说明 | | -------- | -------- | -| Promise<boolean> | 返回输入法隐藏是否成功。 | +| Promise<boolean> | Promise对象。返回true表示输入法隐藏成功;返回false表示输入法隐藏失败。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method settings extension error. | + +**示例:** ```js -InputMethodController.stopInput().then((result) => { - if (result) { - console.info('Success to stopInput.(promise)'); - } else { - console.error('Failed to stopInput.(promise)'); - } -}).catch((err) => { - console.error('stopInput promise err: ' + err); -}) +try { + InputMethodController.stopInputSession().then((result) => { + if (result) { + console.info('Success to stopInputSession.'); + } else { + console.error('Failed to stopInputSession.'); + } + }).catch((err) => { + console.error('stopInputSession err: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('stopInputSession err: ' + JSON.stringify(err)); +} ``` -### showSoftKeyboard9+ ### +### showSoftKeyboard9+ showSoftKeyboard(callback: AsyncCallback<void>): void -显示软键盘,使用callback异步回调。参数个数为1,否则抛出异常。 +显示软键盘。使用callback异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY **系统能力:** SystemCapability.MiscServices.InputMethodFramework @@ -235,7 +619,16 @@ showSoftKeyboard(callback: AsyncCallback<void>): void | 参数名 | 参数类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当软键盘显示成功。err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method settings extension error. | **示例:** @@ -249,12 +642,13 @@ InputMethodController.showSoftKeyboard((err) => { }) ``` - -### showSoftKeyboard9+ ### +### showSoftKeyboard9+ showSoftKeyboard(): Promise<void> -显示软键盘,使用Promise异步回调。参数个数为0,否则抛出异常。 +显示软键盘,使用Promise异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY **系统能力:** SystemCapability.MiscServices.InputMethodFramework @@ -264,21 +658,32 @@ showSoftKeyboard(): Promise<void> | ------------------- | ------------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method settings extension error. | + **示例:** ```js InputMethodController.showSoftKeyboard().then(async (err) => { console.log('showSoftKeyboard success'); }).catch((err) => { - console.error('showSoftKeyboard promise err: ' + JSON.stringify(err)); + console.error('showSoftKeyboard err: ' + JSON.stringify(err)); }); ``` -### hideSoftKeyboard9+ ### +### hideSoftKeyboard9+ hideSoftKeyboard(callback: AsyncCallback<void>): void -隐藏软键盘,使用callback异步回调。参数个数为1,否则抛出异常。 +隐藏软键盘。使用callback异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY **系统能力:** SystemCapability.MiscServices.InputMethodFramework @@ -286,7 +691,16 @@ hideSoftKeyboard(callback: AsyncCallback<void>): void | 参数名 | 参数类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当软键盘隐藏成功。err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method settings extension error. | **示例:** @@ -300,13 +714,14 @@ InputMethodController.hideSoftKeyboard((err) => { }) ``` - -### hideSoftKeyboard9+ ### +### hideSoftKeyboard9+ hideSoftKeyboard(): Promise<void> 隐藏软键盘,使用Promise异步回调。参数个数为0,否则抛出异常。 +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + **系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -315,54 +730,358 @@ hideSoftKeyboard(): Promise<void> | ------------------- | ------------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method settings extension error. | + **示例:** ```js InputMethodController.hideSoftKeyboard().then(async (err) => { console.log('hideSoftKeyboard success'); }).catch((err) => { - console.error('hideSoftKeyboard promise err: ' + JSON.stringify(err)); + console.error('hideSoftKeyboard err: ' + JSON.stringify(err)); }); ``` +### stopInput(deprecated) + +stopInput(callback: AsyncCallback<boolean>): void + +结束输入会话。使用callback异步回调。 + +> **说明:** +> +> 从API version 6开始支持,从API version 9开始废弃, 建议使用[stopInputSession()](#stopinputsession9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当输入法隐藏成功,err为undefined,data为true;否则为错误对象。 | + +**示例:** + +```js +InputMethodController.stopInput((error, result) => { + if (error) { + console.error('failed to stopInput because: ' + JSON.stringify(error)); + return; + } + if (result) { + console.info('Success to stopInput.(callback)'); + } else { + console.error('Failed to stopInput.(callback)'); + } +}); +``` + +### stopInput(deprecated) + +stopInput(): Promise<boolean> + +结束输入会话。使用promise异步回调。 + +> **说明:** +> +> 从API version 6开始支持,从API version 9开始废弃, 建议使用[stopInputSession()](#stopinputsession9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<boolean> | Promise对象。返回true表示输入法隐藏成功;返回false表示输入法隐藏失败。 | + +**示例:** + +```js +InputMethodController.stopInput().then((result) => { + if (result) { + console.info('Success to stopInput.'); + } else { + console.error('Failed to stopInput.'); + } +}).catch((err) => { + console.error('stopInput err: ' + err); +}) +``` + ## InputMethodSetting8+ -下列API示例中都需使用[getInputMethodSetting](#inputmethodgetinputmethodcontroller)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。 +下列API示例中都需使用[getSetting](#inputmethodgetsetting9)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。 + +### on('imeChange')9+ + +on(type: 'imeChange', callback: (inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype) => void): void + +订阅输入法及子类型变化监听事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘imeChange’时表示订阅输入法及子类型变化监听事件。 | +| callback | [InputMethodProperty](#inputmethodproperty8), [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype) | 是 | 回调函数,返回输入法属性对象及输入法子类型对象。 | + +**示例:** + +```js +let InputMethodSetting = inputMethod.getSetting(); +InputMethodSetting.on('imeChange', (inputMethodProperty, inputMethodSubtype) => { + InputMethodProperty = inputMethodProperty; + InputMethodSubtype = inputMethodSubtype; +}); +``` -### listInputMethod9+ +### off('imeChange')9+ -listInputMethod(enable: boolean, callback: AsyncCallback<Array<InputMethodProperty>>): void +off(type: 'imeChange', callback?: (inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype) => void): void -获取已激活/未激活输入法列表。参数enable取true,返回已激活输入法列表,取false返回未激活输入法列表。使用callback形式返回结果。参数个数为2,否则抛出异常。 +取消订阅输入法及子类型变化监听事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘imeChange’时表示取消订阅输入法及子类型变化监听事件。 | +| callback | [InputMethodProperty](#inputmethodproperty8), [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype) | 否 | 回调函数,返回取消订阅的输入法属性对象及输入法子类型对象。 | + +**示例:** + +```js +let InputMethodSetting = inputMethod.getSetting(); +InputMethodSetting.off('imeChange'); +``` + +### listInputMethodSubtype9+ + +listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: AsyncCallback<Array<InputMethodSubtype>>): void + +获取指定输入法应用的所有子类型。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------------- | ---- | ---------------------- | +| inputMethodProperty | InputMethodProperty| 是 | 指定获取子类型所属的输入法应用。 | +| callback | Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)> | 是 | 回调函数,返回指定输入法应用的所有子类型。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +let inputMethodProperty = { + packageName:'com.example.kikakeyboard', + methodId:'com.example.kikakeyboard', + extra:{} +} +try { + InputMethodSetting.listInputMethodSubtype(inputMethodProperty, (err,data) => { + if (err) { + console.error('listInputMethodSubtype failed: ' + JSON.stringify(err)); + return; + } + console.log('listInputMethodSubtype success'); + }); +} catch (err) { + console.error('listInputMethodSubtype failed: ' + JSON.stringify(err)); +} +``` + +### listInputMethodSubtype9+ + +listInputMethodSubtype(inputMethodProperty: InputMethodProperty): Promise<Array<InputMethodSubtype>> + +获取指定输入法应用的所有子类型。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------------- | ---- | ---------------------- | +| inputMethodProperty | InputMethodProperty| 是 | 指定获取子类型所属的输入法应用。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | ---------------------- | +| Promise> | Promise对象,返回已安装输入法子类型列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +let inputMethodProperty = { + packageName:'com.example.kikakeyboard', + methodId:'com.example.kikakeyboard', + extra:{} +} +try { + InputMethodSetting.listInputMethodSubtype(inputMethodProperty).then((data) => { + console.info('listInputMethodSubtype success'); + }).catch((err) => { + console.error('listInputMethodSubtype err: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('listInputMethodSubtype err: ' + JSON.stringify(err)); +} +``` + +### listCurrentInputMethodSubtype9+ + +listCurrentInputMethodSubtype(callback: AsyncCallback<Array<InputMethodSubtype>>): void + +查询当前输入法应用的所有子类型。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------------- | ---- | ---------------------- | +| callback | Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)> | 是 | 回调函数,返回当前输入法应用的所有子类型。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +try { + InputMethodSetting.listCurrentInputMethodSubtype((err, data) => { + if (err) { + console.error('listCurrentInputMethodSubtype failed: ' + JSON.stringify(err)); + return; + } + console.log('listCurrentInputMethodSubtype success'); + }); +} catch(err) { + console.error('listCurrentInputMethodSubtype err: ' + JSON.stringify(err)); +} +``` + +### listCurrentInputMethodSubtype9+ + +listCurrentInputMethodSubtype(): Promise<Array<InputMethodSubtype>> + +查询当前输入法的子类型列表。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | ---------------------- | +| Promise> | Promise对象,返回当前输入法的子类型列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +try { + InputMethodSetting.listCurrentInputMethodSubtype().then((data) => { + console.info('listCurrentInputMethodSubtype success'); + }).catch((err) => { + console.error('listCurrentInputMethodSubtype err: ' + err); + }) +} catch(err) { + console.error('listCurrentInputMethodSubtype err: ' + JSON.stringify(err)); +} +``` + +### getInputMethods9+ + +getInputMethods(enable: boolean, callback: AsyncCallback<Array<InputMethodProperty>>): void + +获取已激活/未激活输入法列表。参数enable取true,返回已激活输入法列表,取false返回未激活输入法列表。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ----------------------------- | | enable | boolean | 是 | 指定返回已激活/未激活。 | -| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | 是 | 返回已激活/未激活输入法列表。 | +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | 是 | 回调函数,返回已激活/未激活输入法列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method settings extension error. | **示例:** ```js -InputMethodSetting.listInputMethod(true, (err,data) => { - if (err) { - console.error('listInputMethod failed because: ' + JSON.stringify(err)); - return; - } - console.log('listInputMethod success'); - }); +try { + InputMethodSetting.getInputMethods(true, (err,data) => { + if (err) { + console.error('getInputMethods failed: ' + JSON.stringify(err)); + return; + } + console.log('getInputMethods success'); + }); +} catch (err) { + console.error('getInputMethods failed: ' + JSON.stringify(err)); +} ``` -### listInputMethod9+ +### getInputMethods9+ -listInputMethod(enable: boolean): Promise<Array<InputMethodProperty>> +getInputMethods(enable: boolean): Promise<Array<InputMethodProperty>> -获取已激活/未激活输入法列表。参数enable取true返回已激活输入法列表,取false返回未激活输入法列表。使用promise形式返回结果。参数个数为0,否则抛出异常。 +获取已激活/未激活输入法列表。参数enable取true返回已激活输入法列表,取false返回未激活输入法列表。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -370,35 +1089,126 @@ listInputMethod(enable: boolean): Promise<Array<InputMethodProperty>> | ------ | ------- | ---- | ----------------------- | | enable | boolean | 是 | 指定返回已激活/未激活。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method settings extension error. | + **返回值:** | 类型 | 说明 | | ------------------------------------------------------------ | ----------------------------- | -| Promise> | 返回已激活/未激活输入法列表。 | +| Promise> | Promise对象,返回已激活/未激活输入法列表。 | **示例:** ```js -InputMethodSetting.listInputMethod(true).then((data) => { - console.info('listInputMethod success'); +try { + InputMethodSetting.getInputMethods(true).then((data) => { + console.info('getInputMethods success'); + }).catch((err) => { + console.error('getInputMethods err: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('getInputMethods err: ' + JSON.stringify(err)); +} +``` + +### showOptionalInputMethods9+ + +showOptionalInputMethods(callback: AsyncCallback<boolean>): void + +显示输入法选择对话框。使用callback异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当输入法选择对话框显示成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +try { + InputMethodSetting.showOptionalInputMethods((err, data) => { + if (err) { + console.error('showOptionalInputMethods failed: ' + JSON.stringify(err)); + return; + } + console.info('showOptionalInputMethods success'); + }); +} catch (err) { + console.error('showOptionalInputMethods failed: ' + JSON.stringify(err)); +} +``` + +### showOptionalInputMethods9+ + +showOptionalInputMethods(): Promise<boolean> + +显示输入法选择对话框。使用promise异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<boolean> | Promise对象。返回true表示输入法选择对话框显示成功;返回false表示输入法选择对话框显示失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 12800008 | Input method settings extension error. | + +**示例:** + +```js +InputMethodSetting.showOptionalInputMethods().then((data) => { + console.info('displayOptionalInputMethod success.'); }).catch((err) => { - console.error('listInputMethod promise err: ' + err); + console.error('displayOptionalInputMethod err: ' + err); }) ``` -### listInputMethod +### listInputMethod(deprecated) listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>): void -查询已安装的输入法列表。使用callback形式返回结果。参数个数为1,否则抛出异常。 +查询已安装的输入法列表。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,从API version 9开始废弃, 建议使用[getInputMethods](#getinputmethods9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------------- | ---- | ---------------------- | -| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | 是 | 返回已安装输入法列表。 | +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | 是 | 回调函数,返回已安装的输入法列表。 | **示例:** @@ -412,19 +1222,23 @@ InputMethodSetting.listInputMethod((err,data) => { }); ``` -### listInputMethod +### listInputMethod(deprecated) listInputMethod(): Promise<Array<InputMethodProperty>> -查询已安装的输入法列表。使用promise形式返回结果。参数个数为0,否则抛出异常。 +查询已安装的输入法列表。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,从API version 9开始废弃, 建议使用[getInputMethods](#getinputmethods9-1)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** | 类型 | 说明 | | ----------------------------------------------------------- | ---------------------- | -| Promise> | 返回已安装输入法列表。 | +| Promise> | Promise对象,返回已安装输入法列表。 | **示例:** @@ -432,23 +1246,27 @@ listInputMethod(): Promise<Array<InputMethodProperty>> InputMethodSetting.listInputMethod().then((data) => { console.info('listInputMethod success'); }).catch((err) => { - console.error('listInputMethod promise err: ' + err); + console.error('listInputMethod err: ' + JSON.stringify(err)); }) ``` -### displayOptionalInputMethod +### displayOptionalInputMethod(deprecated) displayOptionalInputMethod(callback: AsyncCallback<void>): void -显示输入法选择对话框。使用callback形式返回结果。参数个数为1,否则抛出异常。 +显示输入法选择对话框。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,从API version 9开始废弃, 建议使用[showOptionalInputMethods()](#showoptionalinputmethods9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当输入法选择对话框显示成功。err为undefined,否则为错误对象。 | **示例:** @@ -462,13 +1280,17 @@ InputMethodSetting.displayOptionalInputMethod((err) => { }); ``` -### displayOptionalInputMethod +### displayOptionalInputMethod(deprecated) + +displayOptionalInputMethod(): Promise<void> - displayOptionalInputMethod(): Promise<void> +显示输入法选择对话框。使用promise异步回调。 - 显示输入法选择对话框。使用promise形式返回结果。参数个数为0,否则抛出异常。 +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[showOptionalInputMethods()](#showoptionalinputmethods9-1)替代。 - **系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -480,8 +1302,8 @@ InputMethodSetting.displayOptionalInputMethod((err) => { ```js InputMethodSetting.displayOptionalInputMethod().then(() => { - console.info('displayOptionalInputMethod success.(promise)'); + console.info('displayOptionalInputMethod success'); }).catch((err) => { - console.error('displayOptionalInputMethod promise err: ' + err); + console.error('displayOptionalInputMethod err: ' + err); }) -``` \ No newline at end of file +``` 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 40bbe0fdb9bee5e1d71374c064528a423a758ed9..d441dc68018c365df774f93d1bb3c582b5dab978 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,9 +1,10 @@ # 输入法服务 - 本模块的作用是拉通应用和输入法,保证应用可以通过输入法进行文本输入,以及应用与输入法服务的绑定、应用对输入法的显示和隐藏请求、监听输入法当前的状态等等。 +本模块的作用是拉通输入法应用和其他三方应用(联系人、微信等),功能包括:将三方应用与输入法应用的服务进行绑定、三方应用通过输入法应用进行文本输入、三方应用对输入法应用进行显示键盘请求和隐藏键盘请求、三方应用对输入法应用当前状态进行监听等。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> **说明:** +> +>本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -11,146 +12,295 @@ import inputMethodEngine from '@ohos.inputmethodengine'; ``` -## inputMethodEngine - -常量值。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework - -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| ENTER_KEY_TYPE_UNSPECIFIED | number | 是 | 否 | 无功能键。 | -| ENTER_KEY_TYPE_GO | number | 是 | 否 | “前往”功能键。 | -| ENTER_KEY_TYPE_SEARCH | number | 是 | 否 | “搜索”功能键。 | -| ENTER_KEY_TYPE_SEND | number | 是 | 否 | “发送”功能键。 | -| ENTER_KEY_TYPE_NEXT | number | 是 | 否 | “下一个”功能键。 | -| ENTER_KEY_TYPE_DONE | number | 是 | 否 | “回车”功能键。 | -| ENTER_KEY_TYPE_PREVIOUS | number | 是 | 否 | “前一个”功能键。 | -| PATTERN_NULL | number | 是 | 否 | 无特殊性编辑框。 | -| PATTERN_TEXT | number | 是 | 否 | 文本编辑框。 | -| PATTERN_NUMBER | number | 是 | 否 | 数字编辑框。 | -| PATTERN_PHONE | number | 是 | 否 | 电话号码编辑框。 | -| PATTERN_DATETIME | number | 是 | 否 | 日期编辑框。 | -| PATTERN_EMAIL | number | 是 | 否 | 邮件编辑框。 | -| PATTERN_URI | number | 是 | 否 | 超链接编辑框。 | -| PATTERN_PASSWORD | number | 是 | 否 | 密码编辑框。 | -| OPTION_ASCII | number | 是 | 否 | 允许输入ASCII值。 | -| OPTION_NONE | number | 是 | 否 | 不指定编辑框输入属性。 | -| OPTION_AUTO_CAP_CHARACTERS | number | 是 | 否 | 允许输入字符。 | -| OPTION_AUTO_CAP_SENTENCES | number | 是 | 否 | 允许输入句子。 | -| OPTION_AUTO_WORDS | number | 是 | 否 | 允许输入单词。 | -| OPTION_MULTI_LINE | number | 是 | 否 | 允许输入多行。 | -| OPTION_NO_FULLSCREEN | number | 是 | 否 | 半屏样式。 | -| FLAG_SELECTING | number | 是 | 否 | 编辑框处于选择状态。 | -| FLAG_SINGLE_LINE | number | 是 | 否 | 编辑框为单行。 | -| DISPLAY_MODE_PART | number | 是 | 否 | 编辑框显示为半屏。 | -| DISPLAY_MODE_FULL | number | 是 | 否 | 编辑框显示为全屏。 | -| CURSOR_UP9+ | number | 是 | 否 | 光标上移。 | -| CURSOR_DOWN9+ | number | 是 | 否 | 光标下移。 | -| CURSOR_LEFT9+ | number | 是 | 否 | 光标左移。 | -| CURSOR_RIGHT9+ | number | 是 | 否 | 光标右移。 | -| WINDOW_TYPE_INPUT_METHOD_FLOAT9+ | number | 是 | 否 | 输入法应用窗口风格标识。 | - -## inputMethodEngine.getInputMethodEngine +## 常量 + +功能键常量值、编辑框常量值及光标常量值。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 参数类型 | 值 | 说明 | +| -------- | -------- | -------- | -------- | +| ENTER_KEY_TYPE_UNSPECIFIED | number | 0 | 无功能键。 | +| ENTER_KEY_TYPE_GO | number | 2 | “前往”功能键。 | +| ENTER_KEY_TYPE_SEARCH | number | 3 | “搜索”功能键。 | +| ENTER_KEY_TYPE_SEND | number | 4 | “发送”功能键。 | +| ENTER_KEY_TYPE_NEXT | number | 5 | “下一个”功能键。 | +| ENTER_KEY_TYPE_DONE | number | 6 | “回车”功能键。 | +| ENTER_KEY_TYPE_PREVIOUS | number | 7 | “前一个”功能键。 | +| PATTERN_NULL | number | -1 | 无特殊性编辑框。 | +| PATTERN_TEXT | number | 0 | 文本编辑框。 | +| PATTERN_NUMBER | number | 2 | 数字编辑框。 | +| PATTERN_PHONE | number | 3 | 电话号码编辑框。 | +| PATTERN_DATETIME | number | 4 | 日期编辑框。 | +| PATTERN_EMAIL | number | 5 | 邮件编辑框。 | +| PATTERN_URI | number | 6 | 超链接编辑框。 | +| PATTERN_PASSWORD | number | 7 | 密码编辑框。 | +| OPTION_ASCII | number | 20 | 允许输入ASCII值。 | +| OPTION_NONE | number | 0 | 不指定编辑框输入属性。 | +| OPTION_AUTO_CAP_CHARACTERS | number | 2 | 允许输入字符。 | +| OPTION_AUTO_CAP_SENTENCES | number | 8 | 允许输入句子。 | +| OPTION_AUTO_WORDS | number | 4 | 允许输入单词。 | +| OPTION_MULTI_LINE | number | 1 | 允许输入多行。 | +| OPTION_NO_FULLSCREEN | number | 10 | 半屏样式。 | +| FLAG_SELECTING | number | 2 | 编辑框处于选择状态。 | +| FLAG_SINGLE_LINE | number | 1 | 编辑框为单行。 | +| DISPLAY_MODE_PART | number | 0 | 编辑框显示为半屏。 | +| DISPLAY_MODE_FULL | number | 1 | 编辑框显示为全屏。 | +| CURSOR_UP9+ | number | 1 | 光标上移。 | +| CURSOR_DOWN9+ | number | 2 | 光标下移。 | +| CURSOR_LEFT9+ | number | 3 | 光标左移。 | +| CURSOR_RIGHT9+ | number | 4 | 光标右移。 | +| WINDOW_TYPE_INPUT_METHOD_FLOAT9+ | number | 2105 | 输入法应用窗口风格标识。 | + +## inputMethodEngine.getInputMethodAbility9+ + +getInputMethodAbility(): InputMethodAbility + +获取服务端实例。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | ------------ | +| [InputMethodAbility](#inputmethodability) | 服务端实例。 | + +**示例:** + +```js +let InputMethodAbility = inputMethodEngine.getInputMethodAbility(); +``` + +## inputMethodEngine.getKeyboardDelegate9+ + +getKeyboardDelegate(): KeyboardDelegate + +获取客户端监听实例。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------- | ---------------- | +| [KeyboardDelegate](#keyboarddelegate) | 客户端监听实例。 | + +**示例:** + +```js +let KeyboardDelegate = inputMethodEngine.getKeyboardDelegate(); +``` + +## inputMethodEngine.getInputMethodEngine(deprecated) getInputMethodEngine(): InputMethodEngine 获取服务端实例。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +>从API version 8开始支持,API version 9开始废弃, 建议使用[getInputMethodAbility()](#inputmethodenginegetinputmethodability9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** | 类型 | 说明 | | --------------------------------------- | ------------ | -| [InputMethodEngine](#InputMethodEngine) | 服务端实例。 | +| [InputMethodEngine](#inputmethodengine-1) | 服务端实例。 | **示例:** - ```js - var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); - ``` +```js +let InputMethodEngine = inputMethodEngine.getInputMethodEngine(); +``` -## inputMethodEngine.createKeyboardDelegate +## inputMethodEngine.createKeyboardDelegate(deprecated) createKeyboardDelegate(): KeyboardDelegate 获取客户端监听实例。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +>从API version 8开始支持,API version 9开始废弃, 建议使用[getKeyboardDelegate()](#inputmethodenginegetkeyboarddelegate9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** | 类型 | 说明 | | ------------------------------------- | ---------------- | -| [KeyboardDelegate](#KeyboardDelegate) | 客户端监听实例。 | +| [KeyboardDelegate](#keyboarddelegate) | 客户端监听实例。 | **示例:** - ```js - var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); - ``` +```js +let KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); +``` -## InputMethodEngine +## InputMethodEngine -下列API示例中都需使用[getInputMethodEngine](#getInputMethodEngine)回调获取到InputMethodEngine实例,再通过此实例调用对应方法。 +下列API示例中都需使用[getInputMethodEngine](#inputmethodenginegetinputmethodenginedeprecated)回调获取到InputMethodEngine实例,再通过此实例调用对应方法。 -### on('inputStart') +### on('inputStart') on(type: 'inputStart', callback: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -订阅输入法绑定成功事件,使用callback回调返回输入法操作相关实例。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅输入法绑定成功事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 设置监听类型。
-type为‘inputStart’时表示订阅输入法绑定。 | -| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | 是 | 回调返回输入法操作相关实例。 | +| callback | [KeyboardController](#keyboardcontroller), [TextInputClient](#textinputclient) | 是 | 回调函数,返回订阅输入法的KeyboardController和TextInputClient实例。 | **示例:** - ```js - InputMethodEngine.on('inputStart', (kbController, textInputClient) => { - KeyboardController = kbController; - TextInputClient = textInputClient; - }); - ``` +```js +inputMethodEngine.getInputMethodEngine().on('inputStart', (kbController, textInputClient) => { + KeyboardController = kbController; + TextInputClient = textInputClient; +}); +``` ### off('inputStart') off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -取消订阅输入法绑定成功事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅输入法绑定成功事件。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------ | | type | string | 是 | 设置监听类型。
-type为‘inputStart’时表示订阅输入法绑定。 | -| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | 否 | 回调返回输入法操作相关实例。 | +| callback | [KeyboardController](#keyboardcontroller), [TextInputClient](#textinputclient) | 否 | 回调函数,返回取消订阅的KeyboardController和TextInputClient实例。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodEngine().off('inputStart', (kbController, textInputClient) => { + console.log('delete inputStart notification.'); +}); +``` + +### on('keyboardShow'|'keyboardHide') + +on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void + +订阅输入法事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为'keyboardShow',表示订阅输入法显示。
- type为'keyboardHide',表示订阅输入法隐藏。 | +| callback | void | 否 | 回调函数。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodEngine().on('keyboardShow', () => { + console.log('inputMethodEngine keyboardShow.'); +}); +inputMethodEngine.getInputMethodEngine().on('keyboardHide', () => { + console.log('inputMethodEngine keyboardHide.'); +}); +``` + +### off('keyboardShow'|'keyboardHide') + +off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void + +取消订阅输入法事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为'keyboardShow',表示订阅输入法显示。
- type为'keyboardHide',表示订阅输入法隐藏。 | +| callback | void | 否 | 回调函数。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodEngine().off('keyboardShow', () => { + console.log('inputMethodEngine delete keyboardShow notification.'); +}); +inputMethodEngine.getInputMethodEngine().off('keyboardHide', () => { + console.log('inputMethodEngine delete keyboardHide notification.'); +}); +``` + +## InputMethodAbility + +下列API示例中都需使用[getInputMethodAbility](#inputmethodenginegetinputmethodability9)回调获取到InputMethodAbility实例,再通过此实例调用对应方法。 + +### on('inputStart')9+ + +on(type: 'inputStart', callback: (kbController: KeyboardController, inputClient: InputClient) => void): void + +订阅输入法绑定成功事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘inputStart’时表示订阅输入法绑定。 | +| callback | [KeyboardController](#keyboardcontroller), [InputClient](#inputclient9) | 是 | 回调函数,返回输入法操作相关实例。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().on('inputStart', (kbController, inputClient) => { + KeyboardController = kbController; + InputClient = inputClient; +}); +``` + +### off('inputStart')9+ + +off(type: 'inputStart', callback?: (kbController: KeyboardController, inputClient: InputClient) => void): void + +取消订阅输入法绑定成功事件。使用callback异步回调。 +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘inputStart’时表示订阅输入法绑定。 | +| callback | [KeyboardController](#keyboardcontroller), [InputClient](#inputclient9) | 否 | 回调函数,返回输入法操作相关实例。 | **示例:** - ```js - InputMethodEngine.off('inputStart', (kbController, textInputClient) => { - console.log('delete inputStart notification.'); - }); - ``` +```js +inputMethodEngine.getInputMethodAbility().off('inputStart', (kbController, inputClient) => { + console.log('delete inputStart notification.'); +}); +``` ### on('inputStop')9+ on(type: 'inputStop', callback: () => void): void -订阅停止输入法应用事件,使用callback回调。 +订阅停止输入法应用事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -161,19 +311,19 @@ on(type: 'inputStop', callback: () => void): void **示例:** - ```js -InputMethodEngine.getInputMethodEngine().on('inputStop', () => { - console.log('inputMethodEngine inputStop'); +```js +inputMethodEngine.getInputMethodAbility().on('inputStop', () => { + console.log('inputMethodAbility inputStop'); }); - ``` +``` ### off('inputStop')9+ off(type: 'inputStop', callback: () => void): void -取消订阅停止输入法应用事件。使用callback回调。 +取消订阅停止输入法应用事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -184,65 +334,65 @@ off(type: 'inputStop', callback: () => void): void **示例:** - ```js -InputMethodEngine.getInputMethodEngine().off('inputStop', () => { - console.log('inputMethodEngine delete inputStop notification.'); +```js +inputMethodEngine.getInputMethodAbility().off('inputStop', () => { + console.log('inputMethodAbility delete inputStop notification.'); }); - ``` +``` ### on('setCallingWindow')9+ on(type: 'setCallingWindow', callback: (wid:number) => void): void -订阅设置调用窗口事件,使用callback回调。 +订阅设置调用窗口事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 设置监听类型。
-type为‘setCallingWindow’时表示订阅设置调用窗口事件。 | -| callback | number | 是 | 调用方window id。 | +| callback | number | 是 | 回调函数,返回调用方window id。 | **示例:** - ```js -InputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => { - console.log('inputMethodEngine setCallingWindow'); +```js +inputMethodEngine.getInputMethodAbility().on('setCallingWindow', (wid) => { + console.log('inputMethodAbility setCallingWindow'); }); - ``` +``` ### off('setCallingWindow')9+ off(type: 'setCallingWindow', callback: (wid:number) => void): void -取消订阅设置调用窗口事件。使用callback回调。 +取消订阅设置调用窗口事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 设置监听类型。
-type为‘setCallingWindow’时表示订阅设置调用窗口事件。 | -| callback | number | 是 | 调用方window id。 | +| callback | number | 是 | 回调函数,返回调用方window id。 | **示例:** - ```js -InputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => { - console.log('inputMethodEngine delete setCallingWindow notification.'); +```js +inputMethodEngine.getInputMethodAbility().off('setCallingWindow', () => { + console.log('inputMethodAbility delete setCallingWindow notification.'); }); - ``` +``` -### on('keyboardShow'|'keyboardHide') +### on('keyboardShow'|'keyboardHide')9+ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -订阅输入法事件。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅输入法事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -253,22 +403,22 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void **示例:** - ```js - InputMethodEngine.on('keyboardShow', () => { - console.log('inputMethodEngine keyboardShow.'); - }); - InputMethodEngine.on('keyboardHide', () => { - console.log('inputMethodEngine keyboardHide.'); - }); - ``` +```js +inputMethodEngine.getInputMethodAbility().on('keyboardShow', () => { + console.log('InputMethodAbility keyboardShow.'); +}); +inputMethodEngine.getInputMethodAbility().on('keyboardHide', () => { + console.log('InputMethodAbility keyboardHide.'); +}); +``` -### off('keyboardShow'|'keyboardHide') +### off('keyboardShow'|'keyboardHide')9+ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void -取消订阅输入法事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅输入法事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -279,101 +429,144 @@ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void **示例:** - ```js - InputMethodEngine.off('keyboardShow', () => { - console.log('inputMethodEngine delete keyboardShow notification.'); - }); - InputMethodEngine.off('keyboardHide', () => { - console.log('inputMethodEngine delete keyboardHide notification.'); - }); - ``` +```js +inputMethodEngine.getInputMethodAbility().off('keyboardShow', () => { + console.log('InputMethodAbility delete keyboardShow notification.'); +}); +inputMethodEngine.getInputMethodAbility().off('keyboardHide', () => { + console.log('InputMethodAbility delete keyboardHide notification.'); +}); +``` + +### on('setSubtype')9+ + +on(type: 'setSubtype', callback: (inputMethodSubtype: InputMethodSubtype) => void): void + +订阅设置输入法子类型事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为'setSubtype',表示订阅输入法子类型设置。
- type为'keyboardHide',表示订阅输入法隐藏。 | +| callback | InputMethodSubtype | 是 | 回调函数,返回调用方的输入法子类型。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().on('setSubtype', (inputMethodSubtype) => { + console.log('InputMethodAbility setSubtype.'); +}); +``` + +### off('setSubtype')9+ + +off(ype: 'setSubtype', callback?: (inputMethodSubtype: InputMethodSubtype) => void): void + +取消订阅输入法子类型事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为'setSubtype',表示取消订阅输入法子类型设置。
- type为'keyboardHide',表示订阅输入法隐藏。 | +| callback | InputMethodSubtype | 是 | 回调函数,返回调用方的输入法子类型。 | + +**示例:** +```js +inputMethodEngine.getInputMethodAbility().off('setSubtype', () => { + console.log('InputMethodAbility delete setSubtype notification.'); +}); +``` -## KeyboardDelegate +## KeyboardDelegate -下列API示例中都需使用[createKeyboardDelegate](#createKeyboardDelegate)回调获取到KeyboardDelegate实例,再通过此实例调用对应方法。 +下列API示例中都需使用[getKeyboardDelegate](#inputmethodenginegetkeyboarddelegate9)回调获取到KeyboardDelegate实例,再通过此实例调用对应方法。 ### on('keyDown'|'keyUp') on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void -订阅硬键盘事件,使用callback回调返回按键信息。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅硬键盘事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 设置监听类型。
- type为'keyDown',表示订阅硬键盘按下。
- type为'keyUp',表示订阅硬键盘抬起。 | -| callback | [KeyEvent](#KeyEvent) | 是 | 回调返回按键信息。 | - - +| callback | [KeyEvent](#keyevent) | 是 | 回调函数,返回按键信息。 | **示例:** - ```js - KeyboardDelegate.on('keyUp', (keyEvent) => { - console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode)); - console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction)); - return true; - }); - KeyboardDelegate.on('keyDown', (keyEvent) => { - console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode)); - console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction)); - return true; - }); - ``` +```js +inputMethodEngine.getKeyboardDelegate().on('keyUp', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction)); + return true; +}); +inputMethodEngine.getKeyboardDelegate().on('keyDown', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction)); + return true; +}); +``` ### off('keyDown'|'keyUp') off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void -取消订阅硬键盘事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅硬键盘事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 设置监听类型。
- type为'keyDown',表示订阅硬键盘按下。
- type为'keyUp',表示订阅硬键盘抬起。 | -| callback | [KeyEvent](#KeyEvent) | 否 | 回调返回按键信息。 | +| callback | [KeyEvent](#keyevent) | 否 | 回调函数,返回按键信息。 | **示例:** - ```js - KeyboardDelegate.off('keyUp', (keyEvent) => { - console.log('delete keyUp notification.'); - return true; - }); - KeyboardDelegate.off('keyDown', (keyEvent) => { - console.log('delete keyDown notification.'); - return true; - }); - ``` +```js +inputMethodEngine.getKeyboardDelegate().off('keyUp', (keyEvent) => { + console.log('delete keyUp notification.'); + return true; +}); +inputMethodEngine.getKeyboardDelegate().off('keyDown', (keyEvent) => { + console.log('delete keyDown notification.'); + return true; +}); +``` ### on('cursorContextChange') on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void -订阅光标变化事件,使用callback回调返回光标信息。使用callback回调返回光标信息。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅光标变化事件。使用callback异步回调。 - **系统能力**: SystemCapability.MiscServices.InputMethodFramework + **系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 光标变化事件。
-type为’cursorContextChange‘时,表示光标变化。 | -| callback | number | 是 | 回调返回光标信息。 | +| callback | number | 是 | 回调函数,返回光标信息。 | **示例:** ```js -KeyboardDelegate.on('cursorContextChange', (x, y, height) => { +inputMethodEngine.getKeyboardDelegate().on('cursorContextChange', (x, y, height) => { console.log('inputMethodEngine cursorContextChange x:' + x); console.log('inputMethodEngine cursorContextChange y:' + y); console.log('inputMethodEngine cursorContextChange height:' + height); @@ -384,22 +577,22 @@ KeyboardDelegate.on('cursorContextChange', (x, y, height) => { off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) => void): void -取消订阅光标变化事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅光标变化事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 光标变化事件。
-type为’cursorContextChange‘时,表示光标变化。 | -| callback | number | 否 | 回调返回光标信息。 | +| callback | number | 否 | 回调函数,返回光标信息。 | **示例:** ```js -KeyboardDelegate.off('cursorContextChange', (x, y, height) => { +inputMethodEngine.getKeyboardDelegate().off('cursorContextChange', (x, y, height) => { console.log('delete cursorContextChange notification.'); }); ``` @@ -407,21 +600,21 @@ KeyboardDelegate.off('cursorContextChange', (x, y, height) => { on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -订阅文本选择变化事件,使用callback回调返回文本选择信息。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅文本选择变化事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 文本选择变化事件。
-type为’selectionChange‘时,表示选择文本变化。 | -| callback | number | 是 | 回调返回文本选择信息。 | +| callback | number | 是 | 回调函数,返回文本选择信息。 | **示例:** ```js -KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { +inputMethodEngine.getKeyboardDelegate().on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { console.log('inputMethodEngine beforeEach selectionChange oldBegin:' + oldBegin); console.log('inputMethodEngine beforeEach selectionChange oldEnd:' + oldEnd); console.log('inputMethodEngine beforeEach selectionChange newBegin:' + newBegin); @@ -433,21 +626,21 @@ KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -取消订阅文本选择变化事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅文本选择变化事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 文本选择变化事件。
-type为’selectionChange‘时,表示选择文本变化。 | -| callback | number | 否 | 回调返回文本选择信息。 | +| callback | number | 否 | 回调函数,返回文本选择信息。 | **示例:** ```js -KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { +inputMethodEngine.getKeyboardDelegate().off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { console.log('delete selectionChange notification.'); }); ``` @@ -457,21 +650,21 @@ KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => on(type: 'textChange', callback: (text: string) => void): void -订阅文本变化事件,使用callback回调返回当前文本内容。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅文本变化事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 文本变化事件。
-type为’textChange‘时,表示当前文本变化。 | -| callback | string | 是 | 回调返回当前文本内容。 | +| callback | string | 是 | 回调函数,返回当前文本内容。 | **示例:** ```js -KeyboardDelegate.on('textChange', (text) => { +inputMethodEngine.getKeyboardDelegate().on('textChange', (text) => { console.log('inputMethodEngine textChange. text:' + text); }); ``` @@ -480,63 +673,70 @@ KeyboardDelegate.on('textChange', (text) => { off(type: 'textChange', callback?: (text: string) => void): void -取消订阅文本变化事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅文本变化事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 文本变化事件。
-type为’textChange‘时,表示当前文本变化。 | -| callback | string | 否 | 回调返回当前文本内容。 | +| callback | string | 否 | 回调函数,返回当前文本内容。 | **示例:** ```js -keyboardDelegate.off('textChange', (text) => { +inputMethodEngine.getKeyboardDelegate().off('textChange', (text) => { console.log('delete textChange notification. text:' + text); }); ``` -## KeyboardController +## KeyboardController -下列API示例中都需使用[inputStart](#inputStart)回调获取到KeyboardController实例,再通过此实例调用对应方法。 +下列API示例中都需使用[on('inputStart')](#oninputstart9)回调获取到KeyboardController实例,再通过此实例调用对应方法。 -### hideKeyboard +### hide9+ -hideKeyboard(callback: AsyncCallback<void>): void +hide(callback: AsyncCallback<void>): void -隐藏输入法。使用callback形式返回结果。参数个数为1,否则抛出异常。 +隐藏输入法。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | -------- | -| callback | AsyncCallback<void> | 否 | 回调函数 | +| callback | AsyncCallback<void> | 否 | 回调函数。当输入法隐藏成功,err为undefined,否则为错误对象。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** ```js -KeyboardController.hideKeyboard((err) => { +KeyboardController.hide((err) => { if (err === undefined) { - console.error('hideKeyboard callback result---err: ' + err.msg); + console.error('hide err: ' + JSON.stringify(err)); return; } - console.log('hideKeyboard callback.'); + console.log('hide success.'); }); ``` -### hideKeyboard +### hide9+ -hideKeyboard(): Promise<void> +hide(): Promise<void> -隐藏输入法。使用peomise形式返回结果。参数个数为0,否则抛出异常。 +隐藏输入法。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -544,251 +744,308 @@ hideKeyboard(): Promise<void> | ---------------- | ------------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + **示例:** ```js -async function InputMethodEngine() { - await KeyboardController.hideKeyboard().then(() => { - console.info('hideKeyboard promise.'); - }).catch((err) => { - console.info('hideKeyboard promise err: ' + err.msg); - }); -} +KeyboardController.hide().then(() => { + console.info('hide success.'); +}).catch((err) => { + console.info('hide err: ' + JSON.stringify(err)); +}); ``` -## TextInputClient +### hideKeyboard(deprecated) -下列API示例中都需使用[inputStart](#inputStart)回调获取到TextInputClient实例,再通过此实例调用对应方法。 - -### getForward +hideKeyboard(callback: AsyncCallback<void>): void -getForward(length:number, callback: AsyncCallback<string>): void +隐藏输入法。使用callback异步回调。 -获取光标前固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[hide](#hide9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| length | number | 是 | 文本长度。 | -| callback | AsyncCallback<string> | 是 | 返回文本。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback<void> | 否 | 回调函数。当输入法隐藏成功,err为undefined,否则为错误对象。 | **示例:** - ```js - var length = 1; - TextInputClient.getForward(length, (err, text) => { - if (err === undefined) { - console.error('getForward callback result---err: ' + err.msg); - return; - } - console.log('getForward callback result---text: ' + text); - }); - ``` - -### getForward +```js +KeyboardController.hideKeyboard((err) => { + if (err === undefined) { + console.error('hideKeyboard err: ' + JSON.stringify(err)); + return; + } + console.log('hideKeyboard success.'); +}); +``` -getForward(length:number): Promise<string> +### hideKeyboard(deprecated) -获取光标前固定长度的文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +hideKeyboard(): Promise<void> -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +隐藏输入法。使用promise异步回调。 -**参数:** +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[hide](#hide9-1)替代。 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| length | number | 是 | 文本长度。 | +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** -| 类型 | 说明 | -| ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | 返回文本。 | +| 类型 | 说明 | +| ---------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** - ```js - async function InputMethodEngine() { - var length = 1; - await TextInputClient.getForward(length).then((text) => { - console.info('getForward promise result---res: ' + text); - }).catch((err) => { - console.error('getForward promise err: ' + err.msg); - }); - } - ``` +```js +KeyboardController.hideKeyboard().then(() => { + console.info('hideKeyboard success.'); +}).catch((err) => { + console.info('hideKeyboard err: ' + JSON.stringify(err)); +}); +``` + +## InputClient9+ -### getBackward +下列API示例中都需使用[on('inputStart')](#oninputstart9)回调获取到InputClient实例,再通过此实例调用对应方法。 -getBackward(length:number, callback: AsyncCallback<string>): void +### sendKeyFunction9+ -获取光标后固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +发送功能键。使用callback异步回调。 -**参数:** +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + + **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| length | number | 是 | 文本长度。 | -| callback | AsyncCallback<string> | 是 | 返回文本。 | +| action | number | 是 | 编辑框属性。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当功能键发送成功,err为undefined,data为true;否则为错误对象。 | -**示例:** +**错误码:** - ```js - var length = 1; - TextInputClient.getBackward(length, (err, text) => { - if (err === undefined) { - console.error('getBackward callback result---err: ' + err.msg); - return; - } - console.log('getBackward callback result---text: ' + text); - }); - ``` +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 -### getBackward +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | -getBackward(length:number): Promise<string> + **示例:** + +```js +try { + InputClient.sendKeyFunction(keyFunction, (err, result) => { + if (err) { + console.error('sendKeyFunction err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to sendKeyFunction. '); + } else { + console.error('Failed to sendKeyFunction. '); + } + }); +} catch (err) { + console.error('sendKeyFunction err: ' + JSON.stringify(err)); +} +``` + +### sendKeyFunction9+ + +sendKeyFunction(action:number): Promise<boolean> -获取光标后固定长度的文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +发送功能键。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| length | number | 是 | 文本长度。 | +| action | number | 是 | 编辑框属性。 | **返回值:** | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | 返回文本。 | +| Promise<boolean> | Promise对象。返回true表示功能键发送成功;返回false表示功能键发送失败。| + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **示例:** - ```js - async function InputMethodEngine() { - var length = 1; - await TextInputClient.getBackward(length).then((text) => { - console.info('getBackward promise result---res: ' + text); - }).catch((err) => { - console.error('getBackward promise err: ' + err.msg); - }); - } - ``` +```js +try { + InputClient.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)); + }); +} catch (err) { + console.error('sendKeyFunction err: ' + JSON.stringify(err)); +} +``` -### deleteForward +### getForward9+ -deleteForward(length:number, callback: AsyncCallback<boolean>): void +getForward(length:number, callback: AsyncCallback<string>): void -删除光标前固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +获取光标前固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | length | number | 是 | 文本长度。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当光标前固定长度的文本获取成功,err为undefined,data为获取到的文本;否则为错误对象。 | -**示例:** +**错误码:** - ```js - var length = 1; - TextInputClient.deleteForward(length, (err, result) => { - if (err === undefined) { - console.error('deleteForward callback result---err: ' + err.msg); - return; - } - if (result) { - console.info('Success to deleteForward.(callback) '); - } else { - console.error('Failed to deleteForward.(callback) '); - } - }); - ``` -### deleteForward +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 -deleteForward(length:number): Promise<boolean> +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** + +```js +let length = 1; +try { + InputClient.getForward(length, (err, text) => { + if (err) { + console.error('getForward err: ' + JSON.stringify(err)); + return; + } + console.log('getForward result: ' + text); + }); +} catch (err) { + console.error('getForward err: ' + JSON.stringify(err)); +} +``` + +### getForward9+ + +getForward(length:number): Promise<string> -删除光标前固定长度的文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +获取光标前固定长度的文本。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------- | -| length | number | 是 | 文本长度。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | -**返回值:** +**返回值:** -| 类型 | 说明 | -| ---------------------- | -------------- | -| Promise<boolean> | 操作成功与否。 | +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise对象,返回光标前固定长度的文本。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | **示例:** ```js -async function InputMethodEngine() { - var length = 1; - await TextInputClient.deleteForward(length).then((result) => { - if (result) { - console.info('Success to deleteForward.(promise) '); - } else { - console.error('Failed to deleteForward.(promise) '); - } +let length = 1; +try { + InputClient.getForward(length).then((text) => { + console.info('getForward resul: ' + text); }).catch((err) => { - console.error('deleteForward promise err: ' + err.msg); + console.error('getForward err: ' + JSON.stringify(err)); }); +} catch (err) { + console.error('getForward err: ' + JSON.stringify(err)); } ``` -### deleteBackward +### getBackward9+ -deleteBackward(length:number, callback: AsyncCallback<boolean>): void +getBackward(length:number, callback: AsyncCallback<string>): void -删除光标后固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +获取光标后固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework - **参数:** +**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | -------------- | -| length | number | 是 | 文本长度。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当光标后固定长度的文本获取成功,err为undefined,data为获取到的文本;否则为错误对象。| - **示例:** +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** ```js -var length = 1; -TextInputClient.deleteBackward(length, (err, result) => { - if (err === undefined) { - console.error('deleteBackward callback result---err: ' + err.msg); - return; - } - if (result) { - console.info('Success to deleteBackward.(callback) '); - } else { - console.error('Failed to deleteBackward.(callback) '); - } -}); +let length = 1; +try { + InputClient.getBackward(length, (err, text) => { + if (err) { + console.error('getBackward result: ' + JSON.stringify(err)); + return; + } + console.log('getBackward result---text: ' + text); + }); +} catch (err) { + console.error('getBackward result: ' + JSON.stringify(err)); +} ``` -### deleteBackward +### getBackward9+ -deleteBackward(length:number): Promise<boolean> +getBackward(length:number): Promise<string> -删除光标后固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +获取光标后固定长度的文本。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -796,133 +1053,265 @@ deleteBackward(length:number): Promise<boolean> | -------- | -------- | -------- | -------- | | length | number | 是 | 文本长度。 | -**返回值:** +**返回值:** | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | 操作成功与否。 | +| Promise<string> | Promise对象,返回光标后固定长度的文本。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** + +```js +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)); +} +``` + +### deleteForward9+ + +deleteForward(length:number, callback: AsyncCallback<boolean>): void + +删除光标前固定长度的文本。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当光标前固定长度的文本删除成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +let length = 1; +try { + InputClient.deleteForward(length, (err, result) => { + if (err) { + console.error('deleteForward result: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to deleteForward. '); + } else { + console.error('Failed to deleteForward. '); + } + }); +} catch (err) { + console.error('deleteForward result: ' + JSON.stringify(err)); +} +``` + +### deleteForward9+ + +deleteForward(length:number): Promise<boolean> + +删除光标前固定长度的文本。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | -------------- | +| Promise<boolean> | Promise对象。返回true表示删除光标前固定长度的文本成功;返回false表示删除光标前固定长度的文本失败。| + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **示例:** ```js -async function InputMethodEngine() { - var length = 1; - await TextInputClient.deleteBackward(length).then((result) => { +let length = 1; +try { + InputClient.deleteForward(length).then((result) => { if (result) { - console.info('Success to deleteBackward.(promise) '); + console.info('Success to deleteForward. '); } else { - console.error('Failed to deleteBackward.(promise) '); + console.error('Failed to deleteForward. '); } }).catch((err) => { - console.error('deleteBackward promise err: ' + err.msg); + console.error('deleteForward err: ' + JSON.stringify(err)); }); +} catch (err) { + console.error('deleteForward err: ' + JSON.stringify(err)); } ``` -### sendKeyFunction -sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void +### deleteBackward9+ -发送功能键。使用callback形式返回结果。参数个数为2,否则抛出异常。 +deleteBackward(length:number, callback: AsyncCallback<boolean>): void -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +删除光标后固定长度的文本。使用callback异步回调。 - **参数:** +**系统能力:** SystemCapability.MiscServices.InputMethodFramework -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| action | number | 是 | 编辑框属性。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +**参数:** - **示例:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | -------------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当光标后固定长度的文本删除成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | + +**示例:** ```js -TextInputClient.sendKeyFunction(keyFunction, (err, result) => { - if (err === undefined) { - console.error('sendKeyFunction callback result---err: ' + err.msg); - return; - } - if (result) { - console.info('Success to sendKeyFunction.(callback) '); - } else { - console.error('Failed to sendKeyFunction.(callback) '); - } -}); +let length = 1; +try { + InputClient.deleteBackward(length, (err, result) => { + if (err) { + console.error('deleteBackward err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to deleteBackward. '); + } else { + console.error('Failed to deleteBackward. '); + } + }); +} catch (err) { + console.error('deleteBackward err: ' + JSON.stringify(err)); +} ``` -### sendKeyFunction +### deleteBackward9+ -sendKeyFunction(action:number): Promise<boolean> +deleteBackward(length:number): Promise<boolean> -发送功能键。使用promise形式返回结果。参数个数为1,否则抛出异常。 +删除光标后固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| action | number | 是 | 编辑框属性。 | +| length | number | 是 | 文本长度。 | -**返回值:** +**返回值:** | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | 操作成功与否。 | +| Promise<boolean> | Promise对象。返回true表示删除光标后固定长度的文本成功;返回false表示删除光标后固定长度的文本失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **示例:** - ```js - async function InputMethodEngine() { - await client.sendKeyFunction(keyFunction).then((result) => { - if (result) { - console.info('Success to sendKeyFunction.(promise) '); - } else { - console.error('Failed to sendKeyFunction.(promise) '); - } - }).catch((err) => { - console.error('sendKeyFunction promise err:' + err.msg); - }); - } - ``` - -### insertText +```js +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+ insertText(text:string, callback: AsyncCallback<boolean>): void -插入文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +插入文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | text | string | 是 | 文本。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当文本插入成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **示例:** ```js -TextInputClient.insertText('test', (err, result) => { - if (err === undefined) { - console.error('insertText callback result---err: ' + err.msg); +InputClient.insertText('test', (err, result) => { + if (err) { + console.error('insertText err: ' + JSON.stringify(err)); return; } if (result) { - console.info('Success to insertText.(callback) '); + console.info('Success to insertText. '); } else { - console.error('Failed to insertText.(callback) '); + console.error('Failed to insertText. '); } }); ``` -### insertText +### insertText9+ insertText(text:string): Promise<boolean> -插入文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +插入文本。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -934,111 +1323,149 @@ insertText(text:string): Promise<boolean> | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | 操作成功与否。 | +| Promise<boolean> | Promise对象。返回true表示插入文本成功;返回false表示插入文本失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **示例:** - ```js - async function InputMethodEngine() { - await TextInputClient.insertText('test').then((result) => { - if (result) { - console.info('Success to insertText.(promise) '); - } else { - console.error('Failed to insertText.(promise) '); - } - }).catch((err) => { - console.error('insertText promise err: ' + err.msg); - }); - } - ``` - -### getEditorAttribute +```js +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)); +} +``` + +### getEditorAttribute9+ getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void -获取编辑框属性值。使用callback形式返回结果。参数个数为1,否则抛出异常。 +获取编辑框属性值。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| callback | AsyncCallback<[EditorAttribute](#EditorAttribute)> | 是 | 编辑框属性值。 | +| callback | AsyncCallback<[EditorAttribute](#editorattribute)> | 是 | 回调函数。当编辑框属性值获取成功,err为undefined,data为编辑框属性值;否则为错误对象。| + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **示例:** - ```js - TextInputClient.getEditorAttribute((err, editorAttribute) => { - if (err === undefined) { - console.error('getEditorAttribute callback result---err: ' + err.msg); - return; - } - console.log('editorAttribute.inputPattern(callback): ' + JSON.stringify(editorAttribute.inputPattern)); - console.log('editorAttribute.enterKeyType(callback): ' + JSON.stringify(editorAttribute.enterKeyType)); - }); - ``` +```js +InputClient.getEditorAttribute((err, editorAttribute) => { + if (err) { + console.error('getEditorAttribute err: ' + JSON.stringify(err)); + return; + } + console.log('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}); +``` -### getEditorAttribute +### getEditorAttribute9+ getEditorAttribute(): Promise<EditorAttribute> -获取编辑框属性值。使用promise形式返回结果。参数个数为0,否则抛出异常。 +获取编辑框属性值。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<[EditorAttribute](#EditorAttribute)> | 返回编辑框属性值。 | +| Promise<[EditorAttribute](#editorattribute)> | Promise对象,返回编辑框属性值。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **示例:** - ```js - async function InputMethodEngine() { - await TextInputClient.getEditorAttribute().then((editorAttribute) => { - console.info('editorAttribute.inputPattern(promise): ' + JSON.stringify(editorAttribute.inputPattern)); - console.info('editorAttribute.enterKeyType(promise): ' + JSON.stringify(editorAttribute.enterKeyType)); - }).catch((err) => { - console.error('getEditorAttribute promise err: ' + err.msg); - }); - } - ``` +```js +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+ moveCursor(direction: number, callback: AsyncCallback<void>): void -移动光标。使用callback形式返回结果。参数个数为1,否则抛出异常。 +移动光标。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------- | ---- | -------------- | | direction | number | 是 | 光标移动方向。 | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当光标移动成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **示例:** ```js -TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { - if (err === undefined) { - console.error('moveCursor callback result---err: ' + err.msg); - return; - } -}); +try { + InputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { + if (err) { + console.error('moveCursor err: ' + JSON.stringify(err)); + return; + } + console.info('moveCursor success'); + }); +} catch (err) { + console.error('moveCursor err: ' + JSON.stringify(err)); +} ``` ### moveCursor9+ moveCursor(direction: number): Promise<void> -移动光标。使用promise形式返回结果。参数个数为1,否则抛出异常。 +移动光标。使用promise异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -1052,37 +1479,543 @@ moveCursor(direction: number): Promise<void> | ------------------- | ------------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + **示例:** - ```js -async function InputMethodEngine() { - await TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then(async (err) => { +```js +try { + InputClient.moveCursor(inputMethodEngine.CURSOR_UP).then(() => { console.log('moveCursor success'); }).catch((err) => { - console.error('moveCursor success err: ' + err.msg); + console.error('moveCursor success err: ' + JSON.stringify(err)); }); +} catch (err) { + console.log('moveCursor err: ' + JSON.stringify(err)); } - ``` +``` -## EditorAttribute +## EditorAttribute 编辑框属性值。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ------------ | -------- | ---- | ---- | ------------------ | | enterKeyType | number | 是 | 否 | 编辑框的功能属性。 | | inputPattern | number | 是 | 否 | 编辑框的文本属性。 | -## KeyEvent +## KeyEvent 按键属性值。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework | 名称 | 参数类型 | 可读 | 可写 | 说明 | | --------- | -------- | ---- | ---- | ------------ | | keyCode | number | 是 | 否 | 按键的键值。 | | keyAction | number | 是 | 否 | 按键的状态。 | +## TextInputClient(deprecated) + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[InputClient](#inputclient9)替代。 + +下列API示例中都需使用[on('inputStart')](#oninputstart)回调获取到TextInputClient实例,再通过此实例调用对应方法。 + +### getForward(deprecated) + +getForward(length:number, callback: AsyncCallback<string>): void + +获取光标前固定长度的文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getForward](#getforward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当光标前固定长度的文本获取成功,err为undefined,data为获取到的文本;否则为错误对象。| + +**示例:** + +```js +let length = 1; +TextInputClient.getForward(length, (err, text) => { + if (err === undefined) { + console.error('getForward err: ' + JSON.stringify(err)); + return; + } + console.log('getForward result---text: ' + text); +}); +``` + +### getForward(deprecated) + +getForward(length:number): Promise<string> + +获取光标前固定长度的文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getForward](#getforward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise对象,返回光标前固定长度的文本。 | + +**示例:** + +```js +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) + +getBackward(length:number, callback: AsyncCallback<string>): void + +获取光标后固定长度的文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getBackward](#getbackward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当光标后固定长度的文本获取成功,err为undefined,data为获取到的文本;否则为错误对象。 | + +**示例:** + +```js +let length = 1; +TextInputClient.getBackward(length, (err, text) => { + if (err === undefined) { + console.error('getBackward err: ' + JSON.stringify(err)); + return; + } + console.log('getBackward result---text: ' + text); +}); +``` + +### getBackward(deprecated) + +getBackward(length:number): Promise<string> + +获取光标后固定长度的文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getBackward](#getbackward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise对象,返回光标后固定长度的文本。 | + +**示例:** + +```js +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) + +deleteForward(length:number, callback: AsyncCallback<boolean>): void + +删除光标前固定长度的文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteForward](#deleteforward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当光标前固定长度的文本删除成功,err为undefined,data为true;否则为错误对象。 | + +**示例:** + +```js +let length = 1; +TextInputClient.deleteForward(length, (err, result) => { + if (err === undefined) { + console.error('deleteForward err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to deleteForward. '); + } else { + console.error('Failed to deleteForward. '); + } +}); +``` + +### deleteForward(deprecated) + +deleteForward(length:number): Promise<boolean> + +删除光标前固定长度的文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteForward](#deleteforward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | -------------- | +| Promise<boolean> | Promise对象。返回true表示删除光标前固定长度的文本成功;返回false表示删除光标前固定长度的文本失败。| + +**示例:** + +```js +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) + +deleteBackward(length:number, callback: AsyncCallback<boolean>): void + +删除光标后固定长度的文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteBackward](#deletebackward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + + **参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | -------------- | +| length | number | 是 | 文本长度。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当光标后固定长度的文本删除成功,err为undefined,data为true;否则为错误对象。| + + **示例:** + +```js +let length = 1; +TextInputClient.deleteBackward(length, (err, result) => { + if (err === undefined) { + console.error('deleteBackward err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to deleteBackward. '); + } else { + console.error('Failed to deleteBackward. '); + } +}); +``` + +### deleteBackward(deprecated) + +deleteBackward(length:number): Promise<boolean> + +删除光标后固定长度的文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteBackward](#deletebackward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示删除光标后固定长度的文本成功;返回false表示删除光标后固定长度的文本失败。| + +**示例:** + +```js +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) + +sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void + +发送功能键。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[sendKeyFunction](#sendkeyfunction9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + + **参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| action | number | 是 | 编辑框属性。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当功能键发送成功,err为undefined,data为true;否则为错误对象。 | + + **示例:** + +```js +TextInputClient.sendKeyFunction(keyFunction, (err, result) => { + if (err === undefined) { + console.error('sendKeyFunction err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to sendKeyFunction. '); + } else { + console.error('Failed to sendKeyFunction. '); + } +}); +``` + +### sendKeyFunction(deprecated) + +sendKeyFunction(action:number): Promise<boolean> + +发送功能键。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[sendKeyFunction](#sendkeyfunction9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| action | number | 是 | 编辑框属性。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示发送功能键成功;返回false表示发送功能键失败。 | + +**示例:** + +```js +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) + +insertText(text:string, callback: AsyncCallback<boolean>): void + +插入文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[insertText](#inserttext9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| text | string | 是 | 文本。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当文本插入成功,err为undefined,data为true;否则为错误对象。 | + +**示例:** + +```js +TextInputClient.insertText('test', (err, result) => { + if (err === undefined) { + console.error('insertText err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to insertText. '); + } else { + console.error('Failed to insertText. '); + } +}); +``` + +### insertText(deprecated) + +insertText(text:string): Promise<boolean> + +插入文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[insertText](#inserttext9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| text | string | 是 | 文本。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示插入文本成功;返回false表示插入文本失败。 | + +**示例:** + +```js +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) + +getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void + +获取编辑框属性值。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getEditorAttribute](#geteditorattribute9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| callback | AsyncCallback<[EditorAttribute](#editorattribute)> | 是 | 回调函数。当编辑框的属性值获取成功,err为undefined,data为编辑框属性值;否则为错误对象。| + +**示例:** + +```js +TextInputClient.getEditorAttribute((err, editorAttribute) => { + if (err === undefined) { + console.error('getEditorAttribute err: ' + JSON.stringify(err)); + return; + } + console.log('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}); +``` + +### getEditorAttribute(deprecated) + +getEditorAttribute(): Promise<EditorAttribute> + +获取编辑框属性值。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getEditorAttribute](#geteditorattribute9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<[EditorAttribute](#editorattribute)> | Promise对象,返回编辑框属性值。 | + +**示例:** + +```js +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 56743cb2b46490eb8ca89050e3e891e7b5cf064e..242b63a32ab5337185af44603502d634ae068b2b 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,11 +1,11 @@ # 输入监听 -InputMonitor模块提供了监听全局触摸事件的功能。 - +输入监听模块,提供了监听输入设备事件(当前支持触摸屏和鼠标)的能力。 > **说明:** -> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> - 本模块接口均为系统接口。 +> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> - 本模块接口均为系统接口。 ## 导入模块 @@ -29,19 +29,19 @@ on(type: "touch", receiver: TouchEventReceiver): void **参数:** | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“touch”。 | -| receiver | [TouchEventReceiver](#toucheventreceiver) | 是 | 触摸输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“touch”。 | +| receiver | [TouchEventReceiver](#toucheventreceiver) | 是 | 回调函数,异步上报触摸屏输入事件。 | **示例:** ```js try { - inputMonitor.on("touch", (data)=> { - console.info(`monitorOnTouchEvent success ${JSON.stringify(data)}`); - return false; - }); + inputMonitor.on("touch", (touchEvent) => { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; + }); } catch (error) { - console.info("onMonitor " + error.code + " " + error.message) + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -58,19 +58,19 @@ on(type: "mouse", receiver: Callback<MouseEvent>): void | 参数 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“mouse”。 | -| receiver | Callback<MouseEvent> | 是 | 鼠标输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“mouse”。 | +| receiver | Callback<MouseEvent> | 是 | 回调函数,异步上报鼠标输入事件。 | **示例:** ```js try { - inputMonitor.on("mouse", (data)=> { - console.info(`monitorOnMouseEvent success ${JSON.stringify(data)}`); - return false; - }); + inputMonitor.on("mouse", (mouseEvent) => { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; + }); } catch (error) { - console.info("onMonitor " + error.code + " " + error.message) + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -89,31 +89,38 @@ off(type: "touch", receiver?: TouchEventReceiver): void **参数:** | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“touch”。 | -| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 触摸输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“touch”。 | +| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | **示例:** ```js -// 取消所有监听。 +// 取消监听单个回调函数 +function callback(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; +}; try { - inputMonitor.off("touch"); + inputMonitor.on("touch", callback); + inputMonitor.off("touch", callback); + console.log(`Monitor off success`); } catch (error) { - console.info("offMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } -// 单独取消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) -}, +``` + +```js +// 取消监听所有回调函数 +function callback(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; +}; try { - inputMonitor.off("touch",this.callback); + inputMonitor.on("touch", callback); + inputMonitor.off("touch"); + console.log(`Monitor off success`); } catch (error) { - console.info("offTouchMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -129,39 +136,44 @@ off(type: "mouse", receiver?: Callback<MouseEvent>): void | 参数 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“mouse”。 | -| receiver | Callback<MouseEvent> | 否 | 鼠标输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“mouse”。 | +| receiver | Callback<MouseEvent> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | **示例:** ```js -// 取消所有监听。 +// 取消监听单个回调函数 +function callback(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; +}; try { - inputMonitor.off("mouse"); + inputMonitor.on("mouse", callback); + inputMonitor.off("mouse", callback); + console.log(`Monitor off success`); } catch (error) { - console.info("offMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } -// 单独取消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) -}, +``` + +```js +// 取消监听所有回调函数 +function callback(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; +}; try { - inputMonitor.off("mouse", this.callback); + inputMonitor.on("mouse", callback); + inputMonitor.off("mouse"); + console.log(`Monitor off success`); } catch (error) { - console.info("offMouseMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` - - ## TouchEventReceiver -触摸输入事件的回调函数。如果返回true,则触摸输入被监听器消耗,系统将执行关闭动作。 +触摸输入事件的回调函数。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -170,23 +182,25 @@ try { **参数:** | 参数 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | -| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | 是 | 触摸输入事件回调函数,返回true表示输触事件被监听器消费,false表示输触事件未被监听器消费。 | +| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | 是 | 触摸输入事件。 | **返回值:** | 类型 | 说明 | | ------- | ---------------------------------------- | -| Boolean | 返回true表示触摸输入事件被监听器消费,false表示触摸输入事件未被监听器消费。 | +| Boolean | 若返回true,本次触摸后续产生的事件不再分发到窗口;若返回false,本次触摸后续产生的事件还会分发到窗口。 | **示例:** ```js try { - inputMonitor.on("touch", (event) => { - // 若返回true,表示本次操作后续所有事件不再分发到窗口,事件都由监听者消费。 - return false; + inputMonitor.on("touch", touchEvent => { + if (touchEvent.touches.size() == 3) { // 当前有三个手指按下 + return true; + } else { + return false; + } }); - inputMonitor.off("touch"); } catch (error) { - console.info("offMonitor " + error.code + " " + error.message) + console.log(`Monitor on 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-keycode.md b/zh-cn/application-dev/reference/apis/js-apis-keycode.md index 26f56165a23e232b68ac20f7d867a053a2631032..150356c791aee490a2aa04facc354b2c10a51674 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-keycode.md +++ b/zh-cn/application-dev/reference/apis/js-apis-keycode.md @@ -1,6 +1,6 @@ # 键值 -KeyCode模块提供了按键类设备的键值。 +按键设备键值。 > **说明:** > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -8,7 +8,7 @@ KeyCode模块提供了按键类设备的键值。 ## 导入模块 ```js -import {KeyCode} from '@ohos.multimodalInput.keyCode' +import {KeyCode} from '@ohos.multimodalInput.keyCode'; ``` ## KeyCode @@ -19,7 +19,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' | -------------------------------- | ------ | ---- | ---- | --------------------------- | | KEYCODE_FN | number | 是 | 否 | 功能(Fn)键 | | KEYCODE_UNKNOWN | number | 是 | 否 | 未知按键 | -| KEYCODE_HOME | number | 是 | 否 | 按键Home | +| KEYCODE_HOME | number | 是 | 否 | 功能(Home)键 | | KEYCODE_BACK | number | 是 | 否 | 返回键 | | KEYCODE_MEDIA_PLAY_PAUSE | number | 是 | 否 | 多媒体键 播放/暂停 | | KEYCODE_MEDIA_STOP | number | 是 | 否 | 多媒体键 停止 | @@ -80,10 +80,10 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' | KEYCODE_Z | number | 是 | 否 | 按键'Z' | | KEYCODE_COMMA | number | 是 | 否 | 按键',' | | KEYCODE_PERIOD | number | 是 | 否 | 按键'.' | -| KEYCODE_ALT_LEFT | number | 是 | 否 | Alt+Left | -| KEYCODE_ALT_RIGHT | number | 是 | 否 | Alt+Right | -| KEYCODE_SHIFT_LEFT | number | 是 | 否 | Shift+Left | -| KEYCODE_SHIFT_RIGHT | number | 是 | 否 | Shift+Right | +| KEYCODE_ALT_LEFT | number | 是 | 否 | 左Alt键 | +| KEYCODE_ALT_RIGHT | number | 是 | 否 | 右Alt键 | +| KEYCODE_SHIFT_LEFT | number | 是 | 否 | 左Shift键 | +| KEYCODE_SHIFT_RIGHT | number | 是 | 否 | 右Shift键 | | KEYCODE_TAB | number | 是 | 否 | Tab键 | | KEYCODE_SPACE | number | 是 | 否 | 空格键 | | KEYCODE_SYM | number | 是 | 否 | 符号修改器按键 | @@ -107,19 +107,19 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' | KEYCODE_PAGE_DOWN | number | 是 | 否 | 向下翻页键 | | KEYCODE_ESCAPE | number | 是 | 否 | ESC键 | | KEYCODE_FORWARD_DEL | number | 是 | 否 | 删除键 | -| KEYCODE_CTRL_LEFT | number | 是 | 否 | Control+Left | -| KEYCODE_CTRL_RIGHT | number | 是 | 否 | Control+Right | +| KEYCODE_CTRL_LEFT | number | 是 | 否 | 左Ctrl键 | +| KEYCODE_CTRL_RIGHT | number | 是 | 否 | 右Ctrl键 | | KEYCODE_CAPS_LOCK | number | 是 | 否 | 大写锁定键 | | KEYCODE_SCROLL_LOCK | number | 是 | 否 | 滚动锁定键 | | KEYCODE_META_LEFT | number | 是 | 否 | 左元修改器键 | | KEYCODE_META_RIGHT | number | 是 | 否 | 右元修改器键 | -| KEYCODE_FUNCTION | number | 是 | 否 | 函数修改器键 | +| KEYCODE_FUNCTION | number | 是 | 否 | 功能键 | | KEYCODE_SYSRQ | number | 是 | 否 | 系统请求/打印屏幕键 | | KEYCODE_BREAK | number | 是 | 否 | Break/Pause键 | | KEYCODE_MOVE_HOME | number | 是 | 否 | 光标移动到开始键 | | KEYCODE_MOVE_END | number | 是 | 否 | 光标移动到末尾键 | | KEYCODE_INSERT | number | 是 | 否 | 插入键 | -| KEYCODE_FORWARD | number | 是 | 否 | 删除键 | +| KEYCODE_FORWARD | number | 是 | 否 | 前进键 | | KEYCODE_MEDIA_PLAY | number | 是 | 否 | 多媒体键 播放 | | KEYCODE_MEDIA_PAUSE | number | 是 | 否 | 多媒体键 暂停 | | KEYCODE_MEDIA_CLOSE | number | 是 | 否 | 多媒体键 关闭 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-keyevent.md b/zh-cn/application-dev/reference/apis/js-apis-keyevent.md index 2dcf562d995aa43115528998f8fb14e625ab884d..d1ac98a67ae88626552bb6c8c02252bb5e351ace 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-keyevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-keyevent.md @@ -1,6 +1,6 @@ # 按键输入事件 -KeyEvent模块提供了设备可以上报的按键事件。 +设备上报的按键事件。 > **说明:** > @@ -9,44 +9,44 @@ KeyEvent模块提供了设备可以上报的按键事件。 ## 导入模块 ```js -import {Action,Key,KeyEvent} from '@ohos.multimodalInput.keyEvent'; +import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; ``` ## Action **系统能力**:SystemCapability.MultimodalInput.Input.Core -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ------ | ------ | ---- | ---- | ---- | -| CANCEL | number | 是 | 否 | 取消 | -| DOWN | number | 是 | 否 | 按下按钮 | -| UP | number | 是 | 否 | 抬起按钮 | +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ------ | -------- | ---- | ---- | -------- | +| CANCEL | number | 是 | 否 | 按键取消 | +| DOWN | number | 是 | 否 | 按键按下 | +| UP | number | 是 | 否 | 按键抬起 | ## Key **系统能力**:SystemCapability.MultimodalInput.Input.Core -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ----------- | ------- | ---- | ---- | ------ | -| code | KeyCode | 是 | 否 | 按键码 | -| pressedTime | number | 是 | 否 | 按下时间 | -| deviceId | number | 是 | 否 | 按键所属设备 | +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ----------- | -------- | ---- | ---- | -------------- | +| code | KeyCode | 是 | 否 | 按键码 | +| pressedTime | number | 是 | 否 | 按键按下时间 | +| deviceId | number | 是 | 否 | 按键所属设备id | ## KeyEvent **系统能力**:SystemCapability.MultimodalInput.Input.Core -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ----------- | ------- | ---- | ---- | -------------------- | -| action | Action | 是 | 否 | 按键动作 | -| key | Key | 是 | 否 | 当前发生变化的按键 | -| unicodeChar | number | 是 | 否 | 按键对应的uniCode字符 | -| keys | Key[] | 是 | 否 | 当前处于按下状态的按键列表 | -| ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | -| altKey | boolean | 是 | 否 | 当前altKey是否处于按下状态 | -| shiftKey | boolean | 是 | 否 | 当前shiftKey是否处于按下状态 | -| logoKey | boolean | 是 | 否 | 当前logoKey是否处于按下状态 | -| fnKey | boolean | 是 | 否 | 当前fnKey是否处于按下状态 | -| capsLock | boolean | 是 | 否 | 当前capsLock是否处于激活状态 | -| numLock | boolean | 是 | 否 | 当前numLock是否处于激活状态 | -| scrollLock | boolean | 是 | 否 | 当前scrollLock是否处于激活状态 | \ No newline at end of file +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ----------- | -------- | ---- | ---- | ------------------------------ | +| action | Action | 是 | 否 | 按键动作 | +| key | Key | 是 | 否 | 当前上报的按键 | +| unicodeChar | number | 是 | 否 | 按键对应的uniCode字符 | +| keys | Key[] | 是 | 否 | 当前处于按下状态的按键列表 | +| ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | +| altKey | boolean | 是 | 否 | 当前altKey是否处于按下状态 | +| shiftKey | boolean | 是 | 否 | 当前shiftKey是否处于按下状态 | +| logoKey | boolean | 是 | 否 | 当前logoKey是否处于按下状态 | +| fnKey | boolean | 是 | 否 | 当前fnKey是否处于按下状态 | +| capsLock | boolean | 是 | 否 | 当前capsLock是否处于激活状态 | +| numLock | boolean | 是 | 否 | 当前numLock是否处于激活状态 | +| scrollLock | boolean | 是 | 否 | 当前scrollLock是否处于激活状态 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md index 7a05a0d9b342d62f1f50594a256009de753fcfb7..2514ed13d36f220d75e6f70f757d50fd436152b6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -91,7 +91,7 @@ isEmpty(): boolean const lightWeightMap = new LightWeightMap(); let result = lightWeightMap.isEmpty(); try { - lightWeightMap.isEmpty.bind({})(); + lightWeightMap.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -136,7 +136,7 @@ let map = new LightWeightMap(); map.set("sparrow", 356); let result = lightWeightMap.hasAll(map); try { - lightWeightMap.hasAll.bind({}, map)(); + lightWeightMap.hasAll.bind({}, map)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -180,7 +180,7 @@ lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasKey("squirrel"); try { - lightWeightMap.hasKey.bind({}, "squirrel")(); + lightWeightMap.hasKey.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -223,7 +223,7 @@ let result = lightWeightMap.hasValue(123); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasValue(123); try { - lightWeightMap.hasValue.bind({}, 123)(); + lightWeightMap.hasValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -258,7 +258,7 @@ increaseCapacityTo(minimumCapacity: number): void let lightWeightMap = new LightWeightMap(); lightWeightMap.increaseCapacityTo(10); try { - lightWeightMap.increaseCapacityTo.bind({}, 10)(); + lightWeightMap.increaseCapacityTo.bind({}, 10)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -301,7 +301,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.get("sparrow"); try { - lightWeightMap.get.bind({}, "sparrow")(); + lightWeightMap.get.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -344,7 +344,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfKey("sparrow"); try { - lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); + lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -387,7 +387,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfValue(123); try { - lightWeightMap.getIndexOfValue.bind({}, 123)(); + lightWeightMap.getIndexOfValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -431,12 +431,12 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getKeyAt(1); try { - lightWeightMap.getKeyAt.bind({}, 1)(); + lightWeightMap.getKeyAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - lightWeightMap.getKeyAt(6)(); + lightWeightMap.getKeyAt(6)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -474,7 +474,7 @@ lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); lightWeightMap.setAll(map); try { - lightWeightMap.setAll.bind({}, map)(); + lightWeightMap.setAll.bind({}, map)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -515,7 +515,7 @@ set(key: K, value: V): Object let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.set("squirrel", 123); try { - lightWeightMap.set.bind({}, "squirrel", 123)(); + lightWeightMap.set.bind({}, "squirrel", 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -558,7 +558,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.remove("sparrow"); try { - lightWeightMap.remove.bind({}, "sparrow")(); + lightWeightMap.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -601,7 +601,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.removeAt(1); try { - lightWeightMap.removeAt.bind({}, 1)(); + lightWeightMap.removeAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -646,7 +646,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.setValueAt(1, 3546); try { - lightWeightMap.setValueAt.bind({}, 1, 3546)(); + lightWeightMap.setValueAt.bind({}, 1, 3546)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -695,7 +695,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getValueAt(1); try { - lightWeightMap.getValueAt.bind({}, 1)(); + lightWeightMap.getValueAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -731,7 +731,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.clear(); try { - lightWeightMap.clear.bind({})(); + lightWeightMap.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -773,7 +773,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap.keys.bind({})(); + lightWeightMap.keys.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -815,7 +815,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap.values.bind({})(); + lightWeightMap.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -864,7 +864,7 @@ lightWeightMap.forEach((value, key) => { try { lightWeightMap.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -907,7 +907,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap.entries.bind({})(); + lightWeightMap.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -943,7 +943,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.toString(); try { - lightWeightMap.toString.bind({})(); + lightWeightMap.toString.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -993,7 +993,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap[Symbol.iterator].bind({})(); + lightWeightMap[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md index 6639774866e6a398689f3d54b540213f9e0c9e2a..64dcd50b28ddc85b09c099134cd3b5a5f6b35fca 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -91,7 +91,7 @@ isEmpty(): boolean const lightWeightSet = new LightWeightSet(); let result = lightWeightSet.isEmpty(); try { - lightWeightSet.isEmpty.bind({})(); + lightWeightSet.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -131,7 +131,7 @@ add(obj: T): boolean let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.add("squirrel"); try { - lightWeightSet.add.bind({}, "squirrel")(); + lightWeightSet.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -170,7 +170,7 @@ let set = new LightWeightSet(); set.add("gull"); let result = lightWeightSet.addAll(set); try { - lightWeightSet.addAll.bind({}, set)(); + lightWeightSet.addAll.bind({}, set)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -215,7 +215,7 @@ let set = new LightWeightSet(); set.add("sparrow"); let result = lightWeightSet.hasAll(set); try { - lightWeightSet.hasAll.bind({}, set)(); + lightWeightSet.hasAll.bind({}, set)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -258,7 +258,7 @@ let result = lightWeightSet.has(123); lightWeightSet.add(123); result = lightWeightSet.has(123); try { - lightWeightSet.has.bind({}, 123)(); + lightWeightSet.has.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -302,7 +302,7 @@ lightWeightSet.add("sparrow"); let obj = ["squirrel", "sparrow"]; let result = lightWeightSet.equal(obj); try { - lightWeightSet.equal.bind({}, obj)(); + lightWeightSet.equal.bind({}, obj)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -338,7 +338,7 @@ increaseCapacityTo(minimumCapacity: number): void let lightWeightSet = new LightWeightSet(); lightWeightSet.increaseCapacityTo(10); try { - lightWeightSet.increaseCapacityTo.bind({}, 10)(); + lightWeightSet.increaseCapacityTo.bind({}, 10)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -386,7 +386,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getIndexOf("sparrow"); try { - lightWeightSet.getIndexOf.bind({}, "sparrow")(); + lightWeightSet.getIndexOf.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -429,7 +429,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.remove("sparrow"); try { - lightWeightSet.remove.bind({}, "sparrow")(); + lightWeightSet.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -472,7 +472,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.removeAt(1); try { - lightWeightSet.removeAt.bind({}, 1)(); + lightWeightSet.removeAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -515,7 +515,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getValueAt(1); try { - lightWeightSet.getValueAt.bind({}, 1)(); + lightWeightSet.getValueAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -546,7 +546,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); lightWeightSet.clear(); try { - lightWeightSet.clear.bind({})(); + lightWeightSet.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -583,7 +583,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toString(); try { - lightWeightSet.toString.bind({})(); + lightWeightSet.toString.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -620,7 +620,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toArray(); try { - lightWeightSet.toArray.bind({})(); + lightWeightSet.toArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -662,7 +662,7 @@ while(index < lightWeightSet.length) { index++; } try { - lightWeightSet.values.bind({})(); + lightWeightSet.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -711,7 +711,7 @@ lightWeightSet.forEach((value, key) => { try { lightWeightSet.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -753,7 +753,7 @@ while(index < lightWeightSet.length) { index++; } try { - lightWeightSet.entries.bind({})(); + lightWeightSet.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -802,7 +802,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightSet[Symbol.iterator].bind({})(); + lightWeightSet[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md index 6f0a7a76eb45b08f700a6a582ad3ba1249186f8a..46efb533394a4cbe1f7fdede32914192ef93cd52 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -98,11 +98,12 @@ let linkedList = new LinkedList(); let result = linkedList.add("a"); let result1 = linkedList.add(1); let b = [1, 2, 3]; -linkedList.add(b); +let result2 = linkedList.add(b); let c = {name : "Dylon", age : "13"}; -let result3 = linkedList.add(false); +let result3 = linkedList.add(c); +let result4 = linkedList.add(false); try { - linkedList.add.bind({}, "b")(); + linkedList.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -139,9 +140,10 @@ linkedList.addFirst(1); let b = [1, 2, 3]; linkedList.addFirst(b); let c = {name : "Dylon", age : "13"}; +linkedList.addFirst(c); linkedList.addFirst(false); try { - linkedList.addFirst.bind({}, "b")(); + linkedList.addFirst.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -179,7 +181,7 @@ linkedList.insert(0, "A"); linkedList.insert(1, 0); linkedList.insert(2, true); try { - linkedList.insert.bind({}, 3, "b")(); + linkedList.insert.bind({}, 3, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -226,7 +228,7 @@ let result1 = linkedList.has("squirrel"); linkedList.add("squirrel"); let result = linkedList.has("squirrel"); try { - linkedList.has.bind({}, "squirrel")(); + linkedList.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -273,7 +275,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.get(2); try { - linkedList.get.bind({}, 2)(); + linkedList.get.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -320,7 +322,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.getLastIndexOf(2); try { - linkedList.getLastIndexOf.bind({}, 2)(); + linkedList.getLastIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -367,7 +369,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.getIndexOf(2); try { - linkedList.getIndexOf.bind({}, 2)(); + linkedList.getIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -413,7 +415,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.removeByIndex(2); try { - linkedList.removeByIndex.bind({}, 2)(); + linkedList.removeByIndex.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -463,7 +465,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.removeFirst(); try { - linkedList.removeFirst.bind({})(); + linkedList.removeFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -508,7 +510,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.removeLast(); try { - linkedList.removeLast.bind({})(); + linkedList.removeLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -552,7 +554,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.remove(2); try { - linkedList.remove.bind({}, 2)(); + linkedList.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -602,7 +604,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.removeFirstFound(4); try { - linkedList.removeFirstFound.bind({}, 2)(); + linkedList.removeFirstFound.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -652,7 +654,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.removeLastFound(4); try { - linkedList.removeLastFound.bind({}, 4)(); + linkedList.removeLastFound.bind({}, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -690,7 +692,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.clone(); try { - linkedList.clone.bind({})(); + linkedList.clone.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -742,7 +744,7 @@ linkedList.forEach((value, index) => { try { linkedList.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -774,7 +776,7 @@ linkedList.add(5); linkedList.add(4); linkedList.clear(); try { - linkedList.clear.bind({})(); + linkedList.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -820,7 +822,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.set(2, "b"); try { - linkedList.set.bind({}, 2, "b")(); + linkedList.set.bind({}, 2, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -862,7 +864,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.convertToArray(); try { - linkedList.convertToArray.bind({})(); + linkedList.convertToArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -900,7 +902,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.getFirst(); try { - linkedList.getFirst.bind({})(); + linkedList.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -938,7 +940,7 @@ linkedList.add(5); linkedList.add(4); linkedList.getLast(); try { - linkedList.getLast.bind({})(); + linkedList.getLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -988,7 +990,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - linkedList[Symbol.iterator].bind({})(); + linkedList[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md index 6af207351213967e43bc23ac340a2d7d837373a6..0d2eb8595d2791af97b275ad20daf413258c4193 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-list.md +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -90,14 +90,15 @@ add(element: T): boolean ```ts let list = new List(); -let result = list.add("a"); -let result1 = list.add(1); +let result1 = list.add("a"); +let result2 = list.add(1); let b = [1, 2, 3]; -list.add(b); +let result3 = list.add(b); let c = {name : "Dylon", age : "13"}; -let result3 = list.add(false); +let result4 = list.add(c); +let result5 = list.add(false); try { - list.add.bind({}, "b")(); + list.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -135,7 +136,7 @@ list.insert("A", 0); list.insert(0, 1); list.insert(true, 2); try { - list.insert.bind({}, "b", 3)(); + list.insert.bind({}, "b", 3)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -182,7 +183,7 @@ let result = list.has("squirrel"); list.add("squirrel"); let result1 = list.has("squirrel"); try { - list.has.bind({}, "squirrel")(); + list.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -229,7 +230,7 @@ list.add(2); list.add(4); let result = list.get(2); try { - list.get.bind({}, 2)(); + list.get.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -276,7 +277,7 @@ list.add(2); list.add(4); let result = list.getLastIndexOf(2); try { - list.getLastIndexOf.bind({}, 2)(); + list.getLastIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -324,7 +325,7 @@ list.add(4); list.getIndexOf(2); let result = list.getIndexOf(2); try { - list.getIndexOf.bind({}, 2)(); + list.getIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -374,7 +375,7 @@ list.equal(obj1); let obj2 = {name : "Dylon", age : "13"}; let result = list.equal(obj2); try { - list.equal.bind({}, obj2)(); + list.equal.bind({}, obj2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -420,7 +421,7 @@ list.add(2); list.add(4); let result = list.removeByIndex(2); try { - list.removeByIndex.bind({}, 2)(); + list.removeByIndex.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -469,7 +470,7 @@ list.add(5); list.add(4); let result = list.remove(2); try { - list.remove.bind({}, 2)(); + list.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -524,7 +525,7 @@ list.replaceAllElements((value: number, index: number) => { try { list.replaceAllElements.bind({}, (value: number, index: number) => { return value = 2 * value; - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -576,7 +577,7 @@ list.forEach((value, index) => { try { list.forEach.bind({}, (value, index) => { console.log("value: " + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -623,7 +624,7 @@ list.add(4); list.sort((a: number, b: number) => a - b); list.sort((a: number, b: number) => b - a); try { - list.sort.bind({}, (a: number, b: number) => b - a)(); + list.sort.bind({}, (a: number, b: number) => b - a)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -671,7 +672,7 @@ let result = list.getSubList(2, 4); let result1 = list.getSubList(4, 3); let result2 = list.getSubList(2, 6); try { - list.getSubList.bind({}, 2, 4)(); + list.getSubList.bind({}, 2, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -708,7 +709,7 @@ list.add(5); list.add(4); list.clear(); try { - list.clear.bind({})(); + list.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -754,7 +755,7 @@ list.add(5); list.add(4); list.set(2, "b"); try { - list.set.bind({}, 3, "b")(); + list.set.bind({}, 3, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -797,7 +798,7 @@ list.add(5); list.add(4); let result = list.convertToArray(); try { - list.convertToArray.bind({})(); + list.convertToArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -835,7 +836,7 @@ list.add(5); list.add(4); let result = list.isEmpty(); try { - list.isEmpty.bind({})(); + list.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -873,7 +874,7 @@ list.add(5); list.add(4); let result = list.getFirst(); try { - list.getFirst.bind({})(); + list.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -911,7 +912,7 @@ list.add(5); list.add(4); let result = list.getLast(); try { - list.getLast.bind({})(); + list.getLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -961,7 +962,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - list[Symbol.iterator].bind({})(); + list[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md index a53809173e6b63a26bfe5768a870991171ac22e7..5f07667259c42a4651a409ba78dab990d13fe388 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md +++ b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md @@ -148,7 +148,7 @@ import matrix4 from '@ohos.matrix4' @Entry @Component struct Test { - private matrix1 = Matrix4.identity().translate({x:100}) + private matrix1 = matrix4.identity().translate({x:100}) private matrix2 = this.matrix1.copy().scale({x:2}) build() { diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index c9be6f2af616711ec5ce4c69ed98def44f71cb1f..da6168229c6c24ff3230dec69ab5f41547ba00fe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -300,12 +300,17 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string): Pr **示例:** ```js -let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; -media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ - console.info("getPublicDirectory successfully:"+ JSON.stringify(dicResult)); -}).catch(function(err){ - console.info("getPublicDirectory failed with error:"+ err); -}); +async function example() { + // 使用Promise方式创建Image类型文件 + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + const path = await media.getPublicDirectory(DIR_IMAGE); + media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { + console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); + }).catch((err) => { + console.info('createAsset failed, message = ' + err); + }); +} ``` ### deleteAsset8+ @@ -2587,3 +2592,4 @@ async function example() { | type | string | 是 | 媒体类型,包括:image, video, media,当前仅支持media类型 | | count | number | 是 | 媒体选择,count = 1表示单选,count大于1表示多选。 | + diff --git a/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md b/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md index b47a5d9bd5dcfaaae274b736ec7cf3052eb22703..e576e6611ddd5adce1afe4c1a16c478309bf90f8 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @@ -15,15 +15,15 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou **系统能力**:SystemCapability.MultimodalInput.Input.Core -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ----------- | ------ | ---- | ---- | ---------- | -| CANCEL | number | 是 | 否 | 取消 | -| MOVE | number | 是 | 否 | 鼠标移动 | -| BUTTON_DOWN | number | 是 | 否 | 鼠标按钮按下 | -| BUTTON_UP | number | 是 | 否 | 鼠标按钮抬起 | -| AXIS_BEGIN | number | 是 | 否 | 鼠标关联的轴事件开始 | -| AXIS_UPDATE | number | 是 | 否 | 鼠标关联的轴事件更新 | -| AXIS_END | number | 是 | 否 | 鼠标关联的轴事件结束 | +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ----------- | -------- | ---- | ---- | -------------------- | +| CANCEL | number | 是 | 否 | 取消 | +| MOVE | number | 是 | 否 | 鼠标移动 | +| BUTTON_DOWN | number | 是 | 否 | 鼠标按钮按下 | +| BUTTON_UP | number | 是 | 否 | 鼠标按钮抬起 | +| AXIS_BEGIN | number | 是 | 否 | 鼠标轴事件开始 | +| AXIS_UPDATE | number | 是 | 否 | 鼠标轴事件更新 | +| AXIS_END | number | 是 | 否 | 鼠标轴事件结束 | ## Button @@ -69,14 +69,14 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou | 名称 | 参数类型 | 可读 | 可写 | 描述 | | -------------- | ----------- | ---- | ---- | ---------------------------------------- | | action | Action | 是 | 否 | 鼠标事件动作 | -| screenX | number | 是 | 否 | 鼠标光标在屏幕中的x坐标 | -| screenY | number | 是 | 否 | 鼠标光标在屏幕中的y坐标 | -| windowX | number | 是 | 否 | 鼠标归属窗口的x坐标 | -| windowY | number | 是 | 否 | 鼠标归属窗口的y坐标 | -| rawDeltaX | number | 是 | 否 | X轴相对上次上报鼠标位置的偏移,在屏幕边缘位置时,该值可能小于两次鼠标上报的坐标差 | -| rawDeltaY | number | 是 | 否 | Y轴相对上次上报鼠标位置的偏移 | -| button | Button | 是 | 否 | 当前按下/抬起的按钮 | -| pressedButtons | Button[] | 是 | 否 | 当前处于按下状态的按钮 | +| screenX | number | 是 | 否 | 鼠标光标在屏幕中的横坐标 | +| screenY | number | 是 | 否 | 鼠标光标在屏幕中的纵坐标 | +| windowX | number | 是 | 否 | 鼠标所在窗口的横坐标 | +| windowY | number | 是 | 否 | 鼠标所在窗口的纵坐标 | +| rawDeltaX | number | 是 | 否 | 鼠标本次操作横坐标偏移值 | +| rawDeltaY | number | 是 | 否 | 鼠标本次操作纵坐标偏移值 | +| button | Button | 是 | 否 | 鼠标按钮 +| pressedButtons | Button[] | 是 | 否 | 当前处于按下状态的鼠标按钮 | | axes | AxisValue[] | 是 | 否 | 事件包含的所有轴数据 | | pressedKeys | KeyCode[] | 是 | 否 | 当前处于按下状态的按键列表 | | ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index 3cccd741b976c1b9122a871a11601e411fa18c55..71a0bee5b2b0e60b8ee2984768de9fa1c4891da5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -64,29 +64,57 @@ import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag'; onCreate(want, launchParam) { - // add other code here + // add other code here... // want is initialized by nfc service, contains tag info for this found tag - var tagInfo = tag.getTagInfo(want); - if (tagInfo == undefined) { + var tagInfo; + try { + tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); return; } + + // get the supported technologies for this found tag. var isNfcATag = false; + var isIsoDepTag = false; for (var i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.NFC_A) { isNfcATag = true; - break; } - // also check for technology: tag.NFC_B/NFC_F/NFC_V/ISO_DEP/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; + } + // also check for technology: tag.NFC_B/NFC_F/NFC_V/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE } + + // use NfcA APIs to access the found tag. if (isNfcATag) { - var nfcA = tag.getNfcATag(taginfo); + var nfcA; + try { + nfcA = tag.getNfcATag(taginfo); + } catch (error) { + console.log("tag.getNfcATag catched error: " + error); + } // other code to read or write this found tag. } - // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as: - // var isoDep = tag.getIsoDepTag(taginfo); + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(taginfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } + // other code to read or write this found tag. + } + + // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -154,99 +182,135 @@ getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | NFC V类型Tag对象。 | -## tag.getIsoDepTag9+ +## tag.getIsoDep9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) +getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) -获取IsoDep类型Tag对象,通过该对象可访问Iso Dep技术类型的Tag。 - -**需要权限**:ohos.permission.NFC_TAG +获取IsoDep类型Tag对象,通过该对象可访问支持IsoDep技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | ---------- | ------------------| -| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | Iso Dep类型Tag对象。 | - -## tag.getNdefTag9+ +| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | IsoDep类型Tag对象,通过该对象访问IsoDep类型的相关接口。 | -getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -获取Ndef类型Tag对象,通过该对象可访问Ndef技术类型的Tag。 +## tag.getNdef9+ +getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) -**需要权限**:ohos.permission.NFC_TAG +获取NDEF类型Tag对象,通过该对象可访问支持NDEF技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | ---------| -------------- | -| [NdefTag](js-apis-nfctech.md#ndeftag9) | Ndef类型Tag对象。| +| [NdefTag](js-apis-nfctech.md#ndeftag9) | NDEF类型Tag对象,通过该对象访问NDEF类型的相关接口。| -## tag.getMifareClassicTag9+ +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +## tag.getMifareClassic9+ -获取Mifare Classic类型Tag对象,通过该对象访问Mifare Classic技术类型的Tag。 +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Classic类型Tag对象,通过该对象访问支持MIFARE Classic技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | ----------------- | ------------------------| -| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | Mifare Classic类型Tag对象。 | +| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | MIFARE Classic类型Tag对象,通过该对象访问MIFARE Classic类型的相关接口。 | -## tag.getMifareUltralightTag9+ +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +## tag.getMifareUltralight9+ -获取Mifare Ultralight类型Tag对象,通过该对象可访问Mifare Ultralight技术类型的Tag。 +getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Ultralight类型Tag对象,通过该对象可访问支持MIFARE Ultralight技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | -------------------- | ---------------------------| -| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | Mifare Ultralight类型Tag对象。 | +| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | MIFARE Ultralight类型Tag对象,通过该对象访问MIFARE Ultralight类型的相关接口。 | -## tag.getNdefFormatableTag9+ +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +## tag.getNdefFormatable9+ -获取Ndef Formatable类型Tag对象,通过该对象可访问Ndef Formatable技术类型的Tag。 +getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) -**需要权限**:ohos.permission.NFC_TAG +获取NDEF Formatable类型Tag对象,通过该对象可访问支持NDEF Formatable技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | Ndef Formatable类型Tag对象。 | +| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | NDEF Formatable类型Tag对象,通过该对象访问NDEF Formatable类型的相关接口。 | + +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | ## tag.getTagInfo9+ -getTagInfo(want: Want): [TagInfo](#taginfo) +getTagInfo(want: [Want](js-apis-application-Want.md#Want)): [TagInfo](#taginfo) 从Want中获取TagInfo,Want是被NFC服务初始化,包含了TagInfo所需的属性值。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-application-Want.md#Want) | 是 | 分发Ability时,在系统onCreate入口函数的参数中获取。 | +**返回值:** | **类型** | **说明** | | ------------------ | --------------------------| | [TagInfo](#taginfo) | TagInfo对象,用于获取不同技术类型的Tag对象。 | @@ -255,8 +319,6 @@ getTagInfo(want: Want): [TagInfo](#taginfo) NFC服务在读取到标签时给出的对象,通过改对象属性,应用知道该标签支持哪些技术类型,并使用匹配的技术类型来调用相关接口。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **类型** | **说明** | @@ -268,8 +330,6 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 ## NdefRecord9+ NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **类型** | **说明** | | -------- | -------- | -------- | @@ -281,8 +341,6 @@ NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDE ## 技术类型定义 NFC Tag有多种不同的技术类型,定义常量描述不同的技术类型。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -292,15 +350,13 @@ NFC Tag有多种不同的技术类型,定义常量描述不同的技术类型 | NFC_F | 4 | NFC-F(JIS 6319-4)技术。| | NFC_V | 5 | NFC-V(ISO 15693)技术。| | NDEF | 6 | NDEF技术。| -| MIFARE_CLASSIC | 8 | Mifare Classic技术。| -| MIFARE_ULTRALIGHT | 9 | Mifare Utralight技术。| +| 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》的定义细节。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -315,8 +371,6 @@ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFC ## NDEF Record RTD类型定义 NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -326,8 +380,6 @@ NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规 ## NfcForumType9+ NFC Forum标准里面Tag类型的定义。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -335,25 +387,21 @@ NFC Forum标准里面Tag类型的定义。 | NFC_FORUM_TYPE_2 | 2 | NFC论坛类型2。 | | NFC_FORUM_TYPE_3 | 3 | NFC论坛类型3。 | | NFC_FORUM_TYPE_4 | 4 | NFC论坛类型4。 | -| MIFARE_CLASSIC | 101 | Mifare Classic类型。 | +| MIFARE_CLASSIC | 101 | MIFARE Classic类型。 | ## MifareClassicType9+ -MifareClassic标签类型的定义。 - -**需要权限**:ohos.permission.NFC_TAG +MIFARE Classic标签类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | 未知Mifare类型。 | -| TYPE_CLASSIC | 0 | Mifare Classic类型。| -| TYPE_PLUS | 1 | Mifare Plus类型。| -| TYPE_PRO | 2 | Mifare Pro类型。 | +| TYPE_UNKNOWN | 0 | 未知MIFARE类型。 | +| TYPE_CLASSIC | 1 | MIFARE Classic类型。| +| TYPE_PLUS | 2 | MIFARE Plus类型。| +| TYPE_PRO | 3 | MIFARE Pro类型。 | ## MifareClassicSize9+ -MifareClassic标签存储大小的定义。 - -**需要权限**:ohos.permission.NFC_TAG +MIFARE Classic标签存储大小的定义。 **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | @@ -363,15 +411,13 @@ MifareClassic标签存储大小的定义。 | MC_SIZE_2K | 2048 | 每个标签32个扇区,每个扇区4个块。 | | MC_SIZE_4K | 4096 | 每个标签40个扇区,每个扇区4个块。| -### MifareUltralightType9+ -MifareUltralight标签类型的定义。 - -**需要权限**:ohos.permission.NFC_TAG +## MifareUltralightType9+ +MIFARE Ultralight标签类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | 未知的 Mifare 类型。 | -| TYPE_ULTRALIGHT | 1 | Mifare Ultralight类型。| -| TYPE_ULTRALIGHT_C | 2 | Mifare UltralightC 类型。 | +| TYPE_UNKOWN | 0 | 未知的 MIFARE 类型。 | +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight类型。| +| TYPE_ULTRALIGHT_C | 2 | MIFARE UltralightC 类型。 | \ No newline at end of file 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 2ddd53f960a95e6d2b230017b8c34d17f1c8617f..f198cca93ffad384df83c41be315cc0a0c252b7c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfctech.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfctech.md @@ -15,7 +15,7 @@ import tag from '@ohos.nfc.tag'; NfcATag 提供 NFC-A(ISO 14443-3A)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcATag的独有接口。 @@ -40,8 +40,7 @@ getSak(): number ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcA' correctly. - +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcA' correctly. let sak = nfcA.getSak(); console.log("nfcA sak: " + sak); ``` @@ -67,7 +66,7 @@ getAtqa(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcA' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcA' correctly. let atqa = nfcA.getAtqa(); console.log("nfcA atqa: " + atqa); ``` @@ -76,7 +75,7 @@ console.log("nfcA atqa: " + atqa); NfcBTag 提供对NFC-B(ISO 14443-3B)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类,提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类,提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcBTag的独有接口。 @@ -101,7 +100,7 @@ getRespAppData(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcB' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcB' correctly. let respAppData = nfcB.getRespAppData(); console.log("nfcB respAppData: " + respAppData); ``` @@ -127,7 +126,7 @@ getRespProtocol(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcB' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcB' correctly. let respProtocol = nfcB.getRespProtocol(); console.log("nfcB respProtocol: " + respProtocol); ``` @@ -136,7 +135,7 @@ console.log("nfcB respProtocol: " + respProtocol); NfcFTag 提供对NFC-F(JIS 6319-4)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcFTag的独有接口。 @@ -161,7 +160,7 @@ getSystemCode(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcF' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcF' correctly. let systemCode = nfcF.getSystemCode(); console.log("nfcF systemCode: " + systemCode); ``` @@ -187,7 +186,7 @@ getPmm(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcF' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcF' correctly. let pmm = nfcF.getPmm(); console.log("nfcF pmm: " + pmm); ``` @@ -196,7 +195,7 @@ console.log("nfcF pmm: " + pmm); NfcVTag 提供对NFC-V(ISO 15693)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcVTag的独有接口。 @@ -221,7 +220,7 @@ getResponseFlags(): number ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcV' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcV' correctly. let responseFlags = nfcV.getResponseFlags(); console.log("nfcV responseFlags: " + responseFlags); ``` @@ -247,7 +246,7 @@ getDsfId(): number ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcV' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcV' correctly. let dsfId = nfcV.getDsfId(); console.log("nfcV dsfId: " + dsfId); ``` @@ -256,7 +255,7 @@ console.log("nfcV dsfId: " + dsfId); IsoDepTag 提供对ISO-DEP(ISO 14443-4)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是IsoDepTag的独有接口。 @@ -264,24 +263,20 @@ TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送 getHistoricalBytes(): number[] -获取标签的历史字节。 - -**需要权限**:ohos.permission.NFC_TAG +获取标签的历史字节,针对基于NfcA通信技术的IsoDep卡片。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number[] | IsoDepTag 标签的历史字节,每个number十六进制表示,范围是0x00~0xFF。| +| number[] | IsoDepTag 标签的历史字节,每个number十六进制表示,范围是0x00~0xFF。如果该IsoDep类型Tag是基于NfcB技术的,则该返回值为空。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. let historicalBytes = isoDep.getHistoricalBytes(); console.log("isoDep historicalBytes: " + historicalBytes); ``` @@ -290,24 +285,20 @@ console.log("isoDep historicalBytes: " + historicalBytes); getHiLayerResponse(): number[] -获取标签的HiLayer响应字节。 - -**需要权限**:ohos.permission.NFC_TAG +获取标签的更高层响应字节,针对基于NfcB通信技术的IsoDep卡片。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number[] | IsoDepTag 标签的HiLayer响应字节,每个number十六进制表示,范围是0x00~0xFF。| +| number[] | IsoDepTag 标签的更高层响应字节,每个number十六进制表示,范围是0x00~0xFF。如果该IsoDep类型Tag是基于NfcA技术的,则该返回值为空。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. let hiLayerResponse = isoDep.getHiLayerResponse(); console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` @@ -316,137 +307,368 @@ console.log("isoDep hiLayerResponse: " + hiLayerResponse); isExtendedApduSupported(): Promise<boolean> -检查是否支持扩展的APDU,使用promise方式作为异步方法。 +检查是否支持扩展的APDU,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | Promise<boolean> | 检查结果,true: 支持, false: 不支持。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported() - .then((data) => { - console.log("isoDep isExtendedApduSupported data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. + +// connect the tag at first if not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported().then((response) => { + console.log("isoDep isExtendedApduSupported Promise response: " + response); }).catch((err)=> { - console.log("isoDep isExtendedApduSupported err: " + err); + console.log("isoDep isExtendedApduSupported Promise err: " + err); }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError); +} + ``` ### IsoDepTag.isExtendedApduSupported9+ isExtendedApduSupported(callback: AsyncCallback\): void -检查是否支持扩展的APDU,使用callback方式作为异步方法。 +检查是否支持扩展的APDU,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | 是 | 回调函数,true: 支持, false: 不支持。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported((err, data)=> { - if (err) { - console.log("isoDep isExtendedApduSupported err: " + err); - } else { - console.log("isoDep isExtendedApduSupported data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. + +// connect the tag at first if not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; } -}); +} + +try { + isoDep.isExtendedApduSupported((err, response)=> { + if (err) { + console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err); + } else { + console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError); +} ``` -## NdefTag9+ +## NdefMessage9+ -提供对已格式化为NDEF的NFC标签的数据和操作的访问,继承自TagSession。 +### NdefMessage.getNdefRecords9+ -TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] -以下是NdefTag的独有接口。 +获取NDEF消息中的所有记录。 -### NdefTag.createNdefMessage9+ +**系统能力**:SystemCapability.Communication.NFC -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | -使用原始字节创建ndef消息。 +**示例:** +```js +import tag from '@ohos.nfc.tag'; -**需要权限**:ohos.permission.NFC_TAG +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); -**系统能力**:SystemCapability.Communication.NFC +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 **参数:** -| **参数名** | **类型** | **必填** | **说明** | -| -------- | -------- | -------- | -------- | -| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | 是 | 写入到NDEF Record里面的数据内容。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | +| [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 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. -let ndefMessage = ndef.createNdefMessage(rawData); -console.log("ndef ndefMessage: " + ndefMessage); +// 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); +} ``` -## NdefMessage9+ -### NdefMessage.getNdefRecords9+ +### NdefMessage.makeMimeRecord9+ -getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] +makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); -获取ndef消息的所有记录。 +根据输入的MIME数据和类型,构建NDEF标签的Record。 -**需要权限**:ohos.permission.NFC_TAG +**系统能力**: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消息数据对象。 | + +**返回值:** | **类型** | **说明** | | ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | +| 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。 + +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 + +以下是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', has obtained the 'ndef' correctly. -let ndefRecords = ndef.getNdefRecords(); -console.log("ndef ndefRecords number: " + ndefRecords.length); +// 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消息。 - -**需要权限**:ohos.permission.NFC_TAG +使用NDEF Records列表,创建NDEF Message。 **系统能力**:SystemCapability.Communication.NFC @@ -456,17 +678,15 @@ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) | 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', has obtained the 'ndef' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. let ndefRecords = [ // record format: tnf, rtdType, id, payload // 1st record: @@ -477,33 +697,34 @@ let ndefRecords = [ // other record if has one ... ]; -let ndefMessage = ndef.createNdefMessage(ndefRecords); -console.log("ndef ndefMessage: " + ndefMessage); +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标签的类型。 - -**需要权限**:ohos.permission.NFC_TAG +获取NDEF标签的类型。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF标签类型,包括NFC FORUM TYPE 1/2/3/4等。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefTagType = ndef.getNdefTagType(); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +let ndefTagType = ndefTag.getNdefTagType(); console.log("ndef ndefTagType: " + ndefTagType); ``` @@ -513,217 +734,237 @@ getNdefMessage(): NdefMessage 获取发现NDEF标签时,从标签读取的Message。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefMessage = ndef.getNdefMessage(); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +let ndefMessage = ndefTag.getNdefMessage(); console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ -isNdefWritable(): Promise<boolean> - -检查NDEF标签是否可写,使用promise方式作为异步方法。 +isNdefWritable(): boolean; -**需要权限**:ohos.permission.NFC_TAG +检查NDEF标签是否可写。在调用写数据接口前,需要先判断是否支持写操作。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| Promise<boolean> | 检查结果,true: 可写, false: 不可写。| +| boolean | 检查结果,true: 可写, false: 不可写。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.isNdefWritable() - .then((data) => { - console.log("ndef isNdefWritable data: " + data); - }).catch((err)=> { - console.log("ndef isNdefWritable err: " + err); - }); -``` - -### NdefTag.isNdefWritable9+ - -isNdefWritable(callback: AsyncCallback<boolean>): void; - -检查ndef标签是否可写,使用callback方式作为异步方法。 - -**需要权限**:ohos.permission.NFC_TAG - -**系统能力**:SystemCapability.Communication.NFC - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数,NDEF标签可写,返回true。 | - -**示例:** - -```js -import tag from '@ohos.nfc.tag'; - -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.isNdefWritable((err, data)=> { - if (err) { - console.log("ndef isNdefWritable err: " + err); - } else { - console.log("ndef isNdefWritable data: " + data); - } -}); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +var isWritable = ndefTag.isNdefWritable(); +console.log("ndef isNdefWritable: " + isWritable); ``` ### NdefTag.readNdef9+ readNdef(): Promise\ -读取标签上的ndef消息,使用promise方式作为异步方法。 +读取标签上的NDEF消息,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| Promise\<[NdefMessage](#ndefmessage9)> | 以Promise形式返回从NDEF标签中读取到的Message信息。| +| Promise\<[NdefMessage](#ndefmessage9)> | 以Promise形式返回从NDEF标签中读取到的Message数据对象。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.readNdef() - .then((data) => { - console.log("ndef readNdef data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.readNdef().then((ndefmessage) => { + console.log("ndef readNdef Promise ndefmessage: " + ndefmessage); }).catch((err)=> { - console.log("ndef readNdef err: " + err); + console.log("ndef readNdef Promise err: " + err); }); +} catch (busiError) { + console.log("ndef readNdef Promise catched busiError: " + busiError); +} ``` ### NdefTag.readNdef9+ readNdef(callback: AsyncCallback\<[NdefMessage](#ndefmessage9)>): void -读取标签上的ndef消息,使用callback方式作为异步方法。 +读取标签上的NDEF消息,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | 是 | 回调函数。| +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | 是 | 回调函数,返回从NDEF标签中读取到的Message信息。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.readNdef((err, data)=> { - if (err) { - console.log("ndef readNdef err: " + err); - } else { - console.log("ndef readNdef data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.readNdef((err, ndefmessage)=> { + if (err) { + console.log("ndef readNdef AsyncCallback err: " + err); + } else { + console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage); + } + }); +} catch (busiError) { + console.log("ndef readNdef AsyncCallback catched busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage): Promise\; +writeNdef(msg: NdefMessage): Promise\; -将ndef消息写入标签,使用promise方式作为异步方法。 +将NDEF Messsage数据对象写入标签,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | 是 | Ndef消息。| - -**返回值:** +| msg | NdefMessage | 是 | NDEF Message数据对象。| -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 以Promise形式返回,写入执行后的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +// 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[]) -ndef.writeNdef(ndefMessage) - .then((data) => { - console.log("ndef writeNdef data: " + data); +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.writeNdef(ndefMessage).then(() => { + console.log("ndef writeNdef Promise success."); }).catch((err)=> { console.log("ndef writeNdef err: " + err); }); +} catch (busiError) { + console.log("ndef writeNdef Promise catch busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage, callback: AsyncCallback\): void +writeNdef(msg: NdefMessage, callback: AsyncCallback\): void -将ndef消息写入此标签,使用callback方式作为异步方法。 +将NDEF Message数据对象写入此标签,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | 是 | Ndef消息 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| msg | NdefMessage | 是 | NDEF Message数据对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. -ndef.writeNdef(ndefMessage, (err, data)=> { - if (err) { - console.log("ndef writeNdef err: " + err); - } else { - console.log("ndef writeNdef data: " + data); +// 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[]) + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.writeNdef(ndefMessage, (err)=> { + if (err) { + console.log("ndef writeNdef AsyncCallback err: " + err); + } else { + console.log("ndef writeNdef AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.canSetReadOnly9+ @@ -737,659 +978,874 @@ canSetReadOnly(): boolean **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | boolean| true: NDEF标签可设置为只读, false: NDEF标签不可设置为只读。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -var canSetReadOnly = ndef.canSetReadOnly(); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +var canSetReadOnly = ndefTag.canSetReadOnly(); console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ -setReadOnly(): Promise\ +setReadOnly(): Promise\ -将Ndef标签设置为只读,使用promise方式作为异步方法。 +将NDEF标签设置为只读,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise<number> | 0: 设置成功, 其它: 错误编码。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.setReadOnly() - .then((data) => { - console.log("ndef setReadOnly data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.setReadOnly().then(() => { + console.log("ndef setReadOnly Promise success."); }).catch((err)=> { - console.log("ndef setReadOnly err: " + err); + console.log("ndef setReadOnly Promise err: " + err); }); +} catch (busiError) { + console.log("ndef setReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback\): void +setReadOnly(callback: AsyncCallback\): void -将Ndef标签设置为只读,使用callback方式作为异步方法。 +将NDEF标签设置为只读,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.setReadOnly((err, data)=> { - if (err) { - console.log("ndef setReadOnly err: " + err); - } else { - console.log("ndef setReadOnly data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.setReadOnly((err)=> { + if (err) { + console.log("ndef setReadOnly AsyncCallback err: " + err); + } else { + console.log("ndef setReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.getNdefTagTypeString9+ getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -将Nfc论坛类型转换为Nfc论坛中定义的字节数组。 - -**需要权限**:ohos.permission.NFC_TAG +将NFC论坛类型,转换为NFC论坛中定义的字符串描述。 **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | | type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | 是 | NDEF标签类型,包括NFC FORUM TYPE 1/2/3/4等。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | string | NFC论坛类型的字符串描述。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); -console.log("ndef ndefTypeString: " + ndefTypeString); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +try { + let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); + console.log("ndef ndefTypeString: " + ndefTypeString); +} catch (busiError) { + console.log("ndef getNdefTagTypeString catch busiError: " + busiError); +} ``` ## MifareClassicTag9+ -MifareClassicTag提供对MIFARE经典属性和I/O操作的访问,继承自TagSession。 +MifareClassicTag提供对MIFARE Classic属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是MifareClassicTag的独有接口。 ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ -使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用promise方式作为异步方法。 +使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 待验证的扇区索引 | -| key | number[]| 是 | 用于身份验证的密钥(6字节) | +| sectorIndex | number | 是 | 待验证的扇区索引,从0开始。 | +| key | number[]| 是 | 用于扇区验证的密钥(6字节)。 | | isKeyA | boolean | 是 | isKeyA标志。true 表示KeyA,false 表示KeyB。| -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 身份验证结果,成功返回true,失败返回false。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true); - .then((data) => { - console.log("mifareClassic authenticateSector data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let sectorIndex = 1; // change it to be correct index. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // MUST be 6 bytes, change it to be correct key. + mifareClassic.authenticateSector(sectorIndex, key, true).then(() => { + console.log("mifareClassic authenticateSector Promise success."); }).catch((err)=> { - console.log("mifareClassic authenticateSector err: " + err); + console.log("mifareClassic authenticateSector Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void -使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用callback方式作为异步方法。 +使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 待验证的扇区索引。 | -| key | number[]| 是 | 用于身份验证的密钥(6字节)。 | +| sectorIndex | number | 是 | 待验证的扇区索引,从0开始。 | +| key | number[]| 是 | 用于扇区验证的密钥(6字节)。 | | isKeyA | boolean | 是 | isKeyA标志。true 表示KeyA,false 表示KeyB。| -| callback | AsyncCallback\ | 是 | 回调函数。| +| callback | AsyncCallback\ | 是 | 回调函数。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { - if (err) { - console.log("mifareClassic authenticateSector err: " + err); - } else { - console.log("mifareClassic authenticateSector data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let sectorIndex = 1; // change it to be correct index. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // MUST be 6 bytes, change it to be correct key. + mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> { + if (err) { + console.log("mifareClassic authenticateSector AsyncCallback err: " + err); + } else { + console.log("mifareClassic authenticateSector AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number): Promise\ -读取标签中一个块存储的内容,一个块大小为16字节。使用promise方式作为异步方法。 +读取标签中一个块存储的内容,一个块大小为16字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要读取的块索引。 | +| blockIndex | number | 是 | 要读取的块索引,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | Promise\ | 读取的块数据。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.readSingleBlock(blockIndex).then((data) => { + console.log("mifareClassic readSingleBlock Promise data: " + data); + }).catch((err)=> { + console.log("mifareClassic readSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -读取标签中一个块存储的内容,一个块大小为16字节。使用callback方式作为异步方法。 +读取标签中一个块存储的内容,一个块大小为16字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要读取的块索引 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要读取的块索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回读取到的数据。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic readSingleBlock AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[]): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ -向标签中一个块存储写入内容,一个块大小为16字节。使用promise方式作为异步方法。 +向标签中一个块存储写入内容,一个块大小为16字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要写入的块索引。 | -| data | number[] | 是 | 要写入的数据。 | +| blockIndex | number | 是 | 要写入的块索引,从0开始。 | +| data | number[] | 是 | 要写入的数据,大小必须是16个字节。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行写入操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, ..., 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => { + console.log("mifareClassic writeSingleBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic writeSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void -向标签中一个块存储写入内容,一个块大小为16字节。使用callback方式作为异步方法。 +向标签中一个块存储写入内容,一个块大小为16字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要写入的块索引 | -| data | number[] | 是 | 要写入的数据 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要写入的块索引,从0开始。 | +| data | number[] | 是 | 要写入的数据,大小必须是16个字节。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, ..., 0x15, 0x16]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> { + if (err) { + console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic writeSingleBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number): Promise\ +incrementBlock(blockIndex: number, value: number): Promise\ -增加一块带值的区域块。使用promise方式作为异步方法。 +对指定块的内容,增加指定的数值。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要增加的块索引。 | -| value | number | 是 | 要增加的块数据,非负值。 | +| blockIndex | number | 是 | 要指定增加的块索引,从0开始。 | +| value | number | 是 | 要指定增加的数据,非负数。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行新增操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.incrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic incrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic incrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -增加一块带值的区域块。使用callback方式作为异步方法。 +对指定块的内容,增加指定的数值。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要增加的块索引。 | -| value | number | 是 | 要增加的块数据,非负值。 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要被运算的块索引,从0开始。 | +| value | number | 是 | 要增加的数值,非负数。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.incrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic incrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic incrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number): Promise\ +decrementBlock(blockIndex: number, value: number): Promise\ -递减一块带值的区域块。使用promise方式作为异步方法。 +对指定块的内容,减少指定的数值。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要递减的块索引。 | -| value | number | 是 | 要递减的块数据,非负值。 | +| blockIndex | number | 是 | 要被运算的块索引,从0开始。 | +| value | number | 是 | 要减少的数值,非负数。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行递减操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.decrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic decrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic decrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -递减一块带值的区域块。使用callback方式作为异步方法。 +对指定块的内容,减少指定的数值。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要递减的块索引。 | -| value | number | 是 | 要递减的块数据,非负值。 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要被运算的块索引,从0开始。 | +| value | number | 是 | 要减少的数值,非负数。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.decrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic decrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic decrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number): Promise\ +transferToBlock(blockIndex: number): Promise\ -将寄存器的值复制到块。使用promise方式作为异步方法。 +将临时寄存器的值转移到指定的块。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的目的块索引。 | +| blockIndex | number | 是 | 被操作的块的索引,从0开始。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行复制操作返回的错误代码。如果返回0,表示成功;否则返回错误码。| +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js - import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.transferToBlock(blockIndex).then(() => { + console.log("mifareClassic transferToBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic transferToBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number, callback: AsyncCallback\): void +transferToBlock(blockIndex: number, callback: AsyncCallback\): void -将寄存器的值复制到块。使用callback方式作为异步方法。 +将临时寄存器的值转移到指定的块。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的目的块索引 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 被操作的块的索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.transferToBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic transferToBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic transferToBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number): Promise\ +restoreFromBlock(blockIndex: number): Promise\ -将块的值复制到寄存器。使用promise方式作为异步方法。 +将指定块的值复制到临时寄存器。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的源块索引。| - -**返回值:** +| blockIndex | number | 是 | 被操作的块的索引,从0开始。| -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行复制操作返回的错误代码。如果返回0,表示成功;否则返回错误码。| +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js - import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex) - .then((data) => { - console.log("mifareClassic restoreFromBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.restoreFromBlock(blockIndex).then(() => { + console.log("mifareClassic restoreFromBlock Promise success."); }).catch((err)=> { - console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + console.log("mifareClassic restoreFromBlock Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void -将块的值复制到寄存器。使用callback方式作为异步方法。 +将指定块的值复制到临时寄存器。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的源块索引 | -| callback | AsyncCallback\ | 是 | 回调函数。| +| blockIndex | number | 是 | 被操作的块的索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic restoreFromBlock err: " + err); - } else { - console.log("mifareClassic restoreFromBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.restoreFromBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic restoreFromBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorCount9+ getSectorCount(): number -获取mifare classic标签中的扇区数。 - -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Classic标签中的扇区数。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number | 扇区数量。| +| number | 标签中的扇区数量。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let sectorCount = mifareClassic.getSectorCount(); console.log("mifareClassic sectorCount: " + sectorCount); ``` @@ -1398,56 +1854,53 @@ console.log("mifareClassic sectorCount: " + sectorCount); getBlockCountInSector(sectorIndex: number): number -获取扇区中的块数。 - -**需要权限**:ohos.permission.NFC_TAG +获取指定扇区中的块数。 **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 扇区序号。| +| sectorIndex | number | 是 | 扇区序号,从0开始。| **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | number | 该扇区内的块数量。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockCountInSector = mifareClassic.getBlockCountInSector(); -console.log("mifareClassic blockCountInSector: " + blockCountInSector); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // change it to be correct index. + let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex); + console.log("mifareClassic blockCnt: " + blockCnt); +} catch (busiError) { + console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError); +} ``` ### MifareClassicTag.getType9+ getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) -获取MifareClassic标签的类型。 - -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Classic标签的类型。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | MifareClassic标签的类型。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let getType = mifareClassic.getType(); console.log("mifareClassic getType: " + getType); ``` @@ -1456,24 +1909,20 @@ console.log("mifareClassic getType: " + getType); getTagSize(): number -获取标签的大小(字节),具体请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。 - -**需要权限**:ohos.permission.NFC_TAG +获取标签的存储空间大小,具体请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | number | 标签的大小,单位为字节,请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let tagSize = mifareClassic.getTagSize(); console.log("mifareClassic tagSize: " + tagSize); ``` @@ -1482,24 +1931,20 @@ console.log("mifareClassic tagSize: " + tagSize); isEmulatedTag(): boolean -检查标签是否已模拟。 - -**需要权限**:ohos.permission.NFC_TAG +检查标签是不是被模拟的。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | boolean |检查结果,true: 是;false:否。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let isEmulatedTag = mifareClassic.isEmulatedTag(); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` @@ -1508,73 +1953,75 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); getBlockIndex(sectorIndex: number): number -获取特定扇区的第一个块。 - -**需要权限**:ohos.permission.NFC_TAG +获取特定扇区的第一个块的序号。 **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 扇区序号。 | +| sectorIndex | number | 是 | 扇区序号,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number | 该扇区内的第一个块的序列号。 | +| number | 该扇区内的第一个块的序号,从0开始。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let blockIndex = mifareClassic.getBlockIndex(sectorIndex); -console.log("mifareClassic blockIndex: " + blockIndex); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // change it to be correct index. + let blockIndex = mifareClassic.getBlockIndex(sectorIndex); + console.log("mifareClassic blockIndex: " + blockIndex); +} catch (busiError) { + console.log("mifareClassic getBlockIndex catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorIndex9+ getSectorIndex(blockIndex: number): number -获取扇区索引,该扇区包含特定块。 +获取包含指定块号的扇区序号。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 块序号。 | +| blockIndex | number | 是 | 块序号,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number | 扇区序号。 | +| number | 扇区序号,从0开始。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let sectorIndex = mifareClassic.getSectorIndex(blockIndex); -console.log("mifareClassic sectorIndex: " + sectorIndex); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +try { + let blockIndex = 1; // change it to be correct index. + let sectorIndex = mifareClassic.getSectorIndex(blockIndex); + console.log("mifareClassic sectorIndex: " + sectorIndex); +} catch (busiError) { + console.log("mifareClassic getSectorIndex catch busiError: " + busiError); +} ``` ## MifareUltralightTag9+ -MifareUltralightTag 提供对MIFARE超轻属性和I/O操作的访问,继承自TagSession。 +MifareUltralightTag 提供对MIFARE Ultralight属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是MifareUltralightTag的独有接口。 @@ -1582,7 +2029,7 @@ TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送 readMultiplePages(pageIndex: number): Promise\ -阅读4页,共16字节。页面大小为4字节。使用promise方式作为异步方法。 +读取标签的4页数据,共16字节的数据。每个页面数据大小为4字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG @@ -1592,298 +2039,383 @@ readMultiplePages(pageIndex: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | ------------------------------ | -| pageIndex | number | 是 | 要读取页面的索引。 | +| pageIndex | number | 是 | 要读取页面的索引,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| Promise\ | 读取的4页的数据。 | +| Promise\ | 读取的4页的数据,共16字节。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex) - .then((data) => { - console.log("mifareUltralight readMultiplePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // change it to be correct index. + mifareUltralight.readMultiplePages(pageIndex).then((data) => { + console.log("mifareUltralight readMultiplePages Promise data = " + data); }).catch((err)=> { - console.log("mifareUltralight readMultiplePages err: " + err); + console.log("mifareUltralight readMultiplePages Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError); +} ``` ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -阅读4页,共16字节。页面大小为4字节。使用callback方式作为异步方法。 +读取标签的4页数据,共16字节的数据。每个页面数据大小为4字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | 是 | 要读取页面的索引 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| pageIndex | number | 是 | 要读取页面的索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回读取到的数据,共16字节。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { - if (err) { - console.log("mifareUltralight readMultiplePages err: " + err); - } else { - console.log("mifareUltralight readMultiplePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // change it to be correct index. + mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err); + } else { + console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[]): Promise\ +writeSinglePage(pageIndex: number, data: number[]): Promise\ -写入一页数据,页面大小为4字节。使用promise方式作为异步方法。 +写入一页数据,数据大小为4字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | 是 | 要写入页面的索引。 | -| data | number[] | 是 | 要写入页面的数据内容。 | - -**返回值:** +| pageIndex | number | 是 | 要写入页面的索引,从0开始。 | +| data | number[] | 是 | 要写入页面的数据内容,必须是4个字节大小。 | -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行写入操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data) - .then((data) => { - console.log("mifareUltralight writeSinglePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => { + console.log("mifareUltralight writeSinglePage Promise success."); }).catch((err)=> { - console.log("mifareUltralight writeSinglePages err: " + err); + console.log("mifareUltralight writeSinglePage Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void +writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\): void -写入一页数据,页面大小为4字节。使用callback方式作为异步方法。 +写入一页数据,数据大小为4字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | ------------------------ | -| pageIndex | number | 是 | 要写入页面的索引。 | -| data | number[] | 是 | 要写入页面的数据内容。 | -| callback|AsyncCallback\ |是| 回调函数。 | +| pageIndex | number | 是 | 要写入页面的索引,从0开始。 | +| data | number[] | 是 | 要写入页面的数据内容,必须是4个字节大小。 | +| callback|AsyncCallback\ |是| 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { - if (err) { - console.log("mifareUltralight writeSinglePages err: " + err); - } else { - console.log("mifareUltralight writeSinglePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> { + if (err) { + console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err); + } else { + console.log("mifareUltralight writeSinglePage AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError); +} ``` ### MifareUltralightTag.getType9+ getType(): MifareUltralightType -获取MifareUltralight标签的类型,以字节形式返回,具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。 - -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Ultralight标签的类型,具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| MifareUltralightType | MifareUltralight标签的类型, 具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。| +| MifareUltralightType | MIFARE Ultralight标签的类型,具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. let getType = mifareClassic.getType(); console.log("mifareUltralight getType: " + getType); ``` ## NdefFormatableTag9+ -NdefFormatableTag为NDEF formattable的标签提供格式化操作,继承自TagSession。 +NdefFormatableTag为NDEF Formattable的标签提供格式化操作,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NdefFormatableTag的独有接口。 ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9)): Promise\ +format(message: [NdefMessage](#ndefmessage9)): Promise\ -将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签。使用promise方式作为异步方法。 +将标签格式化为NDEF标签,将NDEF消息写入NDEF标签。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的Ndef消息。可以为null,为null时仅格式化标签,不写入内容。 | +| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的NDEF消息。可以为null,为null时仅格式化标签,不写入内容。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行操作后返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +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[]) + + ndefFormatable.format(ndefMessage).then(() => { + console.log("ndefFormatable format Promise success."); + }).catch((err)=> { + console.log("ndefFormatable format Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable format Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void -将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签。使用callback方式作为异步方法。 +将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | | message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的Ndef消息。可以为null,为null时仅格式化标签,不写入内容。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | 回调函数。 | +| callback: AsyncCallback\ | 回调函数。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +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[]) + + ndefFormatable.format(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable format AsyncCallback err: " + err); + } else { + console.log("ndefFormatable format AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ -将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签,之后将标签设置为只读。使用promise方式作为异步方法。 +将标签格式化为NDEF标签,将NDEF消息写入NDEF标签,之后将标签设置为只读。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的Ndef消息。可以为null,为null时仅格式化标签,不写入内容。 | - -**返回值:** +| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的NDEF消息。可以为null,为null时仅格式化标签,不写入内容。 | -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行操作后返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +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[]) + + ndefFormatable.formatReadOnly(ndefMessage).then(() => { + console.log("ndefFormatable formatReadOnly Promise success."); + }).catch((err)=> { + console.log("ndefFormatable formatReadOnly Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void 将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签,之后将标签设置为只读。使用callback方式作为异步方法。 @@ -1892,33 +2424,43 @@ formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\ | 回调函数。 | +| callback: AsyncCallback\ | 回调函数。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +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[]) + + ndefFormatable.formatReadOnly(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err); + } else { + console.log("ndefFormatable formatReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError); +} ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-notification.md b/zh-cn/application-dev/reference/apis/js-apis-notification.md index 454ff579051073954699875f933493f999809aad..c3633af4282dafbbaddee308d58eb327dc505ff0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -3414,6 +3414,8 @@ Notification.getSyncNotificationEnabledWithoutApp(userId) ## NotificationSubscriber +提供订阅者接收到新通知或取消通知时的回调方法。 + **系统API**:此接口为系统接口,三方应用不支持调用。 ### onConsume @@ -3424,7 +3426,7 @@ onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void **系统能力**:SystemCapability.Notification.Notification -**系统API**: 此接口为系统接口,三方应用不支持调用。 +**系统接口**: 此接口为系统接口,三方应用不支持调用。 **参数:** @@ -3834,6 +3836,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationActionButton +描述通知中显示的操作按钮。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3846,6 +3850,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationBasicContent +描述普通文本通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3857,6 +3863,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationLongTextContent +描述长文本通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3871,6 +3879,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationMultiLineContent +描述多行文本通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3885,6 +3895,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationPictureContent +描述附有图片的通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3899,6 +3911,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationContent +描述通知类型。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3912,9 +3926,11 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlagStatus8+ +描述通知标志状态。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification -**系统API**:此接口为系统接口,三方应用不支持调用。 +**系统接口**:此接口为系统接口,三方应用不支持调用。 | 名称 | 值 | 描述 | | -------------- | --- | --------------------------------- | @@ -3925,6 +3941,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlags8+ +描述通知标志的实例。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3935,6 +3953,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationRequest +描述通知的请求。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3980,6 +4000,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## DistributedOptions8+ +描述分布式选项。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3992,6 +4014,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSlot +描述通知槽 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -4012,6 +4036,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSorting +提供有关活动通知的排序信息。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统API**: 此接口为系统接口,三方应用不支持调用。 @@ -4025,6 +4051,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSortingMap +提供关于已订阅的所有通知中活动通知的排序信息 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -4037,6 +4065,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSubscribeInfo +设置订阅所需通知的发布者的信息。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统API**: 此接口为系统接口,三方应用不支持调用。 @@ -4049,6 +4079,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationTemplate8+ +通知模板。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 参数类型 | 可读 | 可写 | 说明 | @@ -4059,6 +4091,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationUserInput8+ +保存用户输入的通知消息。 + **系统能力**:SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index 0043100ba5eaa5b540517d43d75dc813d0f70a8d..7cc29cfcc0989fe5067656ef9345c78358aac775 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -1594,7 +1594,7 @@ createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInf | 类型 | 说明 | | ---------------------------------------------- | ------------------------------------- | -| Promise<[OsAccountInfo](#osaccountinfo)> | Promis对象,返回新创建的系统帐号的信息。 | +| Promise<[OsAccountInfo](#osaccountinfo)> | Promise对象,返回新创建的系统帐号的信息。 | **错误码:** @@ -2503,7 +2503,7 @@ getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; getBundleIdFromUid(uid: number): Promise<number>; -通过uid查询对应的bundleId,使用Promis异步回调。 +通过uid查询对应的bundleId,使用Promise异步回调。 **系统接口:** 此接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md index c5d033039f5bd94227577636efe84e62941edd59..27b1bfc3f827854304bb83ebe8cd7e643491d11e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -89,7 +89,7 @@ isEmpty(): boolean const plainArray = new PlainArray(); let result = plainArray.isEmpty(); try { - plainArray.isEmpty.bind({})(); + plainArray.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -132,7 +132,7 @@ plainArray.has(1); plainArray.add(1, "squirrel"); let result1 = plainArray.has(1); try { - plainArray.has.bind({}, 1)(); + plainArray.has.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -175,7 +175,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.get(1); try { - plainArray.get.bind({}, 1)(); + plainArray.get.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -218,7 +218,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfKey(2); try { - plainArray.getIndexOfKey.bind({}, 2)(); + plainArray.getIndexOfKey.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -261,7 +261,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfValue("squirrel"); try { - plainArray.getIndexOfValue.bind({}, "squirrel")(); + plainArray.getIndexOfValue.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -304,7 +304,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getKeyAt(1); try { - plainArray.getKeyAt.bind({}, 1)(); + plainArray.getKeyAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -347,7 +347,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getValueAt(1); try { - plainArray.getValueAt.bind({}, 1)(); + plainArray.getValueAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -388,7 +388,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let newPlainArray = plainArray.clone(); try { - plainArray.clone.bind({})(); + plainArray.clone.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -424,7 +424,7 @@ add(key: number, value: T): void let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); try { - plainArray.add.bind({}, "squirrel")(); + plainArray.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -465,10 +465,9 @@ remove(key: number): T let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); -plainArray.remove(2); let result = plainArray.remove(2); try { - plainArray.remove.bind({}, 2)(); + plainArray.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -509,10 +508,9 @@ removeAt(index: number): T let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); -plainArray.removeAt(1); let result = plainArray.removeAt(1); try { - plainArray.removeAt.bind({}, 1)(); + plainArray.removeAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -557,7 +555,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeRangeFrom(1, 3); try { - plainArray.removeRangeFrom.bind({}, 1, 3)(); + plainArray.removeRangeFrom.bind({}, 1, 3)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -601,7 +599,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.setValueAt(1, 3546); try { - plainArray.setValueAt.bind({}, 1, 3546)(); + plainArray.setValueAt.bind({}, 1, 3546)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -643,7 +641,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.toString(); try { - plainArray.toString.bind({})(); + plainArray.toString.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -674,7 +672,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.clear(); try { - plainArray.clear.bind({})(); + plainArray.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -723,7 +721,7 @@ plainArray.forEach((value, index) => { try { plainArray.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -774,7 +772,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - plainArray[Symbol.iterator].bind({})(); + plainArray[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-pointer.md b/zh-cn/application-dev/reference/apis/js-apis-pointer.md old mode 100644 new mode 100755 index 6a9c09f1a21e7d18e21643085d2023eabd21ef85..ca40808f6481390185bfb8882b3a447e6ed4cc61 --- a/zh-cn/application-dev/reference/apis/js-apis-pointer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-pointer.md @@ -1,6 +1,6 @@ # 鼠标指针 -鼠标指针管理模块,用于提供鼠标指针相关属性接口。 +鼠标指针管理模块,用于查询和设置鼠标指针相关属性。 > **说明**: > @@ -12,11 +12,11 @@ import pointer from '@ohos.multimodalInput.pointer'; ``` -## pointer.setPointerVisibele9+ +## pointer.setPointerVisible9+ setPointerVisible(visible: boolean, callback: AsyncCallback<void>): void -设置鼠标指针显示或者隐藏,使用callback异步回调。 +设置鼠标指针显示或者隐藏,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -24,18 +24,22 @@ setPointerVisible(visible: boolean, callback: AsyncCallback<void>): void | 参数 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------------------------- | -| visible | boolean | 是 | 鼠标指针显示或者隐藏状态,true: 鼠标指针显示; false: 鼠标指针隐藏。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当设置鼠标显示或隐藏成功,err为undefined,否则为错误对象。 | +| visible | boolean | 是 | 鼠标指针是否显示。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **示例**: ```js try { - pointer.setPointerVisible(true, (err, data) => { + 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 (err) { - console.log(`Set pointer visible failed. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -43,7 +47,7 @@ try { setPointerVisible(visible: boolean): Promise<void> -设置鼠标指针显示或者隐藏,使用Promise方式作为异步方法。 +设置鼠标指针显示或者隐藏,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -51,23 +55,23 @@ setPointerVisible(visible: boolean): Promise<void> | 参数 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | ---------------------------------------- | -| visible | boolean | 是 | 鼠标指针显示或者隐藏状态,true: 鼠标指针显示; false: 鼠标指针隐藏。 | +| visible | boolean | 是 | 鼠标指针是否显示。 | **返回值**: | 参数 | 说明 | | ------------------- | ------------------- | -| Promise<void> | Promise实例,用于异步获取结果。 | +| Promise<void> | Promise对象。 | **示例**: ```js try { - pointer.setPointerVisible(false).then(data => { - console.log(`Set mouse pointer visible success`); + pointer.setPointerVisible(false).then(() => { + console.log(`Set pointer visible success`); }); -} catch { - console.log(`Set mouse pointer visible failed err=${JSON.stringify(data)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -75,7 +79,7 @@ try { isPointerVisible(callback: AsyncCallback<boolean>): void -获取鼠标指针显示或隐藏状态,使用callback异步回调。 +获取鼠标指针显示或隐藏状态,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -83,17 +87,21 @@ isPointerVisible(callback: AsyncCallback<boolean>): void | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | -------------- | -| callback | AsyncCallback<boolean> | 是 | 回调函数,异步返回查询结果。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数,异步返回鼠标指针显示或隐藏状态。 | **示例**: ```js try { - pointer.isPointerVisible(visible, (err, data) => { - console.log(`The mouse pointer visible attributes is ` + visible); + 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 (err) { - console.log(`The mouse pointer visible attributes is failed. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -101,7 +109,7 @@ try { isPointerVisible(): Promise<boolean> -获取鼠标指针显示或隐藏状态,使用Promise方式作为异步方法。 +获取鼠标指针显示或隐藏状态,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -109,25 +117,21 @@ isPointerVisible(): Promise<boolean> | 参数 | 说明 | | ---------------------- | ------------------- | -| Promise<boolean> | Promise实例,用于异步获取结果。 | +| Promise<boolean> | Promise对象,异步返回鼠标指针显示或隐藏状态。 | **示例**: ```js -try { - pointer.isPointerVisible().then((data) => { - console.log(`The mouse pointer visible attributes is success. data=${JSON.stringify(data)}`); - }); -} catch (err) { - ponsole.info(`The mouse pointer visible attributes is failed. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); -} +pointer.isPointerVisible().then((visible) => { + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); +}); ``` ## pointer.setPointerSpeed9+ setPointerSpeed(speed: number, callback: AsyncCallback<void>): void -设置鼠标移动速度,使用callback异步回调。 +设置鼠标移动速度,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -135,18 +139,22 @@ setPointerSpeed(speed: number, callback: AsyncCallback<void>): void | 参数 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------- | -| speed | number | 是 | 鼠标移动速度设置挡位值1-11,最大值:11,最小值:1,标准值:5。 | -| callback | AysncCallback<void> | 是 | 回调函数。当设置鼠标速度成功,err为undefined,否则为错误对象。 | +| speed | number | 是 | 鼠标移动速度,范围1-11,默认为5。 | +| callback | AysncCallback<void> | 是 | 回调函数。 | **示例**: ```js try { - pointer.setPointerSpeed(5, (err, data) => { + 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 (err) { - console.log(`Set pointer speed failed. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -154,7 +162,7 @@ try { setPointerSpeed(speed: number): Promise<void> -设置鼠标移动速度,使用Promise异步回调。 +设置鼠标移动速度,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -162,23 +170,23 @@ setPointerSpeed(speed: number): Promise<void> | 参数 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------------------- | -| speed | number | 是 | 鼠标移动速度设置挡位值1-11,最大值:11,最小值:1,标准值:5。 | +| speed | number | 是 | 鼠标移动速度,范围1-11,默认为5。 | **返回值**: | 参数 | 说明 | | ------------------- | ---------------- | -| Promise<void> | 无返回结果的Promise对象。 | +| Promise<void> | Promise对象。 | **示例**: ```js try { - pointer.setPointerSpeed(5).then(data => { + pointer.setPointerSpeed(5).then(() => { console.log(`Set pointer speed success`); }); -} catch (err) { - console.log(`Set pointer speed failed err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -186,7 +194,7 @@ try { getPointerSpeed(callback: AsyncCallback<number>): void -获取当前鼠标移动速度,使用callback异步回调。 +获取鼠标移动速度,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -194,17 +202,21 @@ getPointerSpeed(callback: AsyncCallback<number>): void | 参数 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | -------------- | -| callback | AsyncCallback<number> | 是 | 回调函数,异步返回查询结果。 | +| callback | AsyncCallback<number> | 是 | 回调函数,异步返回鼠标移动速度。 | **示例**: ```js try { - pointer.getPointerSpeed(speed, (err, data) => { - console.log(`The pointer speed is ` + 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) { - console.log(`Failed to get the pointer speed. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -212,7 +224,7 @@ try { getPointerSpeed(): Promise<number> -获取当前鼠标移动速度,使用Promise异步回调。 +获取当前鼠标移动速度,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -220,17 +232,17 @@ getPointerSpeed(): Promise<number> | 参数 | 说明 | | --------------------- | ------------------- | -| Promise<number> | Promise实例,用于异步获取结果。 | +| Promise<number> | Promise实例,异步返回鼠标移动速度。 | **示例**: ```js try { - pointer.getPointerSpeed().then(data => { - console.log(`Get pointer speed success. data=${JSON.stringify(data)}`); + pointer.getPointerSpeed().then(speed => { + console.log(`Get pointer speed success, speed: ${JSON.stringify(speed)}`); }); -} catch (err) { - console.log(`Get pointer speed failed err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); +} catch (error) { + console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -238,7 +250,7 @@ try { getPointerStyle(windowId: number, callback: AsyncCallback<PointerStyle>): void -获取鼠标样式类型,使用callback异步回调。 +获取鼠标样式类型,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -246,29 +258,27 @@ getPointerStyle(windowId: number, callback: AsyncCallback<PointerStyle>): | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------- | -| windowId | number | 是 | 输入设备的窗口id。 | -| callback | AsyncCallback<[PointerStyle](#pointerstyle9)> | 是 | 回调函数,异步返回查询结果。 | +| windowId | number | 是 | 窗口id。 | +| callback | AsyncCallback<[PointerStyle](#pointerstyle9)> | 是 | 回调函数,异步返回鼠标样式类型。 | **示例**: ```js -// 获取设备的鼠标样式。 import window from '@ohos.window'; -var windowClass = null; -window.getTopWindow((err, data) => { - windowClass = data; - windowClass.getProperties((err, data) => { - var windowId = data.id; + +window.getTopWindow((error, win) => { + win.getProperties((error, properties) => { + var windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; } try { - pointer.getPointerStyle(windowId, (err, ret) => { - console.log(`The mouse pointer style is: ` + ret); + pointer.getPointerStyle(windowId, (error, style) => { + console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); }); - } catch (err) { - console.log(`Failed to get the pointer style. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); + } catch (error) { + console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } }); }); @@ -278,36 +288,40 @@ window.getTopWindow((err, data) => { getPointerStyle(windowId: number): Promise<PointerStyle> -获取鼠标样式类型,使用Promise方式作为异步方法。 +获取鼠标样式类型,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer **参数**: +| 参数 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -------- | +| windowId | number | 是 | 窗口id。 | + +**返回值**: + | 参数 | 说明 | | ---------------------------------------- | ------------------- | -| Promise<[PointerStyle](#pointerstyle9)> | Promise实例,用于异步获取结果。 | +| Promise<[PointerStyle](#pointerstyle9)> | Promise实例,异步返回鼠标样式类型。 | **示例**: ```js -// 获取设备的鼠标样式。 import window from '@ohos.window'; -var windowClass = null; -window.getTopWindow((err, data) => { - windowClass = data; - windowClass.getProperties((err, data) => { - var windowId = data.id; + +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((ret) => { - console.log(`The mouse pointer style is: ` + ret); + pointer.getPointerStyle(windowId).then((style) => { + console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); }); - } catch (err) { - console.log(`Get pointer style failed err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); + } catch (error) { + console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } }); }); @@ -317,7 +331,7 @@ window.getTopWindow((err, data) => { setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback<void>): void -设置鼠标的样式类型,使用callback异步回调。 +设置鼠标样式类型,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -325,30 +339,28 @@ setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCal | 参数 | 类型 | 必填 | 说明 | | ------------ | ------------------------------ | ---- | ----------------------------------- | -| windowId | number | 是 | 输入设备的窗口id。 | +| windowId | number | 是 | 窗口id。 | | pointerStyle | [PointerStyle](#pointerstyle9) | 是 | 鼠标样式id。 | -| callback | AysncCallback<void> | 是 | 回调函数。当设置样式成功,err为undefined,否则为错误对象。 | +| callback | AysncCallback<void> | 是 | 回调函数。 | **示例**: ```js -// 设置设备的鼠标样式。 import window from '@ohos.window'; -var windowClass = null; -window.getTopWindow((err, data) => { - windowClass = data; - windowClass.getProperties((err, data) => { - var windowId = data.id; + +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, (err) => { - console.log(`Successfully set mouse pointer style`); + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { + console.log(`Set pointer style success`); }); - } catch (err) { - console.log(`Failed to set the pointer style. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } }); }); @@ -357,7 +369,7 @@ window.getTopWindow((err, data) => { setPointerStyle(windowId: number, pointerStyle: PointerStyle): Promise<void> -设置鼠标的样式类型,使用Promise方式作为异步方法。 +设置鼠标样式类型,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -365,37 +377,35 @@ setPointerStyle(windowId: number, pointerStyle: PointerStyle): Promise<void&g | 参数 | 类型 | 必填 | 说明 | | ------------------- | ------------------------------ | ---- | ---------------- | -| windowId | number | 是 | 输入设备的窗口id。 | +| windowId | number | 是 | 窗口id。 | | pointerStyle | [PointerStyle](#pointerstyle9) | 是 | 鼠标样式id。 | -| Promise<void> | void | 是 | 无返回结果的Promise对象。 | +| Promise<void> | void | 是 | Promise对象。 | **示例**: ```js -// 设置设备的鼠标样式。 import window from '@ohos.window'; -var windowClass = null; -window.getTopWindow((err, data) => { - windowClass = data; - windowClass.getProperties((err, data) => { - var windowId = data.id; + +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(`Successfully set mouse pointer style`); + console.log(`Set pointer style success`); }); - } catch (err) { - console.log(`Failed to set the pointer style. err=${JSON.stringify(err)}, msg=${JSON.stringify(message)}`); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } }); }); ``` ## PointerStyle9+ -定义鼠标样式类型。 +鼠标样式类型。 **系统能力**:SystemCapability.MultimodalInput.Input.Pointer @@ -439,6 +449,4 @@ window.getTopWindow((err, data) => { | MIDDLE_BTN_NORTH_WEST | 35 | 向西北滚动 | | MIDDLE_BTN_SOUTH_EAST | 36 | 向东南滚动 | | MIDDLE_BTN_SOUTH_WEST | 37 | 向西南滚动 | -| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | 四向锥形移动 | - - +| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | 四向锥形移动 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md b/zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md index f931e52919a385cacbdd346d27b647868d1b8844..ed34599c56076fe9e3477ccb66c528da3191219e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,19 +1,21 @@ # ProcessRunningInfo(deprecated) -ProcessRunningInfo模块提供对进程运行信息进行设置和查询的能力。 +本模块提供对进程运行信息进行设置和查询的能力。 > **说明:** -> - 本模块接口从API Version 9 开始废弃,建议使用[ProcessRunningInformation9+](js-apis-processrunninginformation.md)替代。 +> - 本模块接口从API version 9 开始废弃,建议使用[ProcessRunningInformation9+](js-apis-processrunninginformation.md)替代。 > - 本模块首批接口从API version 8 开始支持。 ## 使用说明 -通过appManager来获取。 +通过appManager中[getProcessRunningInfos](js-apis-appmanager.md#appmanagergetprocessrunninginfosdeprecated)方法来获取。 ```js import appManager from '@ohos.application.appManager'; -appManager.getProcessRunningInfos((error,data) => { - console.log("getProcessRunningInfos error: " + error.code + " data: " + JSON.stringify(data)); +app.getProcessRunningInfos().then((data) => { + console.log('success:' + JSON.stringify(data)); +}).catch((error) => { + console.log('failed:' + JSON.stringify(error)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-queue.md b/zh-cn/application-dev/reference/apis/js-apis-queue.md index d75d29a0b02e20d194bc3582d4bf32376f0cc32f..e6d713fce36bd5c91e0dd42e087f292a37392890 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-queue.md +++ b/zh-cn/application-dev/reference/apis/js-apis-queue.md @@ -92,13 +92,12 @@ add(element: T): boolean let queue = new Queue(); let result = queue.add("a"); let result1 = queue.add(1); -queue.add(1); let b = [1, 2, 3]; -queue.add(b); +let result2 = queue.add(b); let c = {name : "Dylon", age : "13"}; let result3 = queue.add(c); try { - queue.add.bind({}, "b")(); + queue.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -137,7 +136,7 @@ queue.add(2); queue.add(4); let result = queue.pop(); try { - queue.pop.bind({})(); + queue.pop.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -175,7 +174,7 @@ queue.add(5); queue.add(2); let result = queue.getFirst(); try { - queue.getFirst.bind({})(); + queue.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -227,7 +226,7 @@ queue.forEach((value, index) => { try { queue.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -276,7 +275,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - queue[Symbol.iterator].bind({})(); + queue[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md index 22f367d73a8c447c0123ae2600d6f52892b45c4e..4aa51affe53c246dcfb3eaf8795247633c50bb01 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -608,9 +608,9 @@ try { | actionButton | [ActionButton](#actionbutton) | 否 | 弹出的提醒通知栏中显示的按钮(参数可选,支持0/1/2个按钮)。 | | wantAgent | [WantAgent](#wantagent) | 否 | 点击通知后需要跳转的目标ability信息。 | | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | 否 | 提醒到达时跳转的目标包。如果设备正在使用中,则弹出一个通知框。 | -| ringDuration | number | 否 | 指明响铃时长。 | +| ringDuration | number | 否 | 指明响铃时长(单位:秒)。 | | snoozeTimes | number | 否 | 指明延迟提醒次数。 | -| timeInterval | number | 否 | 执行延迟提醒间隔。 | +| timeInterval | number | 否 | 执行延迟提醒间隔(单位:秒)。 | | title | string | 否 | 指明提醒标题。 | | content | string | 否 | 指明提醒内容。 | | expiredContent | string | 否 | 指明提醒过期后需要显示的内容。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index b1ad40aa1b6748ad6a11598526aae234055b3a09..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 @@ -1,6 +1,6 @@ # 资源管理 -资源管理模块,根据当前configuration(语言,区域,横竖屏,mccmnc)和device capability(设备类型,分辨率)提供获取应用资源信息读取接口。 +资源管理模块,根据当前configuration:语言、区域、横竖屏、Mcc(移动国家码)和Mnc(移动网络码)、Device capability(设备类型)、Density(分辨率)提供获取应用资源信息读取接口。 > **说明:** > @@ -16,9 +16,16 @@ import resourceManager from '@ohos.resourceManager'; ## 使用说明 从API Version9开始,Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包,此方式FA模型不适用。 +Stage模型下Context的引用方法请参考[Stage模型的Context详细介绍](../../ability/context-userguide.md) ```ts -this.context.resourceManager; +import Ability from '@ohos.application.Ability'; +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + let context = this.context; + let resourceManager = context.resourceManager; + } +} ``` ## resourceManager.getResourceManager @@ -1277,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)。 @@ -1318,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-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index 510bac63015e8793b7b34199403cea444db4f6fe..f13771a442e172f3e02488017033fb8876859590 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -604,7 +604,7 @@ router.getParams(); | 名称 | 描述 | | -------- | ---------------------------------------- | -| Standard | 标准模式。 | +| Standard | 标准模式。
目标页面会被添加到页面路由栈顶,无论栈中是否存在相同url的页面。 | | Single | 单实例模式。
如果目标页面的url在页面栈中已经存在同url页面,离栈顶最近的页面会被移动到栈顶,移动后的页面为新建页。
如目标页面的url在页面栈中不存在同url页面,按标准模式跳转。 | ## 完整示例 diff --git a/zh-cn/application-dev/reference/apis/js-apis-rpc.md b/zh-cn/application-dev/reference/apis/js-apis-rpc.md index 4ca8bd896c8e0bb40346a6b62d7fa98caf2128de..61a2f32b4c1f8a3f71447572ae5307137d13ab3b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-rpc.md +++ b/zh-cn/application-dev/reference/apis/js-apis-rpc.md @@ -3307,7 +3307,7 @@ readInterfaceToken(): string ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let interfaceToken = data.readInterfaceToken(); console.log("RpcServer: interfaceToken is " + interfaceToken); return true; @@ -3438,7 +3438,7 @@ getWritableBytes(): number ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let getWritableBytes = data.getWritableBytes(); console.log("RpcServer: getWritableBytes is " + getWritableBytes); return true; @@ -7130,7 +7130,7 @@ static getCallingPid(): number ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerPid = rpc.IPCSkeleton.getCallingPid(); console.log("RpcServer: getCallingPid result: " + callerPid); return true; @@ -7157,7 +7157,7 @@ static getCallingUid(): number ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerUid = rpc.IPCSkeleton.getCallingUid(); console.log("RpcServer: getCallingUid result: " + callerUid); return true; @@ -7185,7 +7185,7 @@ static getCallingTokenId(): number; ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); console.log("RpcServer: getCallingTokenId result: " + callerTokenId); return true; @@ -7212,7 +7212,7 @@ static getCallingDeviceID(): string ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID(); console.log("RpcServer: callerDeviceID is: " + callerDeviceID); return true; @@ -7239,7 +7239,7 @@ static getLocalDeviceID(): string ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID(); console.log("RpcServer: localDeviceID is: " + localDeviceID); return true; @@ -7266,7 +7266,7 @@ static isLocalCalling(): boolean ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let isLocalCalling = rpc.IPCSkeleton.isLocalCalling(); console.log("RpcServer: isLocalCalling is: " + isLocalCalling); return true; @@ -7385,7 +7385,7 @@ static resetCallingIdentity(): string ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); console.log("RpcServer: callingIdentity is: " + callingIdentity); return true; @@ -7412,7 +7412,7 @@ static restoreCallingIdentity(identity : string): void ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = null; try { callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); @@ -7452,7 +7452,7 @@ static setCallingIdentity(identity : string): boolean ``` class Stub extends rpc.RemoteObject { - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = null; try { callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); @@ -7818,7 +7818,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me ### onRemoteRequest8+(deprecated) ->从API version 9 开始不再维护,建议使用[onRemoteRequestEx](#onremoterequestex9)类替代。 +>从API version 9 开始不再维护,建议使用[onRemoteMessageRequest](#onremotemessagerequest9)类替代。 onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean @@ -7874,14 +7874,14 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里处理 } ``` -### onRemoteRequestEx9+ +### onRemoteMessageRequest9+ -onRemoteRequestEx(code : number, data : MessageSequence, reply: MessageSequence, options : MessageOption): boolean | Promise\ +onRemoteMessageRequest(code : number, data : MessageSequence, reply: MessageSequence, options : MessageOption): boolean | Promise\ > **说明:** > ->* 开发者应优先选择重载onRemoteRequestEx方法,其中可以自由实现同步和异步的消息处理。 ->* 开发者同时重载onRemoteRequest和onRemoteRequestEx方法时,仅onRemoteRequestEx方法生效。 +>* 开发者应优先选择重载onRemoteMessageRequest方法,其中可以自由实现同步和异步的消息处理。 +>* 开发者同时重载onRemoteRequest和onRemoteMessageRequest方法时,仅onRemoteMessageRequest方法生效。 sendMessageRequest请求的响应处理函数,服务端在该函数里同步或异步地处理请求,回复结果。 @@ -7900,10 +7900,10 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 | 类型 | 说明 | | ----------------- | ---------------------------------------------------------------------------------------------- | - | boolean | 若在onRemoteRequestEx中同步地处理请求,则返回一个布尔值:操作成功,则返回true;否则返回false。 | - | Promise\ | 若在onRemoteRequestEx中异步地处理请求,则返回一个Promise对象。 | + | boolean | 若在onRemoteMessageRequest中同步地处理请求,则返回一个布尔值:操作成功,则返回true;否则返回false。 | + | Promise\ | 若在onRemoteMessageRequest中异步地处理请求,则返回一个Promise对象。 | -**重载onRemoteRequestEx方法同步处理请求示例:** +**重载onRemoteMessageRequest方法同步处理请求示例:** ```ets class MyDeathRecipient { @@ -7920,9 +7920,9 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 isObjectDead(): boolean { return false; } - onRemoteRequestEx(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteMessageRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); @@ -7932,7 +7932,7 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 } ``` - **重载onRemoteRequestEx方法异步处理请求示例:** + **重载onRemoteMessageRequest方法异步处理请求示例:** ```ets class MyDeathRecipient { @@ -7949,9 +7949,9 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 isObjectDead(): boolean { return false; } - async onRemoteRequestEx(code, data, reply, option) { + async onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; @@ -7964,7 +7964,7 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 } ``` -**同时重载onRemoteRequestEx和onRemoteRequest方法同步处理请求示例:** +**同时重载onRemoteMessageRequest和onRemoteRequest方法同步处理请求示例:** ```ets class MyDeathRecipient { @@ -7983,17 +7983,17 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 } onRemoteRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteMessageRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); return false; } } - // 同时调用仅会执行onRemoteRequestEx - onRemoteRequestEx(code, data, reply, option) { + // 同时调用仅会执行onRemoteMessageRequest + onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; @@ -8004,7 +8004,7 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 } ``` - **同时重载onRemoteRequestEx和onRemoteRequest方法异步处理请求示例:** + **同时重载onRemoteMessageRequest和onRemoteRequest方法异步处理请求示例:** ```ets class MyDeathRecipient { @@ -8030,10 +8030,10 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 return false; } } - // 同时调用仅会执行onRemoteRequestEx - async onRemoteRequestEx(code, data, reply, option) { + // 同时调用仅会执行onRemoteMessageRequest + async onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index de9ec2ae2b856bbf0f36bb7a98e41d90f0f584b1..c95391469e678dfb6822b15a12d4242c426d358f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -1,15 +1,6 @@ # 传感器 -sensor模块提供订阅传感器数据基本能力,包括订阅、取消订阅传感器数据,获取传感器列表,以及通用的传感器算法接口如通过气压值计算海拔高度、通过旋转矩阵计算设备方向等。 - -传感器是指用于侦测环境中所发生事件或变化,并将此消息发送至其他电子设备(如中央处理器)的设备,通常由敏感组件和转换组件组成。传感器是实现物联网智能化的重要基石,为实现全场景智慧化战略,支撑“1+8+N”产品需求,需要构筑统一的传感器管理框架,达到为各产品/业务提供低时延、低功耗的感知数据的目的。根据用途可分为以下六大类: - -- 运动类:加速度、陀螺仪、重力、线性加速度传感器等 -- 姿态类:旋转矢量、方向传感器等 -- 环境类:磁力计、气压、湿度传感器等 -- 光线类:环境光、接近光、色温传感器等 -- 健康类:心率、心跳传感器等 -- 其它:霍尔传感器、手握传感器等 +sensor模块提供了获取传感器数据的能力,包括获取传感器属性列表,订阅传感器数据,以及一些通用的传感器算法。 > **说明:** > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -27,9 +18,9 @@ import sensor from '@ohos.sensor'; on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void -订阅加速度计传感器数据。 +订阅加速度传感器数据。 -**需要权限**:ohos.permission.ACCELEROMETER +**需要权限**:ohos.permission.ACCELEROMETER **系统能力**:SystemCapability.Sensors.Sensor @@ -37,9 +28,9 @@ on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的加速度传感器类型为 ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -53,13 +44,13 @@ on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse> ```js try { - sensor.on(sensor.SensorId.ACCELEROMETER,function(data){ + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -67,7 +58,7 @@ try { on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>,options?: Options): void -订阅未校准的加速度计传感器数据。 +订阅未校准加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -77,9 +68,9 @@ on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Acceleromete | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的未校准加速度传感器类型为ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerUncalibratedResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -93,16 +84,16 @@ on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Acceleromete ```js try { - sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED,function(data){ + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -118,9 +109,9 @@ on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, option | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | -| type | [SensorId](#sensorid9) | 是 | 要订阅的环境光传感器类型为AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LightResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -134,11 +125,11 @@ on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, option ```js try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT,function(data){ - console.info('Illumination: ' + data.intensity); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, function (data) { + console.info('The ambient light intensity: ' + data.intensity); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -146,7 +137,7 @@ try { on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>,options?: Options): void -订阅环境温度传感器数据。 +订阅温度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -154,9 +145,9 @@ on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的环境温度传感器类型为AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AmbientTemperatureResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -170,11 +161,11 @@ on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureR ```js try { - sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE,function(data){ - console.info('Temperature: ' + data.temperature); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { + console.info('Temperature: ' + data.temperature); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -190,9 +181,9 @@ on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, option | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的气压计传感器类型为BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为BarometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -206,11 +197,11 @@ on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, option ```js try { - sensor.on(sensor.SensorId.BAROMETER,function(data){ - console.info('Atmospheric pressure: ' + data.pressure); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.BAROMETER, function (data) { + console.info('Atmospheric pressure: ' + data.pressure); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -226,9 +217,9 @@ on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: O | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | -| type | [SensorId](#sensorid9) | 是 | 要订阅的重力传感器类型为GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GravityResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -242,13 +233,13 @@ on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: O ```js try { - sensor.on(sensor.SensorId.GRAVITY,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GRAVITY, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -266,9 +257,9 @@ on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的陀螺仪传感器类型为GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 返回注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -282,13 +273,13 @@ on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options ```js try { - sensor.on(sensor.SensorId.GYROSCOPE,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -297,7 +288,7 @@ try { on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>, options?: Options): void -订阅未经校准的陀螺仪传感器数据 +订阅未校准陀螺仪传感器数据 **需要权限**:ohos.permission.GYROSCOPE @@ -307,9 +298,9 @@ on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalib | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的未校准陀螺仪传感器类型为GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeUncalibratedResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -323,16 +314,16 @@ on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalib ```js try { - sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -348,9 +339,9 @@ on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Option | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的霍尔传感器类型为HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HallResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -364,11 +355,11 @@ on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Option ```js try { - sensor.on(sensor.SensorId.HALL,function(data){ - console.info('Status: ' + data.status); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HALL, function (data) { + console.info('Hall status: ' + data.status); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -386,9 +377,9 @@ on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,option | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的心率传感器类型为HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HeartRateResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -402,11 +393,11 @@ on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,option ```js try { - sensor.on(sensor.SensorId.HEART_RATE,function(data){ + sensor.on(sensor.SensorId.HEART_RATE, function (data) { console.info('Heart rate: ' + data.heartRate); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -422,9 +413,9 @@ on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的湿度传感器类型为HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HumidityResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -438,11 +429,11 @@ on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: ```js try { - sensor.on(sensor.SensorId.HUMIDITY,function(data){ - console.info('Humidity: ' + data.humidity); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HUMIDITY, function (data) { + console.info('Humidity: ' + data.humidity); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -461,9 +452,9 @@ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAcceleromete | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的线性加速度传感器类型为LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELEROMETER。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LinearAccelerometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -477,13 +468,13 @@ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAcceleromete ```js try { - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -491,7 +482,7 @@ try { on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void -订阅磁场传感器数据。 +订阅地磁传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -499,9 +490,9 @@ on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的磁场传感器类型为MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -515,13 +506,13 @@ on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse> ```js try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -529,7 +520,7 @@ try { on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void -订阅未校准的磁场传感器数据 +订阅未校准地磁传感器数据 **系统能力**:SystemCapability.Sensors.Sensor @@ -537,9 +528,9 @@ on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFie | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的未校准磁场传感器类型为MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldUncalibratedResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -553,16 +544,16 @@ on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFie ```js try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -570,7 +561,7 @@ try { on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,options?: Options): void -订阅定向传感器数据。 +订阅方向传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -586,21 +577,21 @@ on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,opt | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的方向传感器类型为ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 回调函数,异步上报的传感器数据固定为OrientationResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **示例:** ```js try { - sensor.on(sensor.SensorId.ORIENTATION,function(data){ - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ORIENTATION, function (data) { + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -626,19 +617,19 @@ on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, option | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的计步传感器类型为PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **示例:** ```js try { - sensor.on(sensor.SensorId.PEDOMETER,function(data){ - console.info('Steps: ' + data.steps); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER, function (data) { + console.info('Step count: ' + data.steps); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -647,7 +638,7 @@ try { on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void -订阅计步器检测传感器数据。 +订阅计步检测器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -657,9 +648,9 @@ on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的计步检测传感器类型为PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerDetectionResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -673,11 +664,11 @@ on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionR ```js try { - sensor.on(sensor.SensorId.PEDOMETER_DETECTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, function (data) { + console.info('Pedometer scalar: ' + data.scalar); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -685,7 +676,7 @@ try { on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, options?: Options): void -订阅接近传感器数据。 +订阅接近光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -693,9 +684,9 @@ on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, option | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的接近光传感器类型为PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为ProximityResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -709,11 +700,11 @@ on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, option ```js try { - sensor.on(sensor.SensorId.PROXIMITY,function(data){ - console.info('Distance: ' + data.distance); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PROXIMITY, function (data) { + console.info('Distance: ' + data.distance); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -730,9 +721,9 @@ on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的旋转矢量传感器类型为ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 回调函数,异步上报的传感器数据固定为RotationVectorResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -746,14 +737,14 @@ on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse& ```js try { - sensor.on(sensor.SensorId.ROTATION_VECTOR,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ROTATION_VECTOR, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -762,7 +753,7 @@ try { on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void -订阅重要的运动传感器数据。 +订阅大幅动作检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -770,9 +761,9 @@ on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionRes | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的大幅动作传感器类型为SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为SignificantMotionResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -786,11 +777,11 @@ on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionRes ```js try { - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { + console.info('Scalar data: ' + data.scalar); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -807,9 +798,9 @@ on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的佩戴检测传感器类型为WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为WearDetectionResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -823,11 +814,11 @@ on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse> ```js try { - sensor.on(sensor.SensorId.WEAR_DETECTION,function(data){ - console.info('Wear status: ' + data.value); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.WEAR_DETECTION, function (data) { + console.info('Wear status: ' + data.value); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -837,7 +828,7 @@ try { once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>): void -订阅一次加速度计传感器数据。 +获取一次加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -847,8 +838,8 @@ once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 加速度传感器类型为ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册一次加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerResponse。 | **错误码**: @@ -862,14 +853,13 @@ once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse&g ```js try { - sensor.once(sensor.SensorId.ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -877,7 +867,7 @@ try { once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): void -订阅一次未校准的加速度计传感器数据。 +获取一次未校准加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -887,8 +877,8 @@ once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Accelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 未校准加速度传感器类型为ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册一次未校准加速度传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerUncalibratedResponse。 | **错误码**: @@ -902,17 +892,16 @@ once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Accelerome ```js try { - sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -920,7 +909,7 @@ try { once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): void -订阅环境光传感器数据一次。 +获取一次环境光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -928,8 +917,8 @@ once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 环境光传感器类型为AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册一次环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LightResponse。 | **错误码**: @@ -943,12 +932,11 @@ once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): voi ```js try { - sensor.once(sensor.SensorId.AMBIENT_LIGHT, function(data) { - console.info('Illumination: ' + data.intensity); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.AMBIENT_LIGHT, function (data) { + console.info('The ambient light intensity: ' + data.intensity); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -956,7 +944,7 @@ try { once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>): void -一次订阅环境温度传感器数据。 +获取一次温度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -964,8 +952,8 @@ once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatur | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 环境温度传感器类型为AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册一次环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AmbientTemperatureResponse。 | **错误码**: @@ -979,12 +967,11 @@ once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatur ```js try { - sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function(data) { - console.info('Temperature: ' + data.temperature); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { + console.info('Temperature: ' + data.temperature); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -992,7 +979,7 @@ try { once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): void -订阅一次气压计传感器数据。 +获取一次气压计传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1000,8 +987,8 @@ once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 气压计传感器类型为BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册一次气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为BarometerResponse。 | **错误码**: @@ -1015,12 +1002,11 @@ once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): voi ```js try { - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function (data) { + console.info('Atmospheric pressure: ' + data.pressure); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1028,7 +1014,7 @@ try { once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void -订阅一次重力传感器数据。 +获取一次重力传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1036,8 +1022,8 @@ once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 重力传感器类型为GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册一次重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GravityResponse。 | **错误码**: @@ -1051,14 +1037,13 @@ once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void ```js try { - sensor.once(sensor.SensorId.GRAVITY, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GRAVITY, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1066,7 +1051,7 @@ try { once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): void -订阅一次陀螺仪传感器数据。 +获取一次陀螺仪传感器数据。 **需要权限**:ohos.permission.GYROSCOPE @@ -1076,8 +1061,8 @@ once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 陀螺仪传感器类型为GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册一次陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeResponse。 | **错误码**: @@ -1091,14 +1076,13 @@ once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): voi ```js try { - sensor.once(sensor.SensorId.GYROSCOPE, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GYROSCOPE, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1106,7 +1090,7 @@ try { once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>): void -一次订阅未校准的陀螺仪传感器数据。 +获取一次未校准陀螺仪传感器数据。 **需要权限**:ohos.permission.GYROSCOPE @@ -1116,8 +1100,8 @@ once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncal | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 未校准陀螺仪传感器类型为GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册一次未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeUncalibratedResponse。 | **错误码**: @@ -1131,17 +1115,16 @@ once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncal ```js try { - sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function(data) { + sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1149,7 +1132,7 @@ try { once(type: SensorId.HALL, callback: Callback<HallResponse>): void -订阅一次霍尔传感器数据。 +获取霍尔传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1157,8 +1140,8 @@ once(type: SensorId.HALL, callback: Callback<HallResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 霍尔传感器类型为HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册一次霍尔传感器的回调函数,上报的数据类型为HallResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HallResponse。 | **错误码**: @@ -1172,12 +1155,11 @@ once(type: SensorId.HALL, callback: Callback<HallResponse>): void ```js try { - sensor.once(sensor.SensorId.HALL, function(data) { + sensor.once(sensor.SensorId.HALL, function (data) { console.info('Status: ' + data.status); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1185,7 +1167,7 @@ try { once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): void -订阅一次心率传感器数据。 +获取一次心率传感器数据。 **需要权限**:ohos.permission.READ_HEALTH_DATA @@ -1195,8 +1177,8 @@ once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): vo | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 心率传感器类型为HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HeartRateResponse。 | **错误码**: @@ -1210,12 +1192,11 @@ once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): vo ```js try { - sensor.once(sensor.SensorId.HEART_BEAT_RATE, function(data) { + sensor.once(sensor.SensorId.HEART_BEAT_RATE, function (data) { console.info('Heart rate: ' + data.heartRate); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1223,7 +1204,7 @@ try { once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void -订阅一次湿度传感器数据。 +获取一次湿度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1231,8 +1212,8 @@ once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 湿度传感器类型为HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册一次湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HumidityResponse。 | **错误码**: @@ -1246,12 +1227,11 @@ once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void ```js try { - sensor.once(sensor.SensorId.HUMIDITY, function(data) { + sensor.once(sensor.SensorId.HUMIDITY, function (data) { console.info('Humidity: ' + data.humidity); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1259,7 +1239,7 @@ try { once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void -订阅一次线性加速度传感器数据。 +获取一次线性加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -1269,8 +1249,8 @@ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 线性加速度传感器类型为LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册一次线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELEROMETER。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LinearAccelerometerResponse。 | **错误码**: @@ -1284,14 +1264,13 @@ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerome ```js try { - sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1299,7 +1278,7 @@ try { once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void -订阅一次磁场传感器数据。 +获取一次磁场传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1307,8 +1286,8 @@ once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 磁场传感器类型为MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册一次磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldResponse。 | **错误码**: @@ -1322,14 +1301,13 @@ once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse& ```js try { - sensor.once(sensor.SensorId.MAGNETIC_FIELD, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.MAGNETIC_FIELD, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1337,7 +1315,7 @@ try { once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>): void -订阅一次未经校准的磁场传感器数据。 +获取一次未经校准的磁场传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1345,8 +1323,8 @@ once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticF | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 未校准磁场传感器类型为MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册一次未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldUncalibratedResponse。 | **错误码**: @@ -1360,17 +1338,16 @@ once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticF ```js try { - sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function(data) { + sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1378,7 +1355,7 @@ try { once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): void -订阅一次定向传感器数据。 +获取一次方向传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1386,8 +1363,8 @@ once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 方向传感器类型为ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册一次方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 回调函数,异步上报的传感器数据固定为OrientationResponse。 | **错误码**: @@ -1401,14 +1378,13 @@ once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): ```js try { - sensor.once(sensor.SensorId.ORIENTATION, function(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ORIENTATION, function (data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1416,7 +1392,7 @@ try { once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): void -订阅一次计步器传感器数据。 +获取一次计步器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -1426,8 +1402,8 @@ once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 计步传感器类型为PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册一次计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerResponse。 | **错误码**: @@ -1441,20 +1417,18 @@ once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): voi ```js try { - sensor.once(sensor.SensorId.PEDOMETER, function(data) { - console.info('Steps: ' + data.steps); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PEDOMETER, function (data) { + console.info('Step count: ' + data.steps); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` ### PEDOMETER_DETECTION9+ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>): void - -订阅一次计步器检测传感器数据。 +获取一次计步检测器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -1464,8 +1438,8 @@ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectio | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 计步检测传感器类型为PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册一次计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerDetectionResponse。 | **错误码**: @@ -1479,12 +1453,11 @@ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectio ```js try { - sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function(data) { + sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function (data) { console.info('Scalar data: ' + data.scalar); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1492,7 +1465,7 @@ try { once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): void -订阅一次接近传感器数据。 +获取一次接近光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1500,8 +1473,8 @@ once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 接近光传感器类型为PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册一次接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为ProximityResponse。 | **错误码**: @@ -1515,12 +1488,11 @@ once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): voi ```js try { - sensor.once(sensor.SensorId.PROXIMITY, function(data) { - console.info('Distance: ' + data.distance); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PROXIMITY, function (data) { + console.info('Distance: ' + data.distance); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1528,7 +1500,7 @@ try { once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void -订阅一次旋转矢量传感器数据。 +获取一次旋转矢量传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1536,8 +1508,8 @@ once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorRespons | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 旋转矢量传感器类型为ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册一次旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 回调函数,异步上报的传感器数据固定为RotationVectorResponse。 | **错误码**: @@ -1551,15 +1523,14 @@ once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorRespons ```js try { - sensor.once(sensor.SensorId.ROTATION_VECTOR, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ROTATION_VECTOR, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1567,7 +1538,7 @@ try { once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>): void -订阅一次重要的运动传感器数据。 +获取一次大幅动作检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1575,8 +1546,8 @@ once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 有效运动传感器类型为SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册一次有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为SignificantMotionResponse。 | **错误码**: @@ -1590,12 +1561,11 @@ once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionR ```js try { - sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { + console.info('Scalar data: ' + data.scalar); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1603,7 +1573,7 @@ try { once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void -订阅一次佩戴检测传感器数据。 +获取一次佩戴检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1611,8 +1581,8 @@ once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 佩戴检测传感器类型为WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册一次穿戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为WearDetectionResponse。 | **错误码**: @@ -1626,12 +1596,11 @@ once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse& ```js try { - sensor.once(sensor.SensorId.WEAR_DETECTION, function(data) { - console.info("Wear status: "+ data.value); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.WEAR_DETECTION, function (data) { + console.info("Wear status: " + data.value); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1641,7 +1610,7 @@ try { off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void -取消订阅加速度计传感器数据。 +取消订阅加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -1651,21 +1620,27 @@ off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的加速度传感器类型为ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 取消注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 否 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('x-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.ACCELEROMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER, callback1); + sensor.on(sensor.SensorId.ACCELEROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ACCELEROMETER, callback1); + // 取消SensorId.ACCELEROMETER类型的所有回调 + sensor.off(sensor.SensorId.ACCELEROMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1673,7 +1648,7 @@ try { off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void -取消订阅未校准的加速度计传感器数据。 +取消订阅未校准加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -1683,24 +1658,27 @@ off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<Accelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的未校准加速度计传感器类型为ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 取消注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); + // 取消注册SensorId.ACCELEROMETER_UNCALIBRATED类型的所有回调 + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1716,27 +1694,35 @@ off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的环境光传感器类型为AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 取消注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js -try { - function callback(data) { - console.info('Illumination: ' + data.intensity); - } - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); } +try { + sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback1); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback1); + // 取消注册SensorId.AMBIENT_LIGHT的所有回调 + sensor.off(sensor.SensorId.AMBIENT_LIGHT); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +}V ``` ### AMBIENT_TEMPERATURE9+ off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void -取消订阅环境温度传感器数据。 +取消订阅温度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1744,19 +1730,27 @@ off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatur | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的环境温度传感器类型为AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 取消注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Temperature: ' + data.temperature); - } - sensor.off( sensor.SensorId.AMBIENT_TEMPERATURE, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); + // 取消注册SensorId.AMBIENT_TEMPERATURE的所有回调 + sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1772,19 +1766,27 @@ off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的气压计传感器类型为BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 取消注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - sensor.off(sensor.SensorId.BAROMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.BAROMETER, callback1); + sensor.on(sensor.SensorId.BAROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.BAROMETER, callback1); + // 取消注册SensorId.BAROMETER的所有回调 + sensor.off(sensor.SensorId.BAROMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1800,21 +1802,27 @@ off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的重力传感器类型为GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 取消注册注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off( sensor.SensorId.GRAVITY, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GRAVITY, callback1); + sensor.on(sensor.SensorId.GRAVITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GRAVITY, callback1); + // 取消注册SensorId.GRAVITY的所有回调 + sensor.off(sensor.SensorId.GRAVITY); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1832,21 +1840,27 @@ off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的陀螺仪传感器类型为GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 取消注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.GYROSCOPE, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE, callback1); + sensor.on(sensor.SensorId.GYROSCOPE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GYROSCOPE, callback1); + // 取消注册SensorId.GYROSCOPE的所有回调 + sensor.off(sensor.SensorId.GYROSCOPE); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1854,7 +1868,7 @@ try { off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void - 取消订阅未校准的陀螺仪传感器数据。 + 取消订阅未校准陀螺仪传感器数据。 **需要权限**:ohos.permission.GYROSCOPE @@ -1864,21 +1878,27 @@ off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncal | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的未校准陀螺仪传感器类型为GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 取消注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); + // 取消注册SensorId.GYROSCOPE_UNCALIBRATED的所有回调 + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1894,19 +1914,27 @@ off(type: SensorId.HALL, callback?: Callback<HallResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的霍尔传感器类型为HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 取消注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Status: ' + data.status); - } - sensor.off(sensor.SensorId.HALL, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HALL, callback1); + sensor.on(sensor.SensorId.HALL, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HALL, callback1); + // 取消注册SensorId.HALL的所有回调 + sensor.off(sensor.SensorId.HALL); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1924,19 +1952,27 @@ off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): vo | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的心率传感器类型为HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 取消注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info("Heart rate: " + data.heartRate); - } - sensor.off(sensor.SensorId.HEART_RATE, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HEART_RATE, callback1); + sensor.on(sensor.SensorId.HEART_RATE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HEART_RATE, callback1); + // 取消注册SensorId.HEART_RATE的所有回调 + sensor.off(sensor.SensorId.HEART_RATE); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1952,19 +1988,27 @@ off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的湿度传感器类型为HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 取消注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Humidity: ' + data.humidity); - } - sensor.off(sensor.SensorId.HUMIDITY, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HUMIDITY, callback1); + sensor.on(sensor.SensorId.HUMIDITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HUMIDITY, callback1); + // 取消注册SensorId.HUMIDITY的所有回调 + sensor.off(sensor.SensorId.HUMIDITY); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1982,21 +2026,27 @@ off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的线性加速度传感器类型为LINEAR_ACCELERATION。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 取消注册性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELERATION。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); + // 取消注册SensorId.LINEAR_ACCELEROMETER的所有回调 + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2012,21 +2062,27 @@ off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的磁场传感器类型为MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 取消注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback1); + // 取消注册SensorId.MAGNETIC_FIELD的所有回调 + sensor.off(sensor.SensorId.MAGNETIC_FIELD); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2042,24 +2098,27 @@ off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticF | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的未校准磁场传感器类型为MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 取消注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + // 取消注册SensorId.MAGNETIC_FIELD_UNCALIBRATED的所有回调 + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2075,21 +2134,27 @@ off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的方向传感器类型为ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 取消注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - sensor.off(sensor.SensorId.ORIENTATION, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ORIENTATION, callback1); + sensor.on(sensor.SensorId.ORIENTATION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ORIENTATION, callback1); + // 取消注册SensorId.ORIENTATION的所有回调 + sensor.off(sensor.SensorId.ORIENTATION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2107,19 +2172,27 @@ off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的计步传感器类型为PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 取消注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Steps: ' + data.steps); - } - sensor.off(sensor.SensorId.PEDOMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER, callback1); + sensor.on(sensor.SensorId.PEDOMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PEDOMETER, callback1); + // 取消注册SensorId.PEDOMETER的所有回调 + sensor.off(sensor.SensorId.PEDOMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2127,7 +2200,7 @@ try { off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void -取消订阅计步器检测传感器数据。 +取消订阅计步检测器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -2137,19 +2210,27 @@ off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectio | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的计步检测传感器类型为PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 取消注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Scalar data: ' + data.scalar); - } - sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback1); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback1); + // 取消注册SensorId.PEDOMETER_DETECTION的所有回调 + sensor.off(sensor.SensorId.PEDOMETER_DETECTION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2157,7 +2238,7 @@ try { off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void -取消订阅接近传感器数据。 +取消订阅接近光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2165,19 +2246,27 @@ off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的接近光传感器类型为PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 取消注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Distance: ' + data.distance); - } - sensor.off(sensor.SensorId.PROXIMITY, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PROXIMITY, callback1); + sensor.on(sensor.SensorId.PROXIMITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PROXIMITY, callback1); + // 取消注册SensorId.PROXIMITY的所有回调 + sensor.off(sensor.SensorId.PROXIMITY); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2193,22 +2282,27 @@ off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorRespons | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的旋转矢量传感器类型为ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 取消注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - sensor.off(sensor.SensorId.ROTATION_VECTOR, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback1); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback1); + // 取消注册SensorId.ROTATION_VECTOR的所有回调 + sensor.off(sensor.SensorId.ROTATION_VECTOR); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2216,7 +2310,7 @@ try { off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void -取消订阅重要的运动传感器数据。 +取消大幅动作检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2224,19 +2318,27 @@ off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的大幅动作传感器类型为SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 取消注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Scalar data: ' + data.scalar); - } - sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + // 取消注册SensorId.SIGNIFICANT_MOTION的所有回调 + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2252,19 +2354,27 @@ off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的佩戴检测传感器类型为WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 取消注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| type | [SensorId](#sensorid9) | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function accCallback(data) { - console.info('Wear status: ' + data.value); - } - sensor.off(sensor.SensorId.WEAR_DETECTION, accCallback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback1); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.WEAR_DETECTION, callback1); + // 取消注册SensorId.WEAR_DETECTION的所有回调 + sensor.off(sensor.SensorId.WEAR_DETECTION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2272,7 +2382,7 @@ try { getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void -获取地球上特定位置的地磁场 。 +获取某时刻地球上特定位置的地磁场信息。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2280,9 +2390,9 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callbac | 参数名 | 类型 | 必填 | 说明 | | --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | -| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置。 | -| timeMillis | number | 是 | 表示获取磁偏角的时间,单位为毫秒。 | -| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | 是 | 返回磁场信息。 | +| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置,包括经度、纬度和海拔高度。 | +| timeMillis | number | 是 | 获取磁偏角的时间,unix时间戳,单位毫秒。 | +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | 是 | 回调函数,返回地磁场信息。 | **错误码**: @@ -2296,13 +2406,21 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callbac ```js try { - sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000, function(data) { - console.info('sensor_getGeomagneticInfo_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000, function (err, data) { + if (err) { + console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info("GeomagneticInfo x" + data.x); + console.info("GeomagneticInfo y" + data.y); + console.info("GeomagneticInfo z" + data.z); + console.info("GeomagneticInfo geomagneticDip" + data.geomagneticDip); + console.info("GeomagneticInfo deflectionAngle" + data.deflectionAngle); + console.info("GeomagneticInfo levelIntensity" + data.levelIntensity); + console.info("GeomagneticInfo totalIntensity" + data.totalIntensity); }); } catch (err) { - console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2310,7 +2428,7 @@ try { getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> -获取地球上特定位置的地磁场 。 +获取某时刻地球上特定位置的地磁场信息。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2318,14 +2436,14 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promis | 参数名 | 类型 | 必填 | 说明 | | --------------- | ----------------------------------- | ---- | ---------------------------------- | -| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置。 | -| timeMillis | number | 是 | 表示获取磁偏角的时间,单位为毫秒。 | +| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置,包括经度、纬度和海拔高度。 | +| timeMillis | number | 是 | 获取磁偏角的时间,unix时间戳,单位毫秒。 | **返回值:** | 类型 | 说明 | | ---------------------------------------------------------- | -------------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | 返回磁场信息。 | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise对象,返回地磁场信息。 | **错误码**: @@ -2339,16 +2457,20 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promis ```js try { - const promise = sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000); - promise.then((data) => { - console.info('sensor_getGeomagneticInfo_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); - }).catch((reason) => { - console.info('Operation failed.'); - }) + const promise = sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000); + promise.then((data) => { + console.info("GeomagneticInfo x" + data.x); + console.info("GeomagneticInfo y" + data.y); + console.info("GeomagneticInfo z" + data.z); + console.info("GeomagneticInfo geomagneticDip" + data.geomagneticDip); + console.info("GeomagneticInfo deflectionAngle" + data.deflectionAngle); + console.info("GeomagneticInfo levelIntensity" + data.levelIntensity); + console.info("GeomagneticInfo totalIntensity" + data.totalIntensity); + }, (err)=>{ + console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get geomagneticInfo. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2356,7 +2478,7 @@ try { getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void -根据当前气压获取设备所在的海拔高度。 +根据气压值获取海拔高度。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2364,9 +2486,9 @@ getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncC | 参数名 | 类型 | 必填 | 说明 | | --------------- | --------------------------- | ---- | ------------------------------------- | -| seaPressure | number | 是 | 表示海平面气压值,单位为hPa。 | -| currentPressure | number | 是 | 表示设备所在高度的气压值,单位为hPa。 | -| callback | AsyncCallback<number> | 是 | 返回设备所在的海拔高度,单位为米。 | +| seaPressure | number | 是 | 海平面气压值,单位为hPa。 | +| currentPressure | number | 是 | 指定的气压值,单位为hPa。 | +| callback | AsyncCallback<number> | 是 | 回调函数,返回指定的气压值对应的海拔高度,单位为米。 | **错误码**: @@ -2380,11 +2502,17 @@ getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncC ```js try { - sensor.getDeviceAltitude(0, 200, function(data) { - console.info('Successed to get getDeviceAltitude interface get data: ' + data); - }); + let seaPressure = 1013.2; + let currentPressure = 1500.0; + sensor.getDeviceAltitude(seaPressure, currentPressure, function (err, data) { + if (err) { + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('altitude: ' + data); + }); } catch (err) { - console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2392,7 +2520,7 @@ try { getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<number> -根据当前气压获取设备所在的海拔高度。 +根据气压值获取海拔高度。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2400,14 +2528,14 @@ getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<numb | 参数名 | 类型 | 必填 | 说明 | | --------------- | ------ | ---- | ------------------------------------- | -| seaPressure | number | 是 | 表示海平面气压值,单位为hPa。 | -| currentPressure | number | 是 | 表示设备所在高度的气压值,单位为hPa。 | +| seaPressure | number | 是 | 海平面气压值,单位为hPa。 | +| currentPressure | number | 是 | 指定的气压值,单位为hPa。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------------------ | -| Promise<number> | 返回设备所在的海拔高度(单位:米)。 | +| Promise<number> | Promise对象,返回指定的气压值对应的海拔高度,单位为米。 | **错误码**: @@ -2421,14 +2549,16 @@ getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<numb ```js try { - const promise = sensor.getDeviceAltitude (0, 200); - promise.then((data) => { - console.info('sensor_getDeviceAltitude_Promise success', data); - }).catch((err) => { - console.error("Operation failed"); - }) + let seaPressure = 1013.2; + let currentPressure = 1500.0; + const promise = sensor.getDeviceAltitude(seaPressure, currentPressure); + promise.then((data) => { + console.info('sensor_getDeviceAltitude_Promise success', data); + }, (err) => { + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2436,7 +2566,7 @@ try { getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void -从倾角矩阵计算地磁倾角的弧度。 +根据倾斜矩阵计算地磁倾角。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2444,8 +2574,8 @@ getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback&l | 参数名 | 类型 | 必填 | 说明 | | ----------------- | --------------------------- | ---- | ---------------------------- | -| inclinationMatrix | Array<number> | 是 | 表示倾斜矩阵。 | -| callback | AsyncCallback<number> | 是 | 返回地磁倾斜角,单位为弧度。 | +| inclinationMatrix | Array<number> | 是 | 倾斜矩阵。 | +| callback | AsyncCallback<number> | 是 | 回调函数,返回地磁倾角,单位为弧度。 | **错误码**: @@ -2459,11 +2589,21 @@ getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback&l ```js try { - sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { - console.info('Successed to get getInclination interface get data: ' + data); - }) + // inclinationMatrix可以为3*3,或者4*4 + let inclinationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + sensor.getInclination(inclinationMatrix, function (err, data) { + if (err) { + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('Inclination: ' + data); + }) } catch (err) { - console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2471,7 +2611,7 @@ try { getInclination(inclinationMatrix: Array<number>): Promise<number> - 从倾角矩阵计算地磁倾角的弧度。 +根据倾斜矩阵计算地磁倾角。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2479,13 +2619,13 @@ try { | 参数名 | 类型 | 必填 | 说明 | | ----------------- | ------------------- | ---- | -------------- | -| inclinationMatrix | Array<number> | 是 | 表示倾斜矩阵。 | +| inclinationMatrix | Array<number> | 是 | 倾斜矩阵。 | **返回值:** | 类型 | 说明 | | --------------------- | ---------------------------- | -| Promise<number> | 返回地磁倾斜角,单位为弧度。 | +| Promise<number> | Promise对象,返回地磁倾斜角,单位为弧度。 | **错误码**: @@ -2499,14 +2639,20 @@ try { ```js try { - const promise = sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1]); - promise.then((data) => { - console.info('getInclination_promise successed', data); - }).catch((err) => { - console.error("Operation failed"); - }) + // inclinationMatrix可以为3*3,或者4*4 + let inclinationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + const promise = sensor.getInclination(inclinationMatrix); + promise.then((data) => { + console.info('Inclination: ' + data); + }, (err) => { + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2515,7 +2661,7 @@ try { getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback): void -得到两个旋转矩阵之间的角度变化。 +计算两个旋转矩阵之间的角度变化。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2523,9 +2669,9 @@ try { | 参数名 | 类型 | 必填 | 说明 | | --------------------- | ---------------------------------------- | ---- | --------------------------------- | -| currentRotationMatrix | Array<number> | 是 | 表示当前旋转矩阵。 | -| preRotationMatrix | Array<number> | 是 | 表示旋转矩阵。 | -| callback | AsyncCallback<Array<number>> | 是 | 返回z、x、y轴方向的旋转角度变化。 | +| currentRotationMatrix | Array<number> | 是 | 当前旋转矩阵。 | +| preRotationMatrix | Array<number> | 是 | 相对旋转矩阵。 | +| callback | AsyncCallback<Array<number>> | 是 | 回调函数,返回绕z、x、y轴方向的旋转角度。 | **错误码**: @@ -2539,13 +2685,31 @@ try { ```js try { - sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(data) { - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) + // 旋转矩阵可以为3*3,或者4*4 + let currentRotationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]; + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix, function (err, data) { + if (err) { + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + if (data.length < 3) { + console.error("Get angle variation failed, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }) } catch (err) { - console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2561,14 +2725,14 @@ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: | 参数名 | 类型 | 必填 | 说明 | | --------------------- | ------------------- | ---- | ------------------ | -| currentRotationMatrix | Array<number> | 是 | 表示当前旋转矩阵。 | -| preRotationMatrix | Array<number> | 是 | | +| currentRotationMatrix | Array<number> | 是 | 当前旋转矩阵。 | +| preRotationMatrix | Array<number> | 是 | 相对旋转矩阵 | **返回值:** | 类型 | 说明 | | ---------------------------------- | --------------------------------- | -| Promise<Array<number>> | 返回z、x、y轴方向的旋转角度变化。 | +| Promise<Array<number>> | Promise对象,返回绕z、x、y轴方向的旋转角度。 | **错误码**: @@ -2582,16 +2746,30 @@ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: ```js try { - const promise = sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); - promise.then((data) => { - for (var i=0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }).catch((reason) => { - console.info('promise::catch ', reason); - }) + // 旋转矩阵可以为3*3,或者4*4 + let currentRotationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]; + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix); + promise.then((data) => { + if (data.length < 3) { + console.error("Get angle variation failed, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }, (err) => { + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2599,7 +2777,7 @@ try { getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void -将旋转向量转换为旋转矩阵。 +根据旋转矢量获取旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2607,8 +2785,8 @@ getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback -将旋转向量转换为旋转矩阵。 +根据旋转矢量获取旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2644,13 +2827,13 @@ getRotationMatrix(rotationVector: Array<number>): Promise { - for (var i=0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }).catch((reason) => { - console.info('promise::catch ', reason); - }) + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + const promise = sensor.getRotationMatrix(rotationVector); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2682,7 +2866,7 @@ try { transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback): void -旋转提供的旋转矩阵,使其可以以不同的方式表示坐标系。 +根据指定坐标系映射旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2690,11 +2874,11 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor | 参数名 | 类型 | 必填 | 说明 | | ---------------- | ----------------------------------------- | ---- | ---------------------- | -| inRotationVector | Array<number> | 是 | 表示旋转矩阵。 | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 表示坐标系方向。 | -| callback | AsyncCallback<Array<number>> | 是 | 返回转换后的旋转矩阵。 | +| inRotationVector | Array<number> | 是 | 旋转矩阵。 | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 指定坐标系方向。 | +| callback | AsyncCallback<Array<number>> | 是 | 回调函数,返回映射后的旋转矩阵。 | -**错误码**: +**错误码**: 以下错误码的详细介绍请参见 [sensor.transformRotationMatrix错误码](../errorcodes/errorcode-sensor.md)。 @@ -2706,13 +2890,22 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor ```js try { - sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(data) { - for (var i=0; i < data.length; i++) { - console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + let rotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }, function (err, data) { + if (err) { + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + '] = ' + data[i]); } }) } catch (err) { - console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2720,7 +2913,7 @@ try { transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise -旋转提供的旋转矩阵,使其可以以不同的方式表示坐标系。 +根据指定坐标系映射旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2728,14 +2921,14 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor | 参数名 | 类型 | 必填 | 说明 | | ---------------- | ----------------------------------------- | ---- | ---------------- | -| inRotationVector | Array<number> | 是 | 表示旋转矩阵。 | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 表示坐标系方向。 | +| inRotationVector | Array<number> | 是 | 旋转矩阵。 | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 指定坐标系方向。 | **返回值:** | 类型 | 说明 | | ---------------------------------- | ---------------------- | -| Promise<Array<number>> | 返回转换后的旋转矩阵。 | +| Promise<Array<number>> | Promise对象,返回转换后的旋转矩阵。 | **错误码**: @@ -2749,16 +2942,21 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor ```js try { - const promise = sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + let rotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }); promise.then((data) => { - for (var i=0; i < data.length; i++) { - console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } - }).catch((err) => { - console.info("Operation failed"); -}) + }, (err) => { + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2766,7 +2964,7 @@ try { getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void -将旋转向量转换为归一化四元数。 +根据旋转向量计算归一化四元数。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2774,8 +2972,8 @@ getQuaternion(rotationVector: Array<number>, callback: AsyncCallback -将旋转向量转换为归一化四元数。 +根据旋转向量计算归一化四元数。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2811,13 +3014,13 @@ getQuaternion(rotationVector: Array<number>): Promise | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------- | ---- | -------------- | -| rotationVector | Array<number> | 是 | 表示旋转矢量。 | +| rotationVector | Array<number> | 是 | 旋转矢量。 | **返回值:** | 类型 | 说明 | | ---------------------------------- | ------------ | -| Promise<Array<number>> | 返回四元数。 | +| Promise<Array<number>> | Promise,对象返归一化回四元数。 | **错误码**: @@ -2831,17 +3034,17 @@ getQuaternion(rotationVector: Array<number>): Promise ```js try { - const promise = sensor.getQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); - promise.then((data) => { - console.info('getQuaternionn_promise successed'); - for (var i=0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + const promise = sensor.getQuaternion(rotationVector); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2849,7 +3052,7 @@ try { getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void -根据旋转矩阵计算设备的方向。 +根据旋转矩阵计算设备方向。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2857,8 +3060,8 @@ getOrientation(rotationMatrix: Array<number>, callback: AsyncCallbackSuccessed to get getOrientation interface get data: " + data); - for (var i = 1; i < data.length; i++) { - console.info('sensor_getOrientation_callback ' + data[i]); - } - }) + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.getOrientation(preRotationMatrix, function (err, data) { + if (err) { + console.error('Get orientation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + if (data.length < 3) { + console.error("Get orientation failed, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }) } catch (err) { - console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get orientation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2895,13 +3109,13 @@ getOrientation(rotationMatrix: Array<number>): Promise { - console.info('sensor_getOrientation_Promise success', data); - for (var i = 1; i < data.length; i++) { - console.info('sensor_getOrientation_promise ' + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) -} catch (err) { + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.getOrientation(preRotationMatrix); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }, (err) => { console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); + }); +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2941,9 +3159,9 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------------------------------------------------ | ---- | -------------- | -| gravity | Array<number> | 是 | 表示重力向量。 | -| geomagnetic | Array<number> | 是 | 表示地磁矢量。 | -| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | 是 | 返回旋转矩阵。 | +| gravity | Array<number> | 是 | 重力矢量。 | +| geomagnetic | Array<number> | 是 | 地磁矢量。 | +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | 是 | 回调函数,返回旋转矩阵。 | **错误码**: @@ -2957,11 +3175,17 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> ```js try { - sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(data) { - console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); - }) + let gravity = [-0.27775216, 0.5351276, 9.788099]; + let geomagnetic = [210.87253, -78.6096, -111.44444]; + sensor.getRotationMatrix(gravity, geomagnetic, function (err, data) => { + if (err) { + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('RotationMatrix' + JSON.stringify(data)); + }) } catch (err) { - console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2977,14 +3201,14 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------- | ---- | -------------- | -| gravity | Array<number> | 是 | 表示重力向量。 | -| geomagnetic | Array<number> | 是 | 表示地磁矢量。 | +| gravity | Array<number> | 是 | 重力向量。 | +| geomagnetic | Array<number> | 是 | 地磁矢量。 | **返回值:** | 类型 | 说明 | | ------------------------------------------------------------ | -------------- | -| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | 返回旋转矩阵。 | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise对象,返回旋转矩阵。 | **错误码**: @@ -2998,20 +3222,22 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> ```js try { - const promise = sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); - promise.then((data) => { - console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); - }).catch((err) => { - console.info('promise failed'); - }) + let gravity = [-0.27775216, 0.5351276, 9.788099]; + let geomagnetic = [210.87253, -78.6096, -111.44444]; + const promise = sensor.getRotationMatrix(gravity, geomagnetic); + promise.then((data) => { + console.info('RotationMatrix' + JSON.stringify(data)); + }, (err) => { + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` ## sensor.getSensorList9+ - getSensorList(callback: AsyncCallback): void +getSensorList(callback: AsyncCallback): void 获取设备上的所有传感器信息。 @@ -3021,7 +3247,7 @@ try { | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | 是 | 返回传感器列表。 | +| callback | AsyncCallback | 是 | 回调函数,返回传感器属性列表。 | **错误码**: @@ -3035,14 +3261,17 @@ try { ```js try { - sensor.getSensorList((data) => { - console.info('getSensorList callback in ' + data.length); + sensor.getSensorList((err, data) => { + if (err) { + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); + console.info('data[' + i + ']: ' + JSON.stringify(data[i])); } }); } catch (err) { - console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3058,7 +3287,7 @@ try { | 参数名 | 类型 | 必填 | 说明 | | ------- | ---------------------------------------- | ---- | ---------------- | -| promise | Promise | 是 | 返回传感器列表。 | +| promise | Promise | 是 | Promise对象,返回传感器属性列表。 | **错误码**: @@ -3073,15 +3302,14 @@ try { ```js try { sensor.getSensorList().then((data) => { - console.info('getSensorList promise in ' + data.length); for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); + console.info('data[' + i + ']: ' + JSON.stringify(data[i])); } - }, (error)=>{ - console.error('getSensorList failed'); + }, (err) => { + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); }); } catch (err) { - console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3089,7 +3317,7 @@ try { getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void -获取指定类型的传感器信息。 +获取指定传感器类型的属性信息。 **系统能力**:SystemCapability.Sensors.Sensor @@ -3097,8 +3325,8 @@ getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------------- | -| type | [SensorId](#sensorid9) | 是 | 传感器类型。 | -| callback | AsyncCallback<[Sensor](#sensor9)> | 是 | 返回传感器信息。 | +| type | [SensorId](#sensorid9) | 是 | 指定传感器类型。 | +| callback | AsyncCallback<[Sensor](#sensor9)> | 是 | 回调函数,返回指定传感器的属性信息。 | **错误码**: @@ -3112,11 +3340,15 @@ getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void ```js try { - sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { - console.info('getSingleSensor ' + JSON.stringify(data)); + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (err, data) => { + if (err) { + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('Sensor: ' + JSON.stringify(data)); }); } catch (err) { - console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3153,12 +3385,12 @@ try { ```js try { sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { - console.info('getSingleSensor '+ JSON.stringify(data)); - }, (error)=>{ - console.error('getSingleSensor failed'); + console.info('Sensor: ' + JSON.stringify(data)); + }, (err) => { + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); }); } catch (err) { - console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3247,11 +3479,11 @@ try { | firmwareVersion | string | 传感器固件版本。 | | hardwareVersion | string | 传感器硬件版本。 | | sensorId | number | 传感器类型id。 | -| maxRange | number | 传感器的最大测量范围。 | +| maxRange | number | 传感器测量范围的最大值。 | | minSamplePeriod | number | 允许的最小采样周期。 | | maxSamplePeriod | number | 允许的最大采样周期。 | | precision | number | 传感器精度。 | -| power | number | 传感器电源。 | +| power | number | 传感器功率。 | ## AccelerometerResponse diff --git a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md index 37d5bcf23cc85414837cd682251f7018124d8aac..7c8b7c69b8253cbff98b304c9c595efa5a80d09c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @@ -13,16 +13,18 @@ ServiceExtensionContext模块提供ServiceExtensionAbility具有的能力和接 在使用ServiceExtensionContext的功能前,需要通过ServiceExtensionAbility子类实例获取。 -```js - import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + + let context = undefined; class MainAbility extends ServiceExtensionAbility { - onCreate() { - let context = this.context; - } + onCreate() { + context = this.context; + } } ``` -## startAbility +## ServiceExtensionContext.startAbility startAbility(want: Want, callback: AsyncCallback<void>): void; @@ -39,18 +41,57 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | want | [Want](js-apis-application-Want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如ability名称,包名等。 | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility"}; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + + try { + this.context.startAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## startAbility +## ServiceExtensionContext.startAbility startAbility(want: Want, options?: StartOptions): Promise\; @@ -73,22 +114,60 @@ startAbility(want: Want, options?: StartOptions): Promise\; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" - }; - this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + var options = { + windowMode: 0, + }; + try { + this.context.startAbility(want, options) + .then((data) => { + // 执行正常业务 + console.log('startAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## startAbility +## ServiceExtensionContext.startAbility startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void @@ -106,20 +185,58 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - - ```js + + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) + + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startAbilityWithAccount @@ -140,20 +257,58 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startAbilityWithAccount(want, accountId, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); - ``` + try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` ## ServiceExtensionContext.startAbilityWithAccount @@ -174,21 +329,60 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityWithAccount(want, accountId, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -216,25 +410,60 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options) - .then((data) => { - console.log('---------- startAbilityWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbility @@ -254,17 +483,48 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want, (err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbility @@ -289,21 +549,48 @@ startServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want) - .then((data) => { - console.log('---------- startServiceExtensionAbility success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbilityWithAccount @@ -326,18 +613,51 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbilityWithAccount @@ -365,22 +685,50 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId) - .then((data) => { - console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbility @@ -400,17 +748,45 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 | | callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want, (err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbility @@ -435,21 +811,45 @@ stopServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want) - .then((data) => { - console.log('---------- stopServiceExtensionAbility success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount @@ -472,18 +872,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 需要停止的系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount @@ -511,22 +940,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId) - .then((data) => { - console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.terminateSelf @@ -545,11 +999,29 @@ terminateSelf(callback: AsyncCallback<void>): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); + ```ts + this.context.terminateSelf((error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('terminateSelf succeed'); }); ``` @@ -569,19 +1041,33 @@ terminateSelf(): Promise<void>; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts this.context.terminateSelf().then((data) => { - console.log('success:' + JSON.stringify(data)); + // 执行正常业务 + console.log('terminateSelf succeed'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); }); ``` -## ServiceExtensionContext.connectAbility +## ServiceExtensionContext.connectServiceExtensionAbility -connectAbility(want: Want, options: ConnectOptions): number; +connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; 将一个Ability与服务类型的Ability绑定。 @@ -602,24 +1088,44 @@ connectAbility(want: Want, options: ConnectOptions): number; | -------- | -------- | | number | 返回一个number,后续根据这个number去断开连接。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" }; - let options = { + var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - let connection = this.context.connectAbility(want,options); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## ServiceExtensionContext.connectAbilityWithAccount +## ServiceExtensionContext.connectServiceExtensionAbilityWithAccount -connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; +connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; 使用AbilityInfo.AbilityType.SERVICE模板和account将当前能力连接到一个能力。 @@ -641,13 +1147,26 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions | -------- | -------- | | number | 返回Ability连接的结果code。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { @@ -655,13 +1174,20 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - const result = this.context.connectAbilityWithAccount(want, accountId, options); - console.log('----------- connectAbilityResult: ------------', result); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## ServiceExtensionContext.disconnectAbility +## ServiceExtensionContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number, callback:AsyncCallback<void>): void; +disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback<void>): void; 将一个Ability与绑定的服务类型的Ability解绑。 @@ -676,19 +1202,44 @@ disconnectAbility(connection: number, callback:AsyncCallback<void>): void; | connection | number | 是 | 在connectAbility中返回的number。 | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - let connection=1 - this.context.disconnectAbility(connection, (err) => { - // connection为connectAbility中的返回值 - console.log('terminateSelf result:' + JSON.stringify(err)); + ```ts + // connection为connectServiceExtensionAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## ServiceExtensionContext.disconnectAbility +## ServiceExtensionContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number): Promise<void>; +disconnectServiceExtensionAbility(connection: number): Promise<void>; 将一个Ability与绑定的服务类型的Ability解绑。通过Promise返回结果。 @@ -707,17 +1258,40 @@ disconnectAbility(connection: number): Promise<void>; | 类型 | 说明 | | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | - + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - let connection=1 - this.context.disconnectAbility(connection).then((data) => { - // connection为connectAbility中的返回值 - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); + ```ts + // connection为connectAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection) + .then((data) => { + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startAbilityByCall @@ -742,10 +1316,26 @@ startAbilityByCall(want: Want): Promise<Caller>; | -------- | -------- | | Promise<Caller> | 获取要通讯的caller对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000050 | Internal Error. | + **示例:** - ```js - let caller = undefined; + 后台启动: + + ```ts + var caller = undefined; // 后台启动Ability,不配置parameters var wantBackground = { @@ -754,13 +1344,29 @@ startAbilityByCall(want: Want): Promise<Caller>; abilityName: "MainAbility", deviceId: "" }; - this.context.startAbilityByCall(wantBackground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller Success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + 前台启动: + + ```ts + var caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true var wantForeground = { @@ -772,12 +1378,22 @@ startAbilityByCall(want: Want): Promise<Caller>; "ohos.aafwk.param.callAbilityToForeground": true } }; - this.context.startAbilityByCall(wantForeground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-stack.md b/zh-cn/application-dev/reference/apis/js-apis-stack.md index cb71700c6191fa6c2546a7a0a111b4432a233e84..3abca73aad6110eb4d9f13e40eb2e444515c4f87 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-stack.md +++ b/zh-cn/application-dev/reference/apis/js-apis-stack.md @@ -95,11 +95,11 @@ let stack = new Stack(); let result = stack.push("a"); let result1 = stack.push(1); let b = [1, 2, 3]; -stack.push(b); +let result2 = stack.push(b); let c = {name : "Dylon", age : "13"}; let result3 = stack.push(c); try { - stack.push.bind({}, "b")(); + stack.push.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -138,7 +138,7 @@ stack.push(2); stack.push(4); let result = stack.pop(); try { - stack.pop.bind({})(); + stack.pop.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -176,7 +176,7 @@ stack.push(5); stack.push(2); let result = stack.peek(); try { - stack.peek.bind({})(); + stack.peek.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -220,7 +220,7 @@ stack.push(5); stack.push(2); let result = stack.locate(2); try { - stack.locate.bind({}, 2)(); + stack.locate.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -272,7 +272,7 @@ stack.forEach((value, index) => { try { stack.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -310,7 +310,7 @@ stack.push(5); stack.push(4); let result = stack.isEmpty(); try { - stack.isEmpty.bind({})(); + stack.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -359,7 +359,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - stack[Symbol.iterator].bind({})(); + stack[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-tagSession.md b/zh-cn/application-dev/reference/apis/js-apis-tagSession.md old mode 100755 new mode 100644 index 0e8c280b1ba2e0eda322df2e2fcb95bba4a6d105..7196bcf24b46dc61da69642ef1178a1cfb897c13 --- a/zh-cn/application-dev/reference/apis/js-apis-tagSession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-tagSession.md @@ -13,64 +13,82 @@ import tag from '@ohos.nfc.tag'; ## tagSession -tagSession是所有[Nfc tag 技术类型](js-apis-nfctech.md)的基类, 提供建立连接和发送数据等共同接口。 +tagSession是所有[NFC Tag技术类型](js-apis-nfctech.md)的基类, 提供建立连接和发送数据等共同接口。 -需要通过其子类来访问以下接口。在下面的示例中 统一用 getXXTag表示获取子类实例的方法。 +需要通过其子类来访问以下接口。在下面的示例中 统一用 getXXX()表示获取子类实例的方法。 具体使用时,请根据实际采用的Nfc tag技术,选择对应的方法,具体请参见[nfcTag](js-apis-nfcTag.md)文档。 -### tagSession.connectTag - -connectTag(): boolean; +### tagSession.getTagInfo -和标签建立连接; +getTagInfo(): tag.TagInfo -在从标签读取数据或将数据写入标签之前,必须调用此方法。 +获取该Tag被分发时,NFC服务所提供的Tag数据对象。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| boolean | 连接建立成功返回 true,失败返回false。 | +| TagInfo | NFC服务所提供的Tag数据对象。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); -console.log("isNfcConnected:" +isNfcConnected); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let tagInfo = tag.getXXX(tagInfo).getTagInfo(); +console.log("tag tagInfo: " + tagInfo); ``` -### tagSession.reset() +### tagSession.connectTag -reset(): void +connectTag(): boolean; -重置与标签的连接,并恢复将数据写入标签的默认超时时间。 +和标签建立连接。在从标签读取数据或将数据写入标签之前,必须调用此方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| boolean | 方法执行成功返回 true,失败返回false。 | +| boolean | 连接建立成功返回true,失败返回false。 | **示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let connectStatus = tag.getXXX(tagInfo).connectTag(); +console.log("connectStatus: " + connectStatus); +``` + +### tagSession.reset() + +reset(): void + +重置与标签的连接。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC.Core +**示例:** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let reset = tag.getXXXTag(taginfo).reset(); -console.log("reset:" +reset); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +tag.getXXX(tagInfo).reset(); ``` ### tagSession.isTagConnected @@ -84,19 +102,19 @@ isTagConnected(): boolean **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | boolean | 已建立连接返回 true,未建立连接返回false。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); -console.log("isTagConnected:" +isTagConnected); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let isTagConnected = tag.getXXX(tagInfo).isTagConnected(); +console.log("isTagConnected: " + isTagConnected); ``` ### tagSession.getMaxSendLength @@ -110,17 +128,160 @@ getMaxSendLength(): number **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| number | 可以发送到标签的最大数据长度,非负数。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... +let maxSendLen = tag.getXXX(tagInfo).getMaxSendLength(); +console.log("tag maxSendLen: " + maxSendLen); +``` + +### tagSession.getSendDataTimeout + +getSendDataTimeout(): number + +查询发送数据到Tag的等待超时时间,单位是毫秒。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC.Core + +**返回值:** | **类型** | **说明** | | ------------------ | --------------------------| -| number | 可以发送到标签的最大数据长度。 | +| number | 发送数据到Tag的等待超时时间,单位是毫秒,非负数。 | **示例:** +```js +import tag from '@ohos.nfc.tag'; +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let sendDataTimeout = tag.getXXX(tagInfo).getSendDataTimeout(); +console.log("tag sendDataTimeout: " + sendDataTimeout); +``` + +### tagSession.setSendDataTimeout + +setSendDataTimeout(timeout: number): boolean + +查询发送数据到Tag的等待超时时间,单位是毫秒。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC.Core + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | 是 | 超时时间,单位毫秒,非负值。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| boolean | 设置超时时间成功返回true,设置失败返回false。 | + +**示例:** + +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let timeoutMs = 700; // change it to be correct. +let setStatus = tag.getXXX(tagInfo).setSendDataTimeout(timeoutMs); +console.log("tag setSendDataTimeout setStatus: " + setStatus); +``` + +### tagSession.sendData + +sendData(data: number[]): Promise + +发送指令到Tag上,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | 是 | 要发送的指令。每个number十六进制表示,范围是0x00~0xFF。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| Promise | 对端Tag对指令的响应数据。每个number十六进制表示,范围是0x00~0xFF。| + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +// connect the tag at first if not connected. +if (!tag.getXXX(tagInfo).isTagConnected()) { + if (!tag.getXXX(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, ...]; // change the raw data to be correct. +tag.getXXX(tagInfo).sendData(cmdData).then((response) => { + console.log("tagSession sendData Promise response: " + response); +}).catch((err)=> { + console.log("tagSession sendData Promise err: " + err); +}); +``` + +### tagSession.sendData + +sendData(data: number[], callback: AsyncCallback): void + +发送指令到Tag上,使用AsyncCallback方式作为异步方法。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | 是 | 要发送的指令。每个number十六进制表示,范围是0x00~0xFF。 | +| callback | AsyncCallback | 是 | 回调函数,返回响应数据。每个number十六进制表示,范围是0x00~0xFF。 | + +**示例:** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); -console.log("mazSendLen:" +mazSendLen); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +// connect the tag at first if not connected. +if (!tag.getXXX(tagInfo).isTagConnected()) { + if (!tag.getXXX(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, ...]; // change the raw data to be correct. +tag.getXXX(tagInfo).sendData(cmdData, (err, response)=> { + if (err) { + console.log("tagSession sendData AsyncCallback err: " + err); + } else { + console.log("tagSession sendData AsyncCallback response: " + response); + } +}); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-testRunner.md b/zh-cn/application-dev/reference/apis/js-apis-testRunner.md index 273d1a19809895449766817a970e177dc4aeb3dd..92b46f63b5eab5c062cef6d588f7c972ef815afc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-testRunner.md +++ b/zh-cn/application-dev/reference/apis/js-apis-testRunner.md @@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner { onPrepare() { console.log("Trigger onPrepare") } - onRun(){} + onRun() {} }; ``` @@ -47,9 +47,9 @@ onRun(): void ```js export default class UserTestRunner implements TestRunner { - onPrepare() { - console.log("Trigger onRun") + onPrepare() {} + onRun() { + console.log("Trigger onRun") } - onRun(){} }; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-touchevent.md b/zh-cn/application-dev/reference/apis/js-apis-touchevent.md index 98a499564467113a1fda62564c9f116658db6202..59f8191cdf9522b993ee139a046456ff8dec2f88 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-touchevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-touchevent.md @@ -54,19 +54,19 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ----------- | ------ | ---- | ---- | ----------------------------------- | -| id | number | 是 | 否 | 指针标识 | -| pressedTime | number | 是 | 否 | 按下时的时间戳 | +| id | number | 是 | 否 | 触摸事件标识 | +| pressedTime | number | 是 | 否 | 按下时间戳 | | screenX | number | 是 | 否 | 触摸位置所属的屏幕x坐标 | | screenY | number | 是 | 否 | 触摸位置所属的屏幕y坐标 | | windowX | number | 是 | 否 | 触摸位置在窗口中的x坐标 | | windowY | number | 是 | 否 | 触摸位置在窗口中的y坐标 | | pressure | number | 是 | 否 | 压力值,取值范围是[0.0, 1.0], 0.0表示不支持 | -| width | number | 是 | 否 | 按下接触区域的宽度 | -| height | number | 是 | 否 | 按下接触区域的高度 | +| width | number | 是 | 否 | 触摸区域的宽度 | +| height | number | 是 | 否 | 触摸区域的高度 | | tiltX | number | 是 | 否 | 相对YZ平面的角度,取值的范围[-90, 90],其中正值是向右倾斜。 | | tiltY | number | 是 | 否 | 相对XZ平面的角度,值的范围[-90, 90],其中正值是向下倾斜。 | -| toolX | number | 是 | 否 | 工具区域的中心点X | -| toolY | number | 是 | 否 | 工具区域的中心点Y | +| toolX | number | 是 | 否 | 工具区域的中心点x坐标 | +| toolY | number | 是 | 否 | 工具区域的中心点y坐标 | | toolWidth | number | 是 | 否 | 工具区域宽度 | | toolHeight | number | 是 | 否 | 工具区域高度 | | rawX | number | 是 | 否 | 输入设备上的x坐标 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md index 2a9ecdf72e3e38ac84630ca6b447bb1fc6739297..2362b3a1e8b2048c9012f922350c88ced020ba0a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treemap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -94,7 +94,7 @@ isEmpty(): boolean const treeMap = new TreeMap(); let result = treeMap.isEmpty(); try { - treeMap.isEmpty.bind({})(); + treeMap.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -137,7 +137,7 @@ let result = treeMap.hasKey("squirrel"); treeMap.set("squirrel", 123); let result1 = treeMap.hasKey("squirrel"); try { - treeMap.hasKey.bind({}, "squirrel")(); + treeMap.hasKey.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -180,7 +180,7 @@ let result = treeMap.hasValue(123); treeMap.set("squirrel", 123); let result1 = treeMap.hasValue(123); try { - treeMap.hasValue.bind({}, 123)(); + treeMap.hasValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -223,7 +223,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.get("sparrow"); try { - treeMap.get.bind({}, "sparrow")(); + treeMap.get.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -260,7 +260,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getFirstKey(); try { - treeMap.getFirstKey.bind({})(); + treeMap.getFirstKey.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -297,7 +297,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getLastKey(); try { - treeMap.getLastKey.bind({})(); + treeMap.getLastKey.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -335,7 +335,7 @@ treeMap.set("sparrow", 356); let map = new TreeMap(); treeMap.setAll(map); try { - treeMap.setAll.bind({}, map)(); + treeMap.setAll.bind({}, map)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -377,7 +377,7 @@ set(key: K, value: V): Object let treeMap = new TreeMap(); treeMap.set("squirrel", 123); try { - treeMap.set.bind({}, "squirrel", 123)(); + treeMap.set.bind({}, "squirrel", 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -420,7 +420,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.remove("sparrow"); try { - treeMap.remove.bind({}, "sparrow")(); + treeMap.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -464,7 +464,7 @@ treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getLowerKey("sparrow"); try { - treeMap.getLowerKey.bind({}, "sparrow")(); + treeMap.getLowerKey.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -508,7 +508,7 @@ treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getHigherKey("sparrow"); try { - treeMap.getHigherKey.bind({}, "sparrow")(); + treeMap.getHigherKey.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -550,7 +550,7 @@ let treeMap = new TreeMap(); treeMap.set("sparrow", 123); let result = treeMap.replace("sparrow", 357); try { - treeMap.replace.bind({}, "sparrow", 357)(); + treeMap.replace.bind({}, "sparrow", 357)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -581,7 +581,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.clear(); try { - treeMap.clear.bind({})(); + treeMap.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -623,7 +623,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap.keys.bind({})(); + treeMap.keys.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -665,7 +665,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap.values.bind({})(); + treeMap.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -714,7 +714,7 @@ treeMap.forEach((value, key) => { try { treeMap.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -757,7 +757,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap.entries.bind({})(); + treeMap.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -807,7 +807,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap[Symbol.iterator].bind({})(); + treeMap[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-treeset.md b/zh-cn/application-dev/reference/apis/js-apis-treeset.md index d2f8259399bc69099d1054342445469be05eec46..02102890f016d30d0f3a1712396683e4ebbb65a7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treeset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treeset.md @@ -83,7 +83,7 @@ isEmpty(): boolean const treeSet = new TreeSet(); let result = treeSet.isEmpty(); try { - treeSet.isEmpty.bind({})(); + treeSet.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -118,7 +118,7 @@ treeSet.has(123); treeSet.add(123); let result1 = treeSet.has(123); try { - treeSet.has.bind({}, 123)(); + treeSet.has.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -147,7 +147,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getFirstValue(); try { - treeSet.getFirstValue.bind({})(); + treeSet.getFirstValue.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -176,7 +176,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getLastValue(); try { - treeSet.getLastValue.bind({})(); + treeSet.getLastValue.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -209,7 +209,7 @@ add(value: T): boolean let treeSet = new TreeSet(); let result = treeSet.add("squirrel"); try { - treeSet.add.bind({}, "squirrel")(); + treeSet.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -244,7 +244,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.remove("sparrow"); try { - treeSet.remove.bind({}, "sparrow")(); + treeSet.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -280,7 +280,7 @@ treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getLowerValue("sparrow"); try { - treeSet.getLowerValue.bind({}, "sparrow")(); + treeSet.getLowerValue.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -316,7 +316,7 @@ treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getHigherValue("sparrow"); try { - treeSet.getHigherValue.bind({}, "sparrow")(); + treeSet.getHigherValue.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -345,7 +345,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popFirst(); try { - treeSet.popFirst.bind({})(); + treeSet.popFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -374,7 +374,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popLast(); try { - treeSet.popLast.bind({})(); + treeSet.popLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -397,7 +397,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.clear(); try { - treeSet.clear.bind({})(); + treeSet.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -431,7 +431,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeSet.values.bind({})(); + treeSet.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -472,7 +472,7 @@ treeSet.forEach((value, key) => { try { treeSet.forEach.bind({}, (value, key) => { console.log("value:" + value, key) - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -507,7 +507,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeSet.entries.bind({})(); + treeSet.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -548,7 +548,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeSet[Symbol.iterator].bind({})(); + treeSet[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-uri.md b/zh-cn/application-dev/reference/apis/js-apis-uri.md index f14cab80f246d22f68b0012e9c3026447f92e776..642bf26604dcbbf0bffd0a6e7c48a97953524d80 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uri.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uri.md @@ -76,7 +76,9 @@ result.toString() ``` -### equals +### equals(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[equalsTo9+](#equalsto9)替代。 equals(other: URI): boolean @@ -103,6 +105,33 @@ const uriInstance = new uri.URI('http://username:password@host:8080/directory/fi const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); uriInstance.equals(uriInstance1); ``` +### equalsTo9+ + +equalsTo(other: URI): boolean + +判断此URI是否与其他URI对象相等。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| other | [URI](#uri) | 是 | 需要比较的URI对象。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 返回true表示相等,否则返回false。 | + +**示例:** + +```js +const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +uriInstance.equalsTo(uriInstance1); +``` ### checkIsAbsolute diff --git a/zh-cn/application-dev/reference/apis/js-apis-url.md b/zh-cn/application-dev/reference/apis/js-apis-url.md index 44b873ad803829f77a47b79878496e9eaab5e92f..4a7cd31c53c0068fe76bd3f73177a9a98fc0c9b9 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-url.md +++ b/zh-cn/application-dev/reference/apis/js-apis-url.md @@ -3,17 +3,374 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 ``` import Url from '@ohos.url' ``` +## URLParams9+ -## URLSearchParams +### constructor9+ -### constructor +constructor(init?: string[][] | Record<string, string> | string | URLParams) + +URLParams的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| init | string[][] \| Record<string, string> \| string \| URLParams | 否 | 入参对象。
- string[][]:字符串二维数组
- Record<string, string>:对象列表
- string:字符串
- URLParams:对象 | + +**示例:** + +```js +let objectParams = new Url.URLParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); +let objectParams1 = new Url.URLParams({"fod" : '1' , "bard" : '2'}); +let objectParams2 = new Url.URLParams('?fod=1&bard=2'); +let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); +let params = new Url.URLParams(urlObject.search); +``` + + +### append9+ + +append(name: string, value: string): void + +将新的键值对插入到查询字符串。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 需要插入搜索参数的键名。 | +| value | string | 是 | 需要插入搜索参数的值。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.append('fod', '3'); +``` + + +### delete9+ + +delete(name: string): void + +删除指定名称的键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 需要删除的键值名称。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsobject = new Url.URLParams(urlObject.search.slice(1)); +paramsobject.delete('fod'); +``` + + +### getAll9+ + +getAll(name: string): string[] + +获取指定名称的所有键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 指定的键值名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string[] | 返回指定名称的所有键值对。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let params = new Url.URLParams(urlObject.search.slice(1)); +params.append('fod', '3'); // Add a second value for the fod parameter. +console.log(params.getAll('fod').toString()) // Output ["1","3"]. +``` + + +### entries9+ + +entries(): IterableIterator<[string, string]> + +返回一个ES6的迭代器,迭代器的每一项都是一个 JavaScript Array。Array的第一项是name,Array的第二项是value。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<[string, string]> | 返回一个ES6的迭代器。 | + +**示例:** + +```js +let searchParamsObject = new Url.URLParams("keyName1=valueName1&keyName2=valueName2"); +for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs + console.log(pair[0]+ ', '+ pair[1]); +} +``` + + +### forEach9+ + +forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void + +通过回调函数来遍历URLSearchParams实例对象上的键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callbackfn | function | 是 | 回调函数。 | +| thisArg | Object | 否 | callbackfn被调用时用作this值 | + +**表1** callbackfn的参数说明 + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | string | 是 | 当前遍历到的键值。 | +| key | string | 是 | 当前遍历到的键名。 | +| searchParams | Object | 是 | 当前调用forEach方法的实例对象。 | + +**示例:** + +```js +const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +myURLObject.URLParams.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.searchParams === searchParams); +}); +``` + + +### get9+ + +get(name: string): string | null + +获取指定名称对应的第一个值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 指定键值对的名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 返回第一个值。 | +| null | 如果没找到,返回 null。 | + +**示例:** + +```js +let paramsObject = new Url.URLParams('name=Jonathan&age=18'); +let name = paramsObject.get("name"); // is the string "Jonathan" +let age = parseInt(paramsObject.get("age"), 10); // is the number 18 +``` + + +### has9+ + +has(name: string): boolean + +判断一个指定的键名对应的值是否存在。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 要查找的参数的键名。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 是否存在相对应的key值,存在返回true,否则返回false。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.has('bard') === true; +``` + + +### set9+ + +set(name: string, value: string): void + +将与name关联的URLSearchParams对象中的值设置为value。如果存在名称为name的键值对,请将第一个键值对的值设置为value并删除所有其他值。如果不是,则将键值对附加到查询字符串。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 将要设置的参数的键值名。 | +| value | string | 是 | 所要设置的参数值。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.set('baz', '3'); // Add a third parameter. +``` + + +### sort9+ + +sort(): void + +对包含在此对象中的所有键值对进行排序,并返回undefined。排序顺序是根据键的Unicode代码点。该方法使用稳定的排序算法 (即,将保留具有相等键的键值对之间的相对顺序)。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + +```js +let searchParamsObject = new Url.URLParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object +searchParamsObject.sort(); // Sort the key/value pairs +console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 +``` + + +### keys9+ + +keys(): IterableIterator<string> + +返回一个所有键值对的name的ES6迭代器。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<string> | 返回一个所有键值对的name的ES6迭代器。 | + +**示例:** + +```js +let searchParamsObject = new Url.URLParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +for (var key of searchParamsObject .keys()) { // Output key-value pairs + console.log(key); +} +``` + + +### values9+ + +values(): IterableIterator<string> + +返回一个所有键值对的value的ES6迭代器。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<string> | 返回一个所有键值对的value的ES6迭代器。 | + +**示例:** + +```js +let searchParams = new Url.URLParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +for (var value of searchParams.values()) { + console.log(value); +} +``` + + +### [Symbol.iterator]9+ + +[Symbol.iterator]\(): IterableIterator<[string, string]> + +返回一个ES6的迭代器,迭代器的每一项都是一个 JavaScript Array。Array的第一项是name,Array的第二项是value。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<[string, string]> | 返回一个ES6的迭代器。 | + +**示例:** + +```js +const paramsObject = new Url.URLParams('fod=bay&edg=bap'); +for (const [name, value] of paramsObject) { + console.log(name, value); +} +``` + + +### tostring9+ + +toString(): string + +返回序列化为字符串的搜索参数,必要时对字符进行百分比编码。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 返回序列化为字符串的搜索参数,必要时对字符进行百分比编码。 | + +**示例:** + +```js +let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let params = new Url.URLParams(url.search.slice(1)); +params.append('fod', '3'); +console.log(params.toString()); +``` + +## URLSearchParams(deprecated) + +### constructor(deprecated) + +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+](#constructor9+)替代。 constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) @@ -37,8 +394,10 @@ let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); let params = new Url.URLSearchParams(urlObject.search); ``` +### append(deprecated) -### append +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.append9+](#append9)替代。 append(name: string, value: string): void @@ -61,8 +420,10 @@ let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); paramsObject.append('fod', '3'); ``` +### delete(deprecated) -### delete +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.delete9+](#delete9)替代。 delete(name: string): void @@ -84,8 +445,10 @@ let paramsobject = new Url.URLSearchParams(urlObject.search.slice(1)); paramsobject.delete('fod'); ``` +### getAll(deprecated) -### getAll +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.getAll9+](#getall9)替代。 getAll(name: string): string[] @@ -114,8 +477,10 @@ params.append('fod', '3'); // Add a second value for the fod parameter. console.log(params.getAll('fod').toString()) // Output ["1","3"]. ``` +### entries(deprecated) -### entries +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.entries9+](#entries9)替代。 entries(): IterableIterator<[string, string]> @@ -139,7 +504,9 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ``` -### forEach +### forEach(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.forEach9+](#foreach9)替代。 forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void @@ -172,7 +539,9 @@ myURLObject.searchParams.forEach((value, name, searchParams) => { ``` -### get +### get(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.get9+](#get9)替代。 get(name: string): string | null @@ -202,7 +571,9 @@ let age = parseInt(paramsObject.get("age"), 10); // is the number 18 ``` -### has +### has(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.has9+](#has9)替代。 has(name: string): boolean @@ -231,7 +602,9 @@ paramsObject.has('bard') === true; ``` -### set +### set(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.set9+](#set9)替代。 set(name: string, value: string): void @@ -255,7 +628,9 @@ paramsObject.set('baz', '3'); // Add a third parameter. ``` -### sort +### sort(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.sort9+](#sort9)替代。 sort(): void @@ -272,7 +647,9 @@ console.log(searchParamsObject.toString()); // Display the sorted query string / ``` -### keys +### keys(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.keys9+](#keys9)替代。 keys(): IterableIterator<string> @@ -296,7 +673,9 @@ for (var key of searchParamsObject .keys()) { // Output key-value pairs ``` -### values +### values(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.values9+](#values9)替代。 values(): IterableIterator<string> @@ -320,7 +699,9 @@ for (var value of searchParams.values()) { ``` -### [Symbol.iterator] +### [Symbol.iterator](deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.[Symbol.iterator]9+](#symbol.iterator9)替代。 [Symbol.iterator]\(): IterableIterator<[string, string]> @@ -343,8 +724,9 @@ for (const [name, value] of paramsObject) { } ``` - -### tostring +### tostring(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.tostring9+](#tostring9)替代。 toString(): string @@ -367,7 +749,6 @@ params.append('fod', '3'); console.log(params.toString()); ``` - ## URL ### 属性 @@ -387,12 +768,13 @@ console.log(params.toString()); | protocol | string | 是 | 是 | 获取和设置URL的协议部分。 | | search | string | 是 | 是 | 获取和设置URL的序列化查询部分。 | | searchParams | URLsearchParams | 是 | 否 | 获取URLSearchParams表示URL查询参数的对象。 | +| URLParams | URLParams | 是 | 否 | 获取URLParams表示URL查询参数的对象。 | | username | string | 是 | 是 | 获取和设置URL的用户名部分。 | ### constructor -constructor(url: string, base?: string | URL) +constructor(url?: string, base?: string | URL) URL的构造函数。 @@ -422,6 +804,27 @@ new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ ``` +### parseURL9+ + +static parseURL(inputUrl : string, inputBase ?: string | URL) + +URL静态成员函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| inputUrl | string | 是 | 入参对象。 | +| inputBase | string \| URL | 否 | 入参字符串或者对象。
- string:字符串
- URL:字符串或对象 | + +**示例:** + +```js +let mm = 'http://username:password@host:8080'; +Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +``` ### tostring @@ -464,3 +867,4 @@ toJSON(): string const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON(); ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md b/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md index 7a5bd18ae9025bd98152dbef34527d4e1af6b409..ac164b3b6b8a98d7deb7ea3459009a68be9d43b8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @@ -1,12 +1,15 @@ # 用户数据管理 +该模块提供用户数据管理能力,包括访问、修改用户等用户公共媒体数据信息等常用功能。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 该模块从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 本模块下的接口均为系统接口 ## 导入模块 -```js -import userFileManager from '@ohos.filemanagement.userfile_manager'; +```ts +import userFileManager from '@ohos.filemanagement.userFileManager'; ``` ## userFileManager.getUserFileMgr @@ -16,7 +19,7 @@ getUserFileMgr(context: Context): UserFileManager 获取用户数据管理模块的实例,用于访问和修改用户等用户公共媒体数据信息(如音频、视频、图片、文档等)。 **模型约束:** 此接口仅可在Stage模型下使用。 - + **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** @@ -35,7 +38,7 @@ getUserFileMgr(context: Context): UserFileManager ```ts const context = getContext(this); -let userFileMgr = userfilemanager.getUserFileMgr(context); +let mgr = userfilemanager.getUserFileMgr(context); ``` ## userFileManager.getUserFileMgr @@ -58,739 +61,746 @@ getUserFileMgr(): UserFileManager **示例:** -```js -let userFileMgr = userfilemanager.getUserFileMgr(); +```ts +let mgr = userfilemanager.getUserFileMgr(); ``` ## UserFileManager -### getPublicDirectory +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + + +获取图片和视频资源,使用callback方式返回结果。 -getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void; -获取系统预设的公共目录,使用callback方式返回异步结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 | -| callback | AsyncCallback<string> | 是 | callback 返回公共目录路径 | +| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回图片和视频检索结果集 | **示例:** ```ts -async function getPublicDirectoryDemoCallback() { - console.info('getPublicDirectoryDemo'); - let DIR_CAMERA = directoryType.DIR_CAMERA; - console.info('DIR_CAMERA', DIR_CAMERA); - userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { - if (dicResult == 'Camera/') { - console.info('mediaLibraryTest : getPublicDirectory passed'); - } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); - } - }); +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchResult fail' + err); + } + }) } ``` -### getPublicDirectory -getPublicDirectory(type: DirectoryType): Promise<string>; +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -获取系统预设的公共目录,使用Promise方式返回结果。 +获取图片和视频资源,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------- | ---- | ------------ | -| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ---------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项 | -**返回值:** +**返回值** -| 类型 | 说明 | -| ---------------- | ---------------- | -| Promise\ | 返回公共目录路径 | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 图片和视频数据结果集 | **示例:** ```ts -async function getPublicDirectoryDemoPromise() { - console.info('getPublicDirectoryDemo'); - let DIR_CAMERA = directoryType.DIR_CAMERA; - try { - let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA); - console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult); - } catch (err) { - console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err); +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getPhotoAssets(fetchOptions) + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } } + } catch (err) { + console.info('getPhotoAssets failed, message = ', err); + } } ``` +### createPhotoAsset -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; -获取文件资源,使用callback方式返回结果。 +创建图片或视频资源,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 文件检索选项 | -| callback | AsyncCallback<string> | 是 | callback 返回文件检索结果 | +| displayName | string | 是 | 创建的图片或者视频文件名 | +| albumUri | string | 是 | 创建的图片或者视频所在相册的uri | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback 返回创建的图片和视频结果 | **示例:** ```ts -async function getFileAssetsDemoCallback() { - console.info('getFileAssets'); - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE - let fetchOp = { - selections: '', - selectionArgs: [], - }; +async function example() { + console.info('createPhotoAssetDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + predicates: predicates + }; + let albums = await mgr.getPhotoAlbums(fetchOptions) + let album = await albums.getFirstObject() + mgr.createPhotoAsset('testFile.txt', album.albumUri, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }) +} +``` - userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => { - if (fetchFileResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchFileResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - }; - } - }) +### createPhotoAsset + +createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): void; + +创建图片或视频资源,使用callback方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的图片或者视频文件名 | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback 返回创建的图片和视频结果 | + +**示例:** + +```ts +async function example() { + console.info('createPhotoAssetDemo') + mgr.createPhotoAsset('testFile.txt', (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }) } ``` -### getFileAssets +### createPhotoAsset -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; +createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset>; -获取文件资源,使用Promise方式返回结果。 +创建图片或视频资源,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | ---------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 文件检索选项 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的图片或者视频文件名 | +| albumUri | string | 否 | 创建的图片或者视频所在相册的uri | **返回值** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | 文件数据结果集 | +| Promise<[FileAsset](#fileasset)> | 返回创建的图片和视频结果 | **示例:** ```ts -async function getFileAssetsDemoPromise() { - console.info('getFileAssets'); - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE - let fetchOp = { - selections: '', - selectionArgs: [], - }; - try { - var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp) - } catch (err) { - console.info('getFileAssets failed, message = ', err); - } - - if (fetchFileResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchFileResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - }; - } +async function example() { + console.info('createPhotoAssetDemo') + try { + let fileAsset = await mgr.createPhotoAsset('testFile.txt') + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ', err); + } } ``` -### on +### getPhotoAlbums -on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void +getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; -打开文件管理库变更通知,使用callback方式返回异步结果。 + +获取相册,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | Callback<void> | 是 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | 是 | callback 返回相册检索结果 | **示例:** ```ts -async function onDemo() { - console.info('onDemo') - userFileMgr.on('imageChange', () => { - // image file had changed, do something - }); +async function example() { + console.info('getPhotoAlbumsDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + + mgr.getPhotoAlbums(albumFetchOptions, (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('albums.count = ' + fetchResult.getCount()); + fetchResult.getFirstObject((err, album) => { + if (album != undefined) { + console.info('first album.albumName = ' + album.albumName); + } else { + console.info('album is undefined, err = ', err); + } + }) + } + console.info('getPhotoAlbums fail, message = ', err); + }) } ``` -### off +### getPhotoAlbums -off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void +getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>>; -关闭文件管理库变更通知,使用callback方式返回异步结果。 +获取相册,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | Callback<void> | 否 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项 | + +**返回值** + +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise 返回相册检索结果 | **示例:** ```ts -async function offDemo() { - console.info('offDemo') - userFileMgr.off('imageChange', () => { - // stop listening success - }); +async function example() { + console.info('getPhotoAlbumsDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + let fetchResult = await mgr.getPhotoAlbums(albumFetchOptions); + console.info('album.count = ' + fetchResult.getCount()); + const album = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + album.albumName); + } catch (err) { + console.info('getPhotoAlbums fail, message = ' + err); + } } ``` -### createAsset +### getPrivateAlbum -createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void +getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; -创建文件资源,使用callback方式返回结果。 -此接口为系统接口。 +获取系统相册,使用 callback 方式返回系统相册的数组。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | --------------------------- | ---- | ------------------------------------------------------------ | -| mediaType | [MediaType](#mediatype) | 是 | 媒体类型 | -| displayName | string | 是 | 展示文件名 | -| relativePath | string | 是 | 文件保存路径,可以通过getPublicDirectory获取不同类型文件的保存路径 | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步获取媒体数据FileAsset之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | 是 | callback 返回相册检索结果 | **示例:** ```ts -async function createAssetDemoCallback() { - console.info('createAssetDemo') - let mediaType = userfile_manager.MediaType.FILE; - let DIR_DOC = directoryType.DIR_DOCUMENTS; - const path = await userFileMgr.getPublicDirectory(DIR_DOC); - userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => { - if (err == undefined) { - console.info('createAsset successfully'); - } else { - console.info('createAsset failed, message = ', err); - } - }) +async function example() { + console.info('getPrivateAlbumDemo') + mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { + if (fetchResult != undefined) { + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } else { + console.info('getPrivateAlbum failed. message = ', err); + } + }); } ``` -### createAsset +### getPrivateAlbum -createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>; +getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum>>; -创建文件资源,使用Promise方式返回结果。 -此接口为系统接口。 +获取系统相册,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | --------- | ---- | ------------------------------------------------------------ | -| mediaType | [MediaType](#mediatype) | 是 | 媒体类型 | -| displayName | string | 是 | 展示文件名 | -| relativePath | string | 是 | 文件保存路径,可以通过getPublicDirectory获取不同类型文件的保存路径 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型 | **返回值** -| 类型 | 说明 | -| --------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 媒体数据FileAsset | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Promise 返回相册检索结果 | **示例:** ```ts -async function createAssetDemoPromise() { - console.info('createAssetDemo') - let mediaType = userfile_manager.MediaType.FILE; - let DIR_DOC = directoryType.DIR_DOCUMENTS; - const path = await userFileMgr.getPublicDirectory(DIR_DOC); - try { - let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/') - console.info('createAsset successfully'); - } catch (err) { - console.info('createAsset failed, message = ', err); - } +async function example() { + console.info('getPrivateAlbumDemo'); + try { + var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } catch (err) { + console.info('getPrivateAlbum failed. message = ', err); + } } ``` -### deleteAsset +### getAudioAssets -deleteAsset(uri: string, callback: AsyncCallback<void>): void; +getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -删除文件资源,使用callback方式返回结果。 -此接口为系统接口。 +获取音频文件,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_AUDIO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ---------------------- | -| uri | string | 是 | 文件URI | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步删除文件之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回相册检索结果 | **示例:** ```ts -async function deleteAssetDemoCallback() { - console.info('deleteAssetDemo') - let fileKeyObj = userfile_manager.FileKey - let fileType = userfile_manager.MediaType.FILE - let option = { - selections: '', - selectionArgs: [], - }; - try { - const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); - var asset = await fetchFileResult.getFirstObject(); - } catch(err) { - console.info('fetch failed, message =', err) - } - - if (asset == undefined) { - console.error('asset not exist') - return +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchFileResult fail' + err); } - userFileMgr.deleteAsset(asset.uri, (err) => { - if (err == undefined) { - console.info("deleteAsset successfully"); - } else { - console.info("deleteAsset failed with error:"+ err); - } - }); + }) } ``` -### deleteAsset +### getAudioAssets -deleteAsset(uri: string): Promise<void>; +getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -创建文件资源,使用Promise方式返回结果。 -此接口为系统接口。 +获取音频文件,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_AUDIO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| uri | string | 是 | 文件URI | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | **返回值** -| 类型 | 说明 | -| ---------------- | --------------------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果 | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise 返回相册检索结果 | **示例:** ```ts -async function deleteAssetDemoPromise() { - console.info('deleteAssetDemo') - let fileKeyObj = userfile_manager.FileKey - let fileType = userfile_manager.MediaType.FILE - let option = { - selections: '', - selectionArgs: [], - }; - try { - const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); - var asset = await fetchFileResult.getFirstObject(); - } catch(err) { - console.info('fetch failed, message =', err) - } - if (asset == undefined) { - console.error('asset not exist') - return - } - try { - await userFileMgr.deleteAsset(asset.uri); - console.info("deleteAsset successfully"); - } catch (err) { - console.info("deleteAsset failed with error:"+ err); +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getPhotoAssets(fetchOptions) + } catch (err) { + console.info('getAudioAssets failed, message = ', err); + } + + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); } + } } ``` +### delete -### getAlbums - -getAlbums(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback | 是 | 相册媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 相册获取条件 | -| callback | AsyncCallback<Array<[Album](#album)>> | 是 | 异步获取Album列表之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 媒体文件uri | +| callback | AsyncCallback<void> | 是 | 回调返回空 | -**示例:** +**示例**: ```ts -async function getAlbumsDemoCallback() { - console.info('getAlbumsDemo') - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => { - if (albumList != undefined) { - const album = albumList[0]; - console.info('first album.albumName = ' + album.albumName); - console.info('album.count = ' + albumList.length); - } else { - console.info('getAlbum fail, message = ' + err); - } - }) +async function example() { + console.info('deleteAssetDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err) + } + + if (asset == undefined) { + console.error('asset not exist') + return; + } + mgr.delete(asset.uri, (err) => { + if (err == undefined) { + console.info("delete successfully"); + } else { + console.info("delete failed with error:" + err); + } + }); } ``` +### delete -### getAlbums +delete(uri: string): Promise<void>; -getAlbums(type: Array<MediaType>, options: MediaFetchOptions): Promise>; +删除媒体文件。 -获取相册列表,使用 promise 方式返回结果。 - -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数** +**参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | -------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 相册媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 相册获取条件 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 媒体文件uri | -**返回值:** +**返回值**: -| 类型 | 说明 | -| ------------------------ | -------------------------- | -| Promise> | Promise实例,返回Album列表 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| 回调返回空 | -**示例:** +**示例**: ```ts -async function getAlbumsDemoPromise() { - console.info('getAlbumsDemo') - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - try { - let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp); - const album = albumList[0]; - console.info('first album.albumName = ' + album.albumName); - console.info('album.count = ' + albumList.length); - } catch (err) { - console.info('getAlbum fail, message = ' + err); - } +async function example() { + console.info('deleteDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err) + } + + if (asset == undefined) { + console.error('asset not exist') + return; + } + try { + await mgr.delete(asset.uri); + console.info("delete successfully"); + } catch (err) { + console.info("delete failed with error:" + err); + } } ``` -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback): void +### on -获取系统相册,使用 callback 方式返回系统相册的数组。 +on(type: ChangeEvent, callback: Callback<void>): void -此接口为系统接口。 +打开文件管理库变更通知,使用callback方式返回异步结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENTS - **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------- | ---- | ---------------------------------- | -| type | [VirtualAlbumType](#virtualalbumtype) | 是 | 系统相册类型 | -| callback | AsyncCallback> | 是 | 异步获取VirtualAlbum数组之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更 | +| callback | Callback<void> | 是 | 回调返回空 | **示例:** ```ts -async function getPrivateAlbumDemoCallback() { - console.info('getPrivateAlbumDemo') - userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => { - if (err == undefined) { - console.info('getPrivateAlbum ok'); - try { - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - } catch (err) { - console.info('getFileAssets failed. message = ', err); - } - // Get file count in trash album - let count = fetchResult.getCount(); - console.info('fetchResult count = ', count) - // Get fileAssets in trash album - let trashAsset = await fetchResult.getFirstObject(); - // Get file trashed date - let isTrash = trashAsset.isTrash(); - console.info('is trashed', isTrash) - } else { - console.info('getPrivateAlbum failed. message = ', err); - } +async function example() { + console.info('onDemo') + userFileMgr.on('imageChange', () => { + // image file had changed, do something }); } ``` -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType): Promise +### off -获取系统相册,使用 Promise 方式返回系统相册的数组。 +off(type: ChangeEvent, callback?: Callback<void>): void -此接口为系统接口。 +关闭文件管理库变更通知,使用callback方式返回异步结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENTS - **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------- | ---- | ------------ | -| type | [VirtualAlbumType](#virtualalbumtype) | 是 | 系统相册类型 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------- | --------------------------------- | -| Promise> | Promise实例,返回VirtualAlbum数组 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更 | +| callback | Callback<void> | 否 | 回调返回空 | **示例:** ```ts -async function getPrivateAlbumDemoPromise() { - console.info('getPrivateAlbumDemo'); - try { - var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - } catch(err) { - console.info('getPrivateAlbum failed. message = ', err); - } - try { - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - } catch (err) { - console.info('getFileAssets failed. message = ', err); - } - // Get file count in trash album - let count = fetchResult.getCount(); - console.info('fetchResult count = ', count) - // Get fileAssets in trash album - let trashAsset = await fetchResult.getFirstObject(); - - // Get file trashed date - let isTrash = trashAsset.isTrash(); - console.info('is trashed', isTrash) +async function example() { + console.info('offDemo') + userFileMgr.off('imageChange', () => { + // stop listening success + }); } ``` ### getActivePeers -getActivePeers(callback: AsyncCallback>): void; +getActivePeers(callback: AsyncCallback<Array<PeerInfo>>): void; 获取在线对端设备的信息,使用callback方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback> | 是 | 系统相册类型 | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表 | **示例:** ```ts -async function getActivePeersDemoCallback() { - console.info('getActivePeersDemo') - var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => { - if (err == undefined) { - console.log('getActivePeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('getActivePeers failed. message = ', err) - } - }); +async function example() { + console.info('getActivePeersDemo') + mgr.getActivePeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getActivePeers failed. message = ', err) + } + }); } ``` ### getActivePeers -getActivePeers(): Promise>; +getActivePeers(): Promise<Array<PeerInfo>>; 获取在线对端设备的信息,使用promise方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **返回值:** | 类型 | 说明 | | --------------------------- | ----------------------------- | -| Promise> | Promise实例,返回在线设备列表 | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回在线设备列表 | **示例:** ```ts -async function getActivePeersDemoPromise() { - console.info('getActivePeersDemo') - try { - var devicesInfo = await userFileMgr.getActivePeers(); - } catch (err) { - console.info('getActivePeers failed. message = ', err) - } - if (devicesInfo != undefined) { - console.log('getActivePeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('get distributed fail') +async function example() { + console.info('getActivePeersDemo') + try { + var devicesInfo = await mgr.getActivePeers(); + } catch (err) { + console.info('getActivePeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } + } else { + console.info('get distributed fail') + } } ``` ### getAllPeers -getAllPeers(callback: AsyncCallback>): void; +getAllPeers(callback: AsyncCallback<Array<PeerInfo>>): void; 获取所有对端设备的信息,使用callback方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback> | 是 | 系统相册类型 | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表 | **示例:** ```ts -async function getAllPeersDemoCallback() { - console.info('getAllPeersDemo') - var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => { - if (err == undefined) { - console.log('getAllPeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('getAllPeers failed. message = ', err) - } - }); +async function example() { + console.info('getAllPeersDemo') + mgr.getAllPeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getAllPeers failed. message = ', err) + } + }); } ``` ### getAllPeers -getAllPeers(): Promise>; +getAllPeers(): Promise<Array<PeerInfo>>; 获取所有对端设备的信息,使用promise方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **返回值:** | 类型 | 说明 | | --------------------------- | ----------------------------- | -| Promise> | Promise实例,返回所有设备列表 | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回所有设备列表 | **示例:** ```ts -async function getAllPeersDemoPromise() { - console.info('getAllPeersDemo') - try { - var devicesInfo = await userFileMgr.getAllPeers(); - } catch (err) { - console.info('getAllPeers failed. message = ', err) - } - if (devicesInfo != undefined) { - console.log('getAllPeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('get distributed fail') +async function example() { + console.info('getAllPeersDemo') + try { + var devicesInfo = await mgr.getAllPeers(); + } catch (err) { + console.info('getAllPeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } + } else { + console.info('get distributed fail') + } } ``` @@ -812,15 +822,15 @@ release(callback: AsyncCallback<void>): void **示例:** ```ts -async function releaseDemoCallback() { - console.info('releaseDemo'); - userFileMgr.release((err) => { - if (err != undefined) { - console.info('release failed. message = ', err); - } else { - console.info('release ok.'); - } - }) +async function example() { + console.info('releaseDemo'); + mgr.release((err) => { + if (err != undefined) { + console.info('release failed. message = ', err); + } else { + console.info('release ok.'); + } + }) } ``` @@ -842,14 +852,14 @@ release(): Promise<void> **示例:** ```ts -async function releaseDemoPromise() { - console.info('releaseDemo'); - try { - await userFileMgr.release(); - console.info('release ok.'); - } catch (err) { - console.info('release failed. message = ', err); - } +async function example() { + console.info('releaseDemo'); + try { + await mgr.release(); + console.info('release ok.'); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -864,79 +874,77 @@ async function releaseDemoPromise() { | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | | uri | string | 是 | 否 | 文件资源uri(如:dataability:///media/image/2) | -| mediaType | [MediaType](#mediatype) | 是 | 否 | 媒体类型 | +| fileType | [FileType](#filetype) | 是 | 否 | 媒体文件类型 | | displayName | string | 是 | 是 | 显示文件名,包含后缀名 | -### isDirectory +### get -isDirectory(callback: AsyncCallback<boolean>): void +get(member: string): MemberType; -判断fileAsset是否为目录,使用callback方式返回异步结果。 +获取FileAsset成员参数 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | ------------------- | -| callback | AsyncCallback<boolean> | 是 | 当前FileAsset是否是目录的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----- | +| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | **示例:** - -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('fileAssetGetDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory((err, isDirectory) => { - // do something - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + let fileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` -### isDirectory +### set -isDirectory():Promise<boolean> +set(member: string, value: string): void; -判断fileAsset是否为目录,使用Promise方式返回异步结果。 +设置FileAsset成员参数 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**返回值:** +**参数:** -| 类型 | 说明 | -| ---------------------- | ---------------------------- | -| Promise<boolean> | Promise实例,返回当前FileAsset是否是目录 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----- | +| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | +| value | string | 是 | 设置成员参数名称,只能修改ImageVideoKey.TITLE的值 | **示例:** - -```js +```ts async function example() { - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('fileAssetSetDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory().then(function(isDirectory){ - console.info("isDirectory result:"+ isDirectory); - }).catch(function(err){ - console.info("isDirectory failed with error:"+ err); - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + fileAsset.set(title.toString(), "newTitle") + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -946,7 +954,7 @@ commitModify(callback: AsyncCallback<void>): void 修改文件的元数据,使用callback方式返回异步结果。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -958,23 +966,28 @@ commitModify(callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.title = 'newtitle'; - asset.commitModify(() => { - console.info('commitModify success'); - }); + console.info('commitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + let fileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle") + fileAsset.commitModify((err) => { + if (err == undefined) { + let newFileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } else { + console.info('commitModify failed, message =', err); + } + }); } ``` @@ -984,7 +997,7 @@ commitModify(): Promise<void> 修改文件的元数据,使用promise方式返回异步结果。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -994,23 +1007,29 @@ commitModify(): Promise<void> | ------------------- | ---------- | | Promise<void> | Promise返回空 | -**示例:** +**示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.title = 'newtitle'; - asset.commitModify(); + console.info('commitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + let fileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle") + try { + await fileAsset.commitModify() + let newFileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -1022,7 +1041,7 @@ open(mode: string, callback: AsyncCallback<number>): void **注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放 -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1036,20 +1055,18 @@ open(mode: string, callback: AsyncCallback<number>): void **示例:** -```js +```ts async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); - const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw', (openError, fd) => { - if(fd > 0){ - asset.close(fd); - }else{ - console.info('File Open Failed!' + openError); - } - }); + console.info('openDemo') + const fileAsset = await mgr.createPhotoAsset("image00003.jpg"); + fileAsset.open('rw', (err, fd) => { + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd) + } else { + console.info('File err' + err); + } + }); } ``` @@ -1061,7 +1078,7 @@ open(mode: string): Promise<number> **注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放 -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1079,20 +1096,21 @@ open(mode: string): Promise<number> **示例:** -```js +```ts async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); - const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw') - .then((fd) => { - console.info('File fd!' + fd); - }) - .catch((err) => { - console.info('File err!' + err); - }); + console.info('openDemo') + try { + const fileAsset = await mgr.createPhotoAsset("image00003.jpg"); + let fd = await fileAsset.open('rw') + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd) + } else { + console.info(' open File fail'); + } + } catch (err) { + console.info('open Demo err' + err); + } } ``` @@ -1113,33 +1131,29 @@ close(fd: number, callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('closeDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.open('rw').then((fd) => { - console.info('File fd!' + fd); - asset.close(fd, (closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } - }); - }) - .catch((err) => { - console.info('File err!' + err); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let fd = await fileAsset.open('rw'); + console.info('file fd', fd); + fileAsset.close(fd, (err) => { + if (err == undefined) { + console.info('asset close succeed.'); + } else { + console.info('close failed, message = ' + err); + } }); + } catch (err) { + console.info('close failed, message = ' + err); + } } ``` @@ -1165,34 +1179,24 @@ close(fd: number): Promise<void> **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('closeDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.open('rw').then((fd) => { - console.info('File fd!' + fd); - asset.close(fd).then((closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - - } else { - console.info("=======asset.close success====>"); - } - }); - }) - .catch((err) => { - console.info('File err!' + err); - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + let fd = await asset.open('rw'); + console.info('file fd', fd); + await asset.close(fd) + console.info('asset close succeed.'); + } catch (err) { + console.info('close failed, message = ' + err); + } } ``` @@ -1202,7 +1206,7 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void 获取文件的缩略图,使用callback方式返回异步结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1214,22 +1218,24 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail((err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }); + console.info('getThumbnailDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName) + asset.getThumbnail((err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); + } + }); } ``` @@ -1239,7 +1245,7 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void 获取文件的缩略图,传入缩略图尺寸,使用callback方式返回异步结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1247,402 +1253,159 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------- | -| size | [Size](#size) | 是 | 缩略图尺寸 | +| size | Size | 是 | 缩略图尺寸 | | callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | **示例:** -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let size = { width: 720, height: 720 }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size, (err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }); -} -``` - -### getThumbnail - -getThumbnail(size?: Size): Promise<image.PixelMap> - -获取文件的缩略图,传入缩略图尺寸,使用promise方式返回异步结果。 - -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---- | -------------- | ---- | ----- | -| size | [Size](#size) | 否 | 缩略图尺寸 | - -**返回值:** - -| 类型 | 说明 | -| ----------------------------- | --------------------- | -| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let size = { width: 720, height: 720 }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size) - .then((pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }) - .catch((err) => { - console.info('mediaLibraryTest : getThumbnail fail'+ err); - }); -} -``` - -### favorite - -favorite(isFavorite: boolean, callback: AsyncCallback<void>): void - -将文件设置为收藏文件,使用callback方式返回异步结果。 - -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ---------------------------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true,function(err){ - // do something - }); -} -``` - -### favorite - -favorite(isFavorite: boolean): Promise<void> - -将文件设置为收藏文件,使用promise方式返回异步结果。 - -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------- | ---- | ---------------------------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ---------- | -| Promise<void> | Promise返回空 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true).then(function() { - console.info("favorite successfully"); - }).catch(function(err){ - console.info("favorite failed with error:"+ err); - }); -} -``` - -### isFavorite - -isFavorite(callback: AsyncCallback<boolean>): void - -判断该文件是否为收藏文件,使用callback方式返回异步结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | ----------- | -| callback | AsyncCallback<boolean> | 是 | 回调表示是否为收藏文件 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite((err, isFavorite) => { - if (isFavorite) { - console.info('FileAsset is favorite'); - }else{ - console.info('FileAsset is not favorite'); - } - }); -} -``` - -### isFavorite - -isFavorite():Promise<boolean> - -判断该文件是否为收藏文件,使用promise方式返回异步结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**返回值:** - -| 类型 | 说明 | -| ---------------------- | ------------------ | -| Promise<boolean> | Promise回调表示是否是收藏文件 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite().then(function(isFavorite){ - console.info("isFavorite result:"+ isFavorite); - }).catch(function(err){ - console.info("isFavorite failed with error:"+ err); - }); -} -``` - -### trash - -trash(isTrash: boolean, callback: AsyncCallback<void>): void - -当文件被定位时,将文件放到垃圾文件夹,使用callback方式返回异步结果。 - -放入垃圾文件夹的文件不会被真正删除,可以通过isTrash = false参数恢复成正常文件。 - -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | --------- | -| isTrash | boolean | 是 | 是否设置为垃圾文件 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | - -**示例:** - -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.trash(true, trashCallBack); - function trashCallBack(err, trash) { - console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); + console.info('getThumbnailDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName) + asset.getThumbnail(size, (err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); } + }); } ``` -### trash - -trash(isTrash: boolean): Promise<void> +### getThumbnail -当文件被定位时,将文件放到垃圾文件夹,使用promise方式返回异步结果。 +getThumbnail(size?: Size): Promise<image.PixelMap> -放入垃圾文件夹的文件不会被真正删除,可以通过isTrash = false参数恢复成正常文件。 +获取文件的缩略图,传入缩略图尺寸,使用promise方式返回异步结果。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | --------- | -| isTrash | boolean | 是 | 是否设置为垃圾文件 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | -------------- | ---- | ----- | +| size | Size | 否 | 缩略图尺寸 | **返回值:** -| 类型 | 说明 | -| ------------------- | ---------- | -| Promise<void> | Promise返回空 | +| 类型 | 说明 | +| ----------------------------- | --------------------- | +| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.trash(true).then(function() { - console.info("trash successfully"); - }).catch(function(err){ - console.info("trash failed with error:"+ err); - }); + console.info('getThumbnailDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName) + asset.getThumbnail(size).then((pixelMap) => { + console.info('getThumbnail successful ' + pixelMap); + }).catch((err) => { + console.info('getThumbnail fail' + err); + }); } ``` -### isTrash +### favorite + +favorite(isFavorite: boolean, callback: AsyncCallback<void>): void -isTrash(callback: AsyncCallback<boolean>): void +将文件设置为收藏文件,使用callback方式返回异步结果。 -当文件被定位,判断文件是否为垃圾文件,使用callback方式返回异步结果。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | --------------- | -| callback | AsyncCallback<boolean> | 是 | 回调返回表示文件是否为垃圾文件 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------------------------- | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isTrash((err, isTrash) => { - if (isTrash == undefined) { - console.error('Failed to get trash state: ' + err); - return; - } - console.info('Get trash state success: ' + isTrash); - }); + console.info('favoriteDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true, (err) => { + if (err == undefined) { + console.info("favorite successfully"); + } else { + console.info("favorite failed with error:" + err); + } + }); } ``` -### isTrash +### favorite + +favorite(isFavorite: boolean): Promise<void> -isTrash():Promise<boolean> +将文件设置为收藏文件,使用promise方式返回异步结果。 -当文件被定位,判断文件是否为垃圾文件,使用promise方式返回异步结果。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ---- | ---------------------------------- | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | + **返回值:** -| 类型 | 说明 | -| ------------------- | -------------------- | -| Promise<void> | Promise回调表示文件是否为垃圾文件 | +| 类型 | 说明 | +| ------------------- | ---------- | +| Promise<void> | Promise返回空 | **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isTrash().then(function(isTrash){ - console.info("isTrash result: " + isTrash); - }).catch(function(err){ - console.error("isTrash failed with error: " + err); - }); + console.info('favoriteDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true).then(function () { + console.info("favorite successfully"); + }).catch(function (err) { + console.info("favorite failed with error:" + err); + }); } ``` -## FetchFileResult +## FetchResult 文件检索结果集。 @@ -1662,19 +1425,17 @@ getCount(): number **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.FILE; - let getFileCountOneOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp); - const fetchCount = fetchFileResult.getCount(); + console.info('getCountDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('fetchCount = ', fetchCount) } ``` @@ -1694,31 +1455,22 @@ isAfterLast(): boolean **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); - let fileAsset = await fetchFileResult.getFirstObject(); - for (var i = 1; i < fetchCount; i++) { - fileAsset = await fetchFileResult.getNextObject(); - if(i == fetchCount - 1) { - console.info('mediaLibraryTest : isLast'); - var result = fetchFileResult.isAfterLast(); - console.info('mediaLibraryTest : isAfterLast:' + result); - console.info('mediaLibraryTest : isAfterLast end'); - fetchFileResult.close(); - } - } + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('count:' + fetchCount); + let fileAsset = await fetchResult.getLastObject(); + if (!fetchResult.isAfterLast()) { + console.info('fileAsset isAfterLast displayName = ', fileAsset.displayName); + } else { + console.info('fileAsset not isAfterLast '); + } } ``` @@ -1732,27 +1484,25 @@ close(): void **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.close(); + console.info('fetchResultCloseDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.close(); + console.info('close succeed.') } ``` ### getFirstObject -getFirstObject(callback: AsyncCallback<FileAsset>): void +getFirstObject(callback: AsyncCallback<T>): void -获取文件检索结果中的第一个文件资产。此方法使用回调返回FileAsset。 +获取文件检索结果中的第一个文件资产。此方法使用callback形式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1760,37 +1510,34 @@ getFirstObject(callback: AsyncCallback<FileAsset>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步获取结果集中第一个FileAsset完成后的回调 | +| callback | AsyncCallback<T> | 是 | 异步获取结果集中的第一个完成后的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getFirstObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getFirstObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getFirstObject -getFirstObject(): Promise<FileAsset> +getFirstObject(): Promise<T> -获取文件检索结果中的第一个文件资产。此方法使用Promise方式返回FileAsset。 +获取文件检索结果中的第一个文件资产。此方法使用promise方式来异步返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1798,33 +1545,27 @@ getFirstObject(): Promise<FileAsset> | 类型 | 说明 | | --------------------------------------- | -------------------------- | -| Promise<[FileAsset](#fileasset)> | Promise方式返回FileAsset。 | +| Promise<T> | Promise方式返回。 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getFirstObject().then(function(fileAsset){ - console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); - }).catch(function(err){ - console.info("getFirstObject failed with error:"+ err); - }); + console.info('getFirstObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAsset displayName: ', fileAsset.displayName) } ``` ### getNextObject - getNextObject(callback: AsyncCallback<FileAsset>): void + getNextObject(callback: AsyncCallback<T>): void 获取文件检索结果中的下一个文件资产。此方法使用callback形式返回结果。 @@ -1834,37 +1575,37 @@ async function example() { | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------------- | ---- | ----------------------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步返回结果集中下一个FileAsset之后的回调 | +| callbacke | AsyncCallback<T> | 是 | 异步返回结果集中下一个之后的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getNextObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + fetchResult.getNextObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); + } } ``` ### getNextObject - getNextObject(): Promise<FileAsset> + getNextObject(): Promise<T> -获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回FileAsset。 +获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1872,33 +1613,32 @@ async function example() { | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 返回FileAsset对象 | +| Promise<T> | 返回结果集中下一个对象 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); - let fileAsset = await fetchFileResult.getNextObject(); + console.info('getNextObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + let fileAsset = await fetchResult.getNextObject(); + console.info('fileAsset displayName: ', fileAsset.displayName) + } } ``` ### getLastObject -getLastObject(callback: AsyncCallback<FileAsset>): void +getLastObject(callback: AsyncCallback<T>): void -获取文件检索结果中的最后一个文件资产。此方法使用callback回调来返回FileAsset。 +获取文件检索结果中的最后一个文件资产。此方法使用callback回调来返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1906,37 +1646,34 @@ getLastObject(callback: AsyncCallback<FileAsset>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步返回FileAsset之后的回调 | +| callback | AsyncCallback<T> | 是 | 异步返回结果集中最后一个的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getLastObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getLastObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getLastObject -getLastObject(): Promise<FileAsset> +getLastObject(): Promise<T> -获取文件检索结果中的最后一个文件资产。此方法使用Promise方式来返回FileAsset。 +获取文件检索结果中的最后一个文件资产。此方法使用Promise方式来返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1944,31 +1681,29 @@ getLastObject(): Promise<FileAsset> | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 返回FileAsset对象 | +| Promise<T> | 返回结果集中最后一个对象 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - let lastObject = await fetchFileResult.getLastObject(); + console.info('getLastObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getLastObject(); + console.info('fileAsset displayName: ', fileAsset.displayName) } ``` ### getPositionObject -getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void +getPositionObject(index: number, callback: AsyncCallback<T>): void -获取文件检索结果中具有指定索引的文件资产。此方法使用回调来返回FileAsset。 +获取文件检索结果中具有指定索引的文件资产。此方法使用callback来返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1977,35 +1712,32 @@ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------ | | index | number | 是 | 要获取的文件的索引,从0开始 | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步返回FileAsset之后的回调 | +| callback | AsyncCallback<T> | 是 | 异步返回指定索引的文件资产的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getPositionObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getPositionObject(0, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getPositionObject -getPositionObject(index: number): Promise<FileAsset> +getPositionObject(index: number): Promise<T> 获取文件检索结果中具有指定索引的文件资产。此方法使用Promise形式返回文件Asset。 @@ -2021,27 +1753,21 @@ getPositionObject(index: number): Promise<FileAsset> | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 返回FileAsset对象 | +| Promise<T> | 返回指定索引的文件资产的对象 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }).catch(function (err) { - console.info("getFileAssets failed with error:" + err); - }); + console.info('getPositionObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getPositionObject(0); + console.info('fileAsset displayName: ', fileAsset.displayName) } ``` @@ -2059,16 +1785,98 @@ async function example() { | albumUri | string | 是 | 否 | 相册Uri | | dateModified | number | 是 | 否 | 修改日期 | | count | number | 是 | 否 | 相册中文件数量 | -| relativePath | string | 是 | 否 | 相对路径 | | coverUri | string | 是 | 否 | 封面文件Uri +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +获取相册中的文件。该方法使用callback形式来返回文件 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回图片和视频数据结果集| + +**示例**: + +```ts +async function example() { + console.info('albumGetFileAssetsDemoCallback') + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { + if (albumFetchResult != undefined) { + console.info("album getPhotoAssets successfully, getCount:" + albumFetchResult.getCount()); + } else { + console.info("album getPhotoAssets failed with error:" + err); + } + }); +} +``` +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +获取相册中的文件。该方法使用Promise来返回文件 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| Promise | [FetchResult](#fetchresult)<[FileAsset](#fileasset)> | 是 | 图片和视频数据结果集 | + +**示例**: + +```ts +async function example() { + console.info('albumGetFileAssetsDemoPromise') + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption).then((albumFetchResult) => { + console.info("album getFileAssets successfully, getCount:" + albumFetchResult.getCount()); + }).catch((err) => { + console.info("album getFileAssets failed with error:" + err); + }); +} +``` + ### commitModify commitModify(callback: AsyncCallback<void>): void; 更新相册属性修改到数据库中。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -2081,28 +1889,22 @@ commitModify(callback: AsyncCallback<void>): void; **示例**: ```ts -async function commitModifyDemoCallback() { - console.info('commitModifyDemo') - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: '', - selectionArgs: [], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); - let asset = await fetchFileResult.getFirstObject(); - console.info('old displayName:', asset.displayName) - asset.displayName = 'newDisplayName'; - console.info('new displayName:', asset.displayName) - asset.commitModify((err) => { - if (err == undefined) { - console.info('commitModify succeed.') - } else { - console.info('commitModify failed, message =', err); - } - }); +async function example() { + console.info('albumCommitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify((err) => { + if (err != undefined) { + console.info("commitModify failed with error:" + err); + } else { + console.info("commitModify successfully"); + } + }); } ``` @@ -2112,7 +1914,7 @@ commitModify(): Promise<void>; 更新相册属性修改到数据库中。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -2125,265 +1927,323 @@ commitModify(): Promise<void>; **示例**: ```ts -async function commitModifyDemoPromise() { - console.info('commitModifyDemo') - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: '', - selectionArgs: [], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); - let asset = await fetchFileResult.getFirstObject(); - console.info('old displayName:', asset.displayName) - asset.displayName = 'newDisplayName'; - console.info('new displayName:', asset.displayName) - try { - await asset.commitModify(); - console.info('commitModify succeed.') - } catch (err) { - console.info('commitModify failed, message =', err); - } +async function example() { + console.info('albumCommitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + var albumList = await mgr.getPhotoAlbums(albumFetchOptions); + } catch (err) { + console.info('getPhotoAlbums failed. message = ', err); + } + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info("commitModify successfully"); + }).catch((err) => { + console.info("commitModify failed with error:" + err); + }); } ``` -### getFileAssets +## PrivateAlbum +系统相册 + +### 属性 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------ | ------ | ---- | ---- | ------- | +| albumName | string | 是 | 是 | 相册名称 | +| albumUri | string | 是 | 否 | 相册Uri | +| dateModified | number | 是 | 否 | 修改日期 | +| count | number | 是 | 否 | 相册中文件数量 | +| coverUri | string | 是 | 否 | 封面文件Uri + +### getPhotoAssets -getFileAssets(type: Array<MediaType>, callback: AsyncCallback<FetchFileResult>): void; +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -按照检索条件获取相册中的文件。此方法使用Callback回调来返回文件结果集。 +获取系统相册中的文件。该方法使用callback形式来返回文件 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回图片和视频数据结果集 | **示例**: ```ts -async function albumGetFileAssetsDemoCallback() { - console.info('albumGetFileAssetsDemoCallback2') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], (err, albumFetchFileResult) => { - if (err == undefined) { - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - } else { - console.info("getFileAssets failed with error:"+ err); - } - }); +async function example() { + console.info('privateAlbumGetFileAssetsDemoCallback') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + trashAlbum.getPhotoAssets(fetchOption, (err, fetchResult) => { + if (fetchResult != undefined) { + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); + } else { + console.info('getFileAssets failed, message = ', err); + } + }); } -``` -### getFileAssets +``` +### getPhotoAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -按照检索条件获取相册中的文件。此方法使用Callback回调来返回文件结果集。 +获取系统相册中的文件。该方法使用Promise来返回文件 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 媒体检索选项。 | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | + +**返回值**: + +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise:[FetchResult](#fetchresult)<[FileAsset](#fileasset)>| 图片和视频数据结果集 | **示例**: ```ts -async function albumGetFileAssetsDemoCallback() { - console.info('albumGetFileAssetsDemoCallback') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - } - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => { - if (err == undefined) { - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - } else { - console.info("getFileAssets failed with error:"+ err); - } - }); - } +async function example() { + console.info('privateAlbumGetFileAssetsDemoPromise') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); +} ``` +### delete + +delete(uri: string, callback: AsyncCallback<void>): void; -### getFileAssets +删除系统相册中的文件 -getFileAssets(type: Array<MediaType>, options?: MediaFetchOptions): Promise<FetchFileResult>; +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | +| callback | AsyncCallback<void> | 是 | 回调返回空 | + +**示例**: + +```ts +async function example() { + console.info('privateAlbumDeleteCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.delete failed, message = ', err); + } else { + console.info('trashAlbum.delete successfully'); + } + }); +} +``` +### delete -按照检索条件获取相册中的文件。此方法使用异步Promise来返回文件结果集。 +delete(uri: string): Promise<void>; -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +删除系统相册中的文件 +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ---------------------------------------- | ---- | -------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -|options | [MediaFetchOptions](#mediafetchoptions) | 否 | 媒体检索选项。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | **返回值**: -| 类型 | 说明 | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | 返回FetchFileResult对象。 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| 回调返回空 | **示例**: ```ts -async function albumGetFileAssetsDemoPromise() { - console.info('albumGetFileAssetsDemoPromise') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - } - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - }).catch(function(err){ - console.info("getFileAssets failed with error:"+ err); - }); -} +async function example() { + console.info('privateAlbumDeleteDemoPromise') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri).then(() => { + console.info('trashAlbum.delete successfully'); + }).catch((err) => { + console.info('trashAlbum.delete failed, message = ', err); + }); +} ``` -## VirtualAlbum -虚拟相册 - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; -按照检索条件获取虚拟相册中的文件。此方法使用Callback回调来返回文件结果集。 +### recover -此接口为系统接口。 +recover(uri: string, callback: AsyncCallback<void>): void; -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENTS +恢复系统相册中的文件 -> 说明: -> 本接口所需申请的分类的权限APL等级为system_basic。APL等级为normal的应用需要通过ACL证书方式申请,申请方式请参考[ACL说明](../../security/accesstoken-overview.md#访问控制列表acl说明) -> -> 建议通过options参数显式地指定要访问的文件类型。若无法判断文件类型,则会根据应用实际申请的权限返回对应的文件资源结果集。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 媒体检索选项。 | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 | + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例**: ```ts -async function virtualAlbumGetFileAssetsDemoCallback() { - console.info('virtualAlbumGetFileAssetsDemoCallback') - try { - var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - } catch (err) { - console.info('getPrivateAlbum failed, message = ', err); +async function example() { + console.info('privateAlbumRecoverDemoCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.recover failed, message = ', err); + } else { + console.info('trashAlbum.recover successfully'); } - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - - trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => { - if (err == undefined) { - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); - } else { - console.info('getFileAssets failed, message = ', err); - } - }); + }); } ``` +### recover -### getFileAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; - -按照检索条件获取虚拟相中的文件。此方法使用异步Promise来返回文件结果集。 +recover(uri: string): Promise<void>; -此接口为系统接口。 +恢复系统相册中的文件 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENTS - -> 说明: -> 本接口所需申请的分类的权限APL等级为system_basic。APL等级为normal的应用需要通过ACL证书方式申请,申请方式请参考[ACL说明](../../security/accesstoken-overview.md#访问控制列表acl说明) -> -> 建议通过options参数显式地指定要访问的文件类型。若无法判断文件类型,则会根据应用实际申请的权限返回对应的文件资源结果集。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ---------------------------------------- | ---- | -------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -|options | [MediaFetchOptions](#mediafetchoptions) | 否 | 媒体检索选项。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | **返回值**: -| 类型 | 说明 | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | 返回FetchFileResult对象。 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| 回调返回空 | **示例**: ```ts -async function virtualAlbumGetFileAssetsDemoPromise() { - console.info('virtualAlbumGetFileAssetsDemoPromise') - let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - - let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); +async function example() { + console.info('privateAlbumRecoverDemoPromise') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri).then(() => { + console.info('trashAlbum.recover successfully'); + }).catch((err) => { + console.info('trashAlbum.recover failed, message = ', err); + }); } ``` +## MemberType + +成员类型。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore + +| 名称 | 类型 | +| ----- | ---- | +| number | number | +| string | string | +| boolean | boolean | + +## ChangeEvent + +变更监听的媒体文件类型。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore + +| 名称 | 说明 | +| ----- | ---- | +| deviceChange | 设备 | +| albumChange | 相册 | +| imageChange | 图片 | +| audioChange | 音频 | +| videoChange | 视频 | +| remoteFileChange | 远程文件 | + ## PeerInfo 注册设备的信息。 -此接口为系统接口。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore @@ -2393,33 +2253,31 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | networkId | string | 是 | 否 | 注册设备的网络ID | | isOnline | boolean | 是 | 否 | 是否在线 | -## MediaType -枚举,媒体类型。 +## FileType + +枚举,媒体文件类型。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core | 名称 | 说明 | | ----- | ---- | -| FILE | 文件 | | IMAGE | 图片 | | VIDEO | 视频 | | AUDIO | 音频 | -## FileKey +## PrivateAlbumType -枚举,文件关键信息。 +枚举,系统相册类型。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core -| 名称 | 默认值 | 说明 | -| ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | 文件uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | -| DISPLAY_NAME | display_name | 显示名字 | -| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | -| TITLE | title | 文件标题 | +| 名称 | 说明 | +| ----- | ---- | +| TYPE_FAVORITE | 收藏夹相册 | +| TYPE_TRASH | 回收站相册 | + + ## AudioKey @@ -2430,7 +2288,6 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | 名称 | 默认值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | 文件uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | | DISPLAY_NAME | display_name | 显示名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | @@ -2438,6 +2295,7 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | ARTIST | artist | 作者 | | AUDIOALBUM | audio_album | 专辑 | | DURATION | duration | 持续时间(单位:毫秒) | +| FAVORITE | favorite | 收藏 | ## ImageVideoKey @@ -2448,14 +2306,17 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | 名称 | 默认值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | 文件uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | +| FILE_TYPE | file_type | 媒体文件类型 | | DISPLAY_NAME | display_name | 显示名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| TITLE | title | 文件标题 | | DURATION | duration | 持续时间(单位:毫秒) | | WIDTH | width | 图片宽度(单位:像素) | | HEIGHT | height | 图片高度(单位:像素) | | DATE_TAKEN | date_taken | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) | +| ORIENTATION | orientation | 图片文件的方向 | +| FAVORITE | favorite | 收藏 | ## AlbumKey @@ -2466,56 +2327,30 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | 名称 | 默认值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | 相册uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | -| DISPLAY_NAME | display_name | 显示名字 | +| FILE_TYPE | file_type | 媒体文件类型 | +| ALBUM_NAME | album_name | 相册名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | -## DirectoryType -枚举,目录类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core - -| 名称 | 说明 | -| ------------- | ------------------ | -| DIR_CAMERA | 表示Camera文件路径 | -| DIR_VIDEO | 表示视频路径 | -| DIR_IMAGE | 表示图片路径 | -| DIR_AUDIO | 表示音频路径 | -| DIR_DOCUMENTS | 表示文档路径 | -| DIR_DOWNLOAD | 表示下载路径 | - -## MediaFetchOptions +## FetchOptions 检索条件。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core -| 名称 | 类型 | 可读 | 可写 | 必填 | 说明 | -| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | 是 | 是 | 是 | 检索条件,使用[FileKey](#filekey)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?‘, | -| selectionArgs | Array<string> | 是 | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | - -## Size - -图片尺寸。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ | ---- | ---- | -------- | -| width | number | 是 | 是 | 宽(单位:像素) | -| height | number | 是 | 是 | 高(单位:像素) | +| 名称 | 类型 | 必填 | 说明 | +| ---------------------- | ------------------- | ---- |------------------------------------------------ | +| fetchColumns | Array<string> | 是 | 检索条件,指定列名查询,如果该参数为空时默认查询uri、name、fileType。示例:
fetchColumns: "uri"| +| predicates | [dataSharePredicates.DataSharePredicates](#../js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | -## VirtualAlbumType -枚举,系统相册或虚拟相册类型 +## AlbumFetchOptions -以下接口均为系统接口。 +相册检索条件。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core -| 名称 | 说明 | -| ------------- | ------------------ | -| TYPE_FAVORITE | 系统相册:收藏夹相册
该接口为系统接口。 | -| TYPE_TRASH | 系统相册:回收站相册
该接口为系统接口。 | +| 名称 | 类型 | 必填 | 说明 | +| ---------------------- | ------------------- | ---- |------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](#../js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index f6da5fb4ba68285030323fca83358f37d28de624..5cd067c6b35ba8ad40797c1156e16c9f73cbbdf0 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -14,7 +14,38 @@ import util from '@ohos.util'; ``` -## util.printf +## util.format9+ + +format(format: string, ...args: Object[]): string + +通过式样化字符串对输入的内容按特定格式输出。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------- | ---- | -------------- | +| format | string | 是 | 式样化字符串。 | +| ...args | Object[] | 否 | 待式样化数据。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| string | 按特定格式式样化后的字符串。 | + +**示例:** + + ```js +let res = util.format("%s", "hello world!"); +console.log(res); + ``` + +## util.printf(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[util.format9+](#utilformat9)替代。 printf(format: string, ...args: Object[]): string @@ -27,7 +58,7 @@ printf(format: string, ...args: Object[]): string | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | format | string | 是 | 式样化字符串。 | -| ...args | Object[] | 否 | 待式样化数据。 | +| ...args | Object[] | 否 | 替换式样化字符串通配符的数据。 | **返回值:** @@ -41,8 +72,38 @@ printf(format: string, ...args: Object[]): string console.log(res); ``` +## util.errnoToString9+ + +errnoToString(errno: number): string + +获取系统错误码对应的详细信息。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------- | +| errno | number | 是 | 系统发生错误产生的错误码。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------- | +| string | 错误码对应的详细信息。 | + +**示例:** + + ```js +let errnum = 10; // 10 : a system error number +let result = util.errnoToString(errnum); +console.log("result = " + result); + ``` + +## util.getErrorString(deprecated) -## util.getErrorString +> **说明:**
+> 从API Version 9开始废弃,建议使用[util.errnoToString9+](#utilerrnotostring9)替代。 getErrorString(errno: number): string @@ -69,7 +130,6 @@ getErrorString(errno: number): string console.log("result = " + result); ``` - ## util.callbackWrapper callbackWrapper(original: Function): (err: Object, value: Object )=>void @@ -103,30 +163,6 @@ callbackWrapper(original: Function): (err: Object, value: Object )=>void }, err) ``` - -## util.promiseWrapper(deprecated) - -promiseWrapper(original: (err: Object, value: Object) => void): Object - -> **说明:**
-> 从API Version 9开始废弃,建议使用[util.promisify9+](#utilpromisify9)替代。 - -对异步函数处理并返回一个promise的版本。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| original | Function | 是 | 异步函数。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| Function | 采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | - ## util.promisify9+ promisify(original: (err: Object, value: Object) => void): Function @@ -162,6 +198,29 @@ promisify(original: (err: Object, value: Object) => void): Function }) ``` +## util.promiseWrapper(deprecated) + +promiseWrapper(original: (err: Object, value: Object) => void): Object + +> **说明:**
+> 从API Version 9开始废弃,建议使用[util.promisify9+](#utilpromisify9)替代。 + +对异步函数处理并返回一个promise的版本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| original | Function | 是 | 异步函数。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Function | 采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | + ## util.randomUUID9+ randomUUID(entropyCache?: boolean): string @@ -244,7 +303,7 @@ parseUUID(uuid: string): Uint8Array console.log(JSON.stringify(uuid)); // 输出: // 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156 - ``` + ``` ## TextDecoder @@ -258,8 +317,45 @@ parseUUID(uuid: string): Uint8Array | fatal | boolean | 是 | 否 | 是否显示致命错误。 | | ignoreBOM | boolean | 是 | 否 | 是否忽略BOM(byte order marker)标记,默认值为false ,表示解码结果包含BOM标记。 | +### constructor9+ -### constructor +constructor() + +TextDecoder的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +### create9+ + +create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): TextDecoder; + +替代有参构造功能。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------ | +| encoding | string | 否 | 编码格式。 | +| options | Object | 否 | 编码相关选项参数,存在两个属性fatal和ignoreBOM。 | + + **表1.1**options + +| 名称 | 参数类型 | 必填 | 说明 | +| --------- | -------- | ---- | ------------------ | +| fatal | boolean | 否 | 是否显示致命错误。 | +| ignoreBOM | boolean | 否 | 是否忽略BOM标记。 | + +**示例:** + + ```js +let textDecoder = new util.TextDecoder() +textDecoder.create('utf-8', { ignoreBOM : true }); + ``` + +### constructor(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) @@ -286,7 +382,6 @@ TextDecoder的构造函数。 let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); ``` - ### decode decode(input: Uint8Array, options?: { stream?: false }): string @@ -397,8 +492,39 @@ TextEncoder的构造函数。 let textEncoder = new util.TextEncoder(); ``` +### encodeInto9+ + +encodeInto(input?: string): Uint8Array + +通过输入参数编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| input | string | 是 | 需要编码的字符串。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ------------------ | +| Uint8Array | 返回编码后的文本。 | + +**示例:** + + ```js +let textEncoder = new util.TextEncoder(); +let buffer = new ArrayBuffer(20); +let result = new Uint8Array(buffer); +result = textEncoder.encodeInto("\uD800¥¥"); + ``` + +### encode(deprecated) -### encode +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeInto9+](#encodeinto9)替代。 encode(input?: string): Uint8Array @@ -426,8 +552,41 @@ encode(input?: string): Uint8Array result = textEncoder.encode("\uD800¥¥"); ``` +### encodeIntoUint8Array9+ + +encodeIntoUint8Array(input: string, dest: Uint8Array, ): { read: number; written: number } + +放置生成的UTF-8编码文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ------------------------------------------------------- | +| input | string | 是 | 需要编码的字符串。 | +| dest | Uint8Array | 是 | Uint8Array对象实例,用于将生成的UTF-8编码文本放入其中。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ------------------ | +| Uint8Array | 返回编码后的文本。 | + +**示例:** + + ```js +let that = new util.TextEncoder() +let buffer = new ArrayBuffer(4) +let dest = new Uint8Array(buffer) +let result = new Object() +result = that.encodeInto('abcd', dest) + ``` + +### encodeInto(deprecated) -### encodeInto +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeIntoUint8Array9+](#encodeintouint8array9)替代。 encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } @@ -459,8 +618,46 @@ encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } ## RationalNumber8+ +### constructor9+ -### constructor8+ +constructor() + +RationalNumber的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(); + ``` + +### parseRationalNumber9+ + +parseRationalNumber(numerator: number,denominator: number) + +替代原有参构造的参数处理。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ---------------- | +| numerator | number | 是 | 分子,整数类型。 | +| denominator | number | 是 | 分母,整数类型。 | + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(); +rationalNumber.parseRationalNumber(1,2) + ``` + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor(numerator: number,denominator: number) @@ -476,11 +673,11 @@ RationalNumber的构造函数。 | denominator | number | 是 | 分母,整数类型。 | **示例:** + ```js let rationalNumber = new util.RationalNumber(1,2); ``` - ### createRationalFromString8+ static createRationalFromString​(rationalString: string): RationalNumber​ @@ -507,8 +704,38 @@ static createRationalFromString​(rationalString: string): RationalNumber​ let rational = util.RationalNumber.createRationalFromString("3/4"); ``` +### compare9+ + +compare​(another: RationalNumber): number​ + +将当前的RationalNumber对象与给定的对象进行比较。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------- | ---- | ------------------ | +| another | RationalNumber | 是 | 其他的有理数对象。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------------------------------------ | +| number | 如果两个对象相等,则返回0;如果给定对象小于当前对象,则返回1;如果给定对象大于当前对象,则返回-1。 | + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compare(rational); + ``` + +### compareTo8+(deprecated) -### compareTo8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[compare9+](#compare9)替代。 compareTo​(another: RationalNumber): number​ @@ -535,7 +762,6 @@ compareTo​(another: RationalNumber): number​ let result = rationalNumber.compareTo(rational); ``` - ### valueOf8+ valueOf(): number @@ -556,7 +782,6 @@ valueOf(): number let result = rationalNumber.valueOf(); ``` - ### equals8+ equals​(obj: Object): boolean @@ -584,8 +809,37 @@ equals​(obj: Object): boolean let result = rationalNumber.equals(rational); ``` +### getCommonFactor9+ + +getCommonFactor(number1: number,number2: number): number + +获取两个指定整数的最大公约数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ---------- | +| number1 | number | 是 | 整数类型。 | +| number2 | number | 是 | 整数类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------ | +| number | 返回两个给定数字的最大公约数。 | + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonFactor(4,6); + ``` -### getCommonDivisor8+ +### getCommonDivisor8+(deprecated) +> **说明:**
+> 从API Version 9开始废弃,建议使用[getCommonFactor9+](#getcommonfactor9)替代。 static getCommonDivisor​(number1: number,number2: number): number @@ -612,7 +866,6 @@ static getCommonDivisor​(number1: number,number2: number): number let result = util.RationalNumber.getCommonDivisor(4,6); ``` - ### getNumerator8+ getNumerator​(): number @@ -633,7 +886,6 @@ getNumerator​(): number let result = rationalNumber.getNumerator(); ``` - ### getDenominator8+ getDenominator​(): number @@ -654,7 +906,6 @@ getDenominator​(): number let result = rationalNumber.getDenominator(); ``` - ### isZero8+ isZero​():boolean @@ -675,7 +926,6 @@ isZero​():boolean let result = rationalNumber.isZero(); ``` - ### isNaN8+ isNaN​(): boolean @@ -696,7 +946,6 @@ isNaN​(): boolean let result = rationalNumber.isNaN(); ``` - ### isFinite8+ isFinite​():boolean @@ -717,7 +966,6 @@ isFinite​():boolean let result = rationalNumber.isFinite(); ``` - ### toString8+ toString​(): string @@ -738,26 +986,27 @@ toString​(): string let result = rationalNumber.toString(); ``` -## LruBuffer8+ + +## LRUCache9+ ### 属性 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| length | number | 是 | 否 | 当前缓冲区中值的总数。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ---------------------- | +| length | number | 是 | 否 | 当前缓冲区中值的总数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(1,8); - let result = pro.length; +let pro = new util.LRUCache(); +pro.put(2,10); +pro.put(1,8); +let result = pro.length; ``` - -### constructor8+ +### constructor9+ constructor(capacity?: number) @@ -767,17 +1016,18 @@ constructor(capacity?: number) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| capacity | number | 否 | 指示要为缓冲区自定义的容量。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ---------------------------- | +| capacity | number | 否 | 指示要为缓冲区自定义的容量。 | **示例:** + ```js - let lrubuffer= new util.LruBuffer(); +let lrubuffer= new util.LRUCache(); ``` -### updateCapacity8+ +### updateCapacity9+ updateCapacity(newCapacity: number): void @@ -787,18 +1037,19 @@ updateCapacity(newCapacity: number): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| newCapacity | number | 是 | 指示要为缓冲区自定义的容量。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ---------------------------- | +| newCapacity | number | 是 | 指示要为缓冲区自定义的容量。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.updateCapacity(100); +let pro = new util.LRUCache(); +let result = pro.updateCapacity(100); ``` -### toString8+ +### toString9+ toString(): string @@ -808,21 +1059,22 @@ toString(): string **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | -------------------------- | | string | 返回对象的字符串表示形式。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - pro.remove(20); - let result = pro.toString(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +let result = pro.toString(); ``` -### getCapacity8+ +### getCapacity9+ getCapacity(): number @@ -832,18 +1084,19 @@ getCapacity(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | ---------------------- | | number | 返回当前缓冲区的容量。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.getCapacity(); +let pro = new util.LRUCache(); +let result = pro.getCapacity(); ``` -### clear8+ +### clear9+ clear(): void @@ -852,15 +1105,16 @@ clear(): void **系统能力:** SystemCapability.Utils.Lang **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.length; - pro.clear(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.length; +pro.clear(); ``` -### getCreateCount8+ +### getCreateCount9+ getCreateCount(): number @@ -870,19 +1124,20 @@ getCreateCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | --------------------------------- | | number | 返回createDefault()返回值的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(1,8); - let result = pro.getCreateCount(); +let pro = new util.LRUCache(); +pro.put(1,8); +let result = pro.getCreateCount(); ``` -### getMissCount8+ +### getMissCount9+ getMissCount(): number @@ -892,20 +1147,21 @@ getMissCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | ------------------------ | | number | 返回查询值不匹配的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMissCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.get(2); +let result = pro.getMissCount(); ``` -### getRemovalCount8+ +### getRemovalCount9+ getRemovalCount(): number @@ -915,21 +1171,22 @@ getRemovalCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | -------------------------- | | number | 返回从缓冲区中驱逐的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.updateCapacity(2); - pro.put(50,22); - let result = pro.getRemovalCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +let result = pro.getRemovalCount(); ``` -### getMatchCount8+ +### getMatchCount9+ getMatchCount(): number @@ -939,20 +1196,21 @@ getMatchCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | -------------------------- | | number | 返回查询值匹配成功的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMatchCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.get(2); +let result = pro.getMatchCount(); ``` -### getPutCount8+ +### getPutCount9+ getPutCount(): number @@ -962,19 +1220,20 @@ getPutCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | ---------------------------- | | number | 返回将值添加到缓冲区的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.getPutCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.getPutCount(); ``` -### isEmpty8+ +### isEmpty9+ isEmpty(): boolean @@ -984,19 +1243,20 @@ isEmpty(): boolean **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------- | ---------------------------------------- | | boolean | 如果当前缓冲区不包含任何值,则返回true。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.isEmpty(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.isEmpty(); ``` -### get8+ +### get9+ get(key: K): V | undefined @@ -1006,25 +1266,26 @@ get(key: K): V | undefined **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 要查询的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------ | +| key | K | 是 | 要查询的键。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------------------------ | ------------------------------------------------------------ | | V \| undefined | 如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.get(2); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.get(2); ``` -### put8+ +### put9+ put(key: K,value: V): V @@ -1034,24 +1295,25 @@ put(key: K,value: V): V **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 要添加的密钥。 | -| value | V | 是 | 指示与要添加的键关联的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------------------- | +| key | K | 是 | 要添加的密钥。 | +| value | V | 是 | 指示与要添加的键关联的值。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| V | 返回与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | +| 类型 | 说明 | +| ---- | ------------------------------------------------------------ | +| V | 返回与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.put(2,10); +let pro = new util.LRUCache(); +let result = pro.put(2,10); ``` -### values8+ +### values9+ values(): V[] @@ -1061,21 +1323,22 @@ values(): V[] **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------- | ------------------------------------------------------------ | | V [] | 按从最近访问到最近最少访问的顺序返回当前缓冲区中所有值的列表。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(2,"anhu"); - pro.put("afaf","grfb"); - let result = pro.values(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +let result = pro.values(); ``` -### keys8+ +### keys9+ keys(): K[] @@ -1085,19 +1348,20 @@ keys(): K[] **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------- | ------------------------------------------------------------ | | K [] | 按升序返回当前缓冲区中所有键的列表,从最近访问到最近最少访问。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.keys(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.keys(); ``` -### remove8+ +### remove9+ remove(key: K): V | undefined @@ -1107,25 +1371,26 @@ remove(key: K): V | undefined **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 要删除的密钥。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------- | +| key | K | 是 | 要删除的密钥。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------------------------ | ------------------------------------------------------------ | | V \| undefined | 返回一个包含已删除键值对的Optional对象;如果key不存在,则返回一个空的Optional对象,如果key为null,则抛出异常。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.remove(20); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.remove(20); ``` -### afterRemoval8+ +### afterRemoval9+ afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void @@ -1135,36 +1400,37 @@ afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| isEvict | boolean | 否 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 | -| key | K | 是 | 表示删除的键。 | -| value | V | 是 | 表示删除的值。 | -| newValue | V | 否 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ------------------------------------------------------------ | +| isEvict | boolean | 否 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 | +| key | K | 是 | 表示删除的键。 | +| value | V | 是 | 表示删除的值。 | +| newValue | V | 否 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 | **示例:** + ```js - let arr = []; - class ChildLruBuffer extends util.LruBuffer - { - constructor() - { - super(); - } - afterRemoval(isEvict, key, value, newValue) - { - if (isEvict === false) - { - arr = [key, value, newValue]; - } - } - } - let lru = new ChildLruBuffer(); - lru.afterRemoval(false,10,30,null); +let arr = []; +class ChildLruBuffer extends util.LRUCache +{ + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } +} +let lru = new ChildLruBuffer(); +lru.afterRemoval(false,10,30,null); ``` -### contains8+ +### contains9+ contains(key: K): boolean @@ -1174,136 +1440,1067 @@ contains(key: K): boolean **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 表示要检查的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ---------------- | +| key | K | 是 | 表示要检查的键。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------ | +| boolean | 如果缓冲区包含指定的键,则返回 true。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.contains(20); + ``` + + +### createDefault9+ + +createDefault(key: K): V + +如果未计算特定键的值,则执行后续操作,参数表示丢失的键,返回与键关联的值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------- | +| key | K | 是 | 表示丢失的键。 | + +**返回值:** + +| 类型 | 说明 | +| ---- | ------------------ | +| V | 返回与键关联的值。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +let result = pro.createDefault(50); + ``` + + +### entries9+ + +entries(): IterableIterator<[K,V]> + +允许迭代包含在这个对象中的所有键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ----------- | -------------------- | +| [K, V] | 返回一个可迭代数组。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.entries(); + ``` + +### [Symbol.iterator]9+ + +[Symbol.iterator]\(): IterableIterator<[K, V]> + +返回一个键值对形式的二维数组。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ----------- | ------------------------------ | +| [K, V] | 返回一个键值对形式的二维数组。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro[Symbol.iterator](); + ``` + +## LruBuffer8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[LRUCache9+](#lrucache9)替代。 + +### 属性 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | 当前缓冲区中值的总数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(1,8); + let result = pro.length; + ``` + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 + +constructor(capacity?: number) + +默认构造函数用于创建一个新的LruBuffer实例,默认容量为64。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| capacity | number | 否 | 指示要为缓冲区自定义的容量。 | + +**示例:** + ```js + let lrubuffer= new util.LruBuffer(); + ``` + +### updateCapacity8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[updateCapacity9+](#updatecapacity9)替代。 + +updateCapacity(newCapacity: number): void + +将缓冲区容量更新为指定容量,如果newCapacity小于或等于0,则抛出异常。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| newCapacity | number | 是 | 指示要为缓冲区自定义的容量。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.updateCapacity(100); + ``` + +### toString8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[toString9+](#tostring9)替代。 + +toString(): string + +返回对象的字符串表示形式。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 返回对象的字符串表示形式。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + pro.remove(20); + let result = pro.toString(); + ``` + +### getCapacity8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getCapacity9+](#getcapacity9)替代。 + +getCapacity(): number + +获取当前缓冲区的容量。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回当前缓冲区的容量。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.getCapacity(); + ``` + +### clear8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[clear9+](#clear9)替代。 + +clear(): void + +从当前缓冲区清除键值对。后续会调用afterRemoval()方法执行后续操作。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.length; + pro.clear(); + ``` + +### getCreateCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getCreateCount9+](#getcreatecount9)替代。 + +getCreateCount(): number + +获取createDefault()返回值的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回createDefault()返回值的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(1,8); + let result = pro.getCreateCount(); + ``` + +### getMissCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getMissCount9+](#getmisscount9)替代。 + +getMissCount(): number + +获取查询值不匹配的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回查询值不匹配的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMissCount(); + ``` + +### getRemovalCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getRemovalCount9+](#getremovalcount9)替代。 + +getRemovalCount(): number + +获取从缓冲区中逐出值的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回从缓冲区中驱逐的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.updateCapacity(2); + pro.put(50,22); + let result = pro.getRemovalCount(); + ``` + +### getMatchCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getMatchCount9+](#getmatchcount9)替代。 + +getMatchCount(): number + +获取查询值匹配成功的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回查询值匹配成功的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMatchCount(); + ``` + +### getPutCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getPutCount9+](#getputcount9)替代。 + +getPutCount(): number + +获取将值添加到缓冲区的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回将值添加到缓冲区的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.getPutCount(); + ``` + +### isEmpty8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[isEmpty9+](#isempty9)替代。 + +isEmpty(): boolean + +检查当前缓冲区是否为空。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 如果当前缓冲区不包含任何值,则返回true。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.isEmpty(); + ``` + +### get8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[get9+](#get9)替代。 + +get(key: K): V | undefined + +表示要查询的键。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 要查询的键。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V \| undefined | 如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.get(2); + ``` + +### put8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[put9+](#put9)替代。 + +put(key: K,value: V): V + +将键值对添加到缓冲区。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 要添加的密钥。 | +| value | V | 是 | 指示与要添加的键关联的值。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V | 返回与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.put(2,10); + ``` + +### values8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[values9+](#values9)替代。 + +values(): V[] + +获取当前缓冲区中所有值从最近访问到最近最少访问的顺序列表 。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V [] | 按从最近访问到最近最少访问的顺序返回当前缓冲区中所有值的列表。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(2,"anhu"); + pro.put("afaf","grfb"); + let result = pro.values(); + ``` + +### keys8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[keys9+](#keys9)替代。 + +keys(): K[] + +获取当前缓冲区中所有键从最近访问到最近最少访问的升序列表。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| K [] | 按升序返回当前缓冲区中所有键的列表,从最近访问到最近最少访问。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.keys(); + ``` + +### remove8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[remove9+](#remove9)替代。 + +remove(key: K): V | undefined + +从当前缓冲区中删除指定的键及其关联的值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 要删除的密钥。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V \| undefined | 返回一个包含已删除键值对的Optional对象;如果key不存在,则返回一个空的Optional对象,如果key为null,则抛出异常。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.remove(20); + ``` + +### afterRemoval8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[afterRemoval9+](#afterremoval9)替代。 + +afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void + +删除值后执行后续操作。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| isEvict | boolean | 否 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 | +| key | K | 是 | 表示删除的键。 | +| value | V | 是 | 表示删除的值。 | +| newValue | V | 否 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 | + +**示例:** + ```js + let arr = []; + class ChildLruBuffer extends util.LruBuffer + { + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } + } + let lru = new ChildLruBuffer(); + lru.afterRemoval(false,10,30,null); + ``` + +### contains8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[contains9+](#contains9)替代。 + +contains(key: K): boolean + +检查当前缓冲区是否包含指定的键。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 表示要检查的键。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 如果缓冲区包含指定的键,则返回 true。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.contains(20); + ``` + +### createDefault8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[createDefault9+](#createdefault9)替代。 + +createDefault(key: K): V + +如果未计算特定键的值,则执行后续操作,参数表示丢失的键,返回与键关联的值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 表示丢失的键。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V | 返回与键关联的值。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.createDefault(50); + ``` + +### entries8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[entries9+](#entries9)替代。 + +entries(): IterableIterator<[K,V]> + +允许迭代包含在这个对象中的所有键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| [K, V] | 返回一个可迭代数组。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.entries(); + ``` + +### [Symbol.iterator]8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[Symbol.iterator9+](#symboliterator9)替代。 + +[Symbol.iterator]\(): IterableIterator<[K, V]> + +返回一个键值对形式的二维数组。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| [K, V] | 返回一个键值对形式的二维数组。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro[Symbol.iterator](); + ``` + +### ScopeType8+ + +用于表示范围中的值的类型。该类型的值,类型可以为ScopeComparable或number。 + +ScopeComparable类型的值需要实现compareTo方法,确保传入的数据具有可比性。 +```js +interface ScopeComparable{ + compareTo(other: ScopeComparable): boolean; +} +type ScopeType = ScopeComparable | number; +``` + + +构造新类,实现compareTo方法。后续示例代码中,均通过Temperature,获取[ScopeType](#scopetype8)的实例化对象。 + + +示例: +```js +class Temperature{ + constructor(value){ + // 当使用ts语言开发时,需要补充以下代码: + // private readonly _temp: Temperature; + this._temp = value; + } + compareTo(value){ + return this._temp >= value.getTemp(); + } + getTemp(){ + return this._temp; + } + toString(){ + return this._temp.toString(); + } +} +``` + +## ScopeHelper9+ + +### constructor9+ + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +用于创建指定下限和上限的作用域实例的构造函数,返回一个ScopeHelper对象。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------------- | +| lowerObj | [ScopeType](#scopetype8) | 是 | 指定作用域实例的下限。 | +| upperObj | [ScopeType](#scopetype8) | 是 | 指定作用域实例的上限。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); + ``` + + +### toString9+ + +toString(): string + +该字符串化方法返回一个包含当前范围的字符串表示形式。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------------------------- | +| string | 返回包含当前范围对象的字符串表示形式。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.toString(); + ``` + + +### intersect9+ + +intersect(range: ScopeHelper): ScopeHelper + +获取给定范围和当前范围的交集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ------------------ | +| range | [ScopeHelper9+](#scopehelper9) | 是 | 传入一个给定范围。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | ------------------------------ | +| [ScopeHelper9+](#scopehelper9) | 返回给定范围和当前范围的交集。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +range.intersect(rangeFir ); + ``` + + +### intersect9+ + +intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper + +获取当前范围与给定下限和上限范围的交集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | 是 | 给定范围的下限。 | +| upperObj | [ScopeType](#scopetype8) | 是 | 给定范围的上限。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | ---------------------------------------- | +| [ScopeHelper9+](#scopehelper9) | 返回当前范围与给定下限和上限范围的交集。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.intersect(tempMiDF, tempMidS); + ``` + + +### getUpper9+ + +getUpper(): ScopeType + +获取当前范围的上限。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | 返回当前范围的上限值。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getUpper(); + ``` + + +### getLower9+ + +getLower(): ScopeType + +获取当前范围的下限。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | 返回当前范围的下限值。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getLower(); + ``` + + +### expand9+ + +expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper + +创建并返回包括当前范围和给定下限和上限的并集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | 是 | 给定范围的下限。 | +| upperObj | [ScopeType](#scopetype8) | 是 | 给定范围的上限。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | ------------------------------------ | +| [ScopeHelper9+](#scopehelper9) | 返回当前范围和给定下限和上限的并集。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF, tempMidS); + ``` + + +### expand9+ + +expand(range: ScopeHelper): ScopeHelper + +创建并返回包括当前范围和给定范围的并集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ------------------ | +| range | [ScopeHelper9+](#scopehelper9) | 是 | 传入一个给定范围。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| boolean | 如果缓冲区包含指定的键,则返回 true。 | +| 类型 | 说明 | +| ------------------------------ | ---------------------------------- | +| [ScopeHelper9+](#scopehelper9) | 返回包括当前范围和给定范围的并集。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.contains(20); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +let result = range.expand(rangeFir); ``` -### createDefault8+ +### expand9+ -createDefault(key: K): V +expand(value: ScopeType): ScopeHelper -如果未计算特定键的值,则执行后续操作,参数表示丢失的键,返回与键关联的值。 +创建并返回包括当前范围和给定值的并集。 **系统能力:** SystemCapability.Utils.Lang **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 表示丢失的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | 是 | 传入一个给定值。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| V | 返回与键关联的值。 | +| 类型 | 说明 | +| ------------------------------ | -------------------------------- | +| [ScopeHelper9+](#scopehelper9) | 返回包括当前范围和给定值的并集。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.createDefault(50); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF); ``` -### entries8+ +### contains9+ -entries(): IterableIterator<[K,V]> +contains(value: ScopeType): boolean -允许迭代包含在这个对象中的所有键值对。 +检查给定value是否包含在当前范围内。 **系统能力:** SystemCapability.Utils.Lang +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | 是 | 传入一个给定值。 | + **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| [K, V] | 返回一个可迭代数组。 | +| 类型 | 说明 | +| ------- | --------------------------------------------------- | +| boolean | 如果给定值包含在当前范围内返回true,否则返回false。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.entries(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +range.contains(tempMiDF); ``` -### [Symbol.iterator]8+ +### contains9+ -[Symbol.iterator]\(): IterableIterator<[K, V]> +contains(range: ScopeHelper): boolean -返回一个键值对形式的二维数组。 +检查给定range是否在当前范围内。 **系统能力:** SystemCapability.Utils.Lang +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ------------------ | +| range | [ScopeHelper9+](#scopehelper9) | 是 | 传入一个给定范围。 | + **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| [K, V] | 返回一个键值对形式的二维数组。 | +| 类型 | 说明 | +| ------- | ----------------------------------------------------- | +| boolean | 如果给定范围包含在当前范围内返回true,否则返回false。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro[Symbol.iterator](); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempLess = new Temperature(20); +let tempMore = new Temperature(45); +let rangeSec = new util.ScopeHelper(tempLess, tempMore); +let result = range.contains(rangeSec); ``` -## Scope8+ +### clamp9+ +clamp(value: ScopeType): ScopeType -### ScopeType8+ +将给定值限定到当前范围内。 -用于表示范围中的值的类型。该类型的值,类型可以为ScopeComparable或number。 +**系统能力:** SystemCapability.Utils.Lang -ScopeComparable类型的值需要实现compareTo方法,确保传入的数据具有可比性。 -```js -interface ScopeComparable{ - compareTo(other: ScopeComparable): boolean; -} -type ScopeType = ScopeComparable | number; -``` +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | -------------- | +| value | [ScopeType](#scopetype8) | 是 | 传入的给定值。 | -构造新类,实现compareTo方法。后续示例代码中,均通过Temperature,获取[ScopeType](#scopetype8)的实例化对象。 +**返回值:** +| 类型 | 说明 | +| ------------------------ | ------------------------------------------------------------ | +| [ScopeType](#scopetype8) | 如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value。 | -示例: -```js -class Temperature{ - constructor(value){ - // 当使用ts语言开发时,需要补充以下代码: - // private readonly _temp: Temperature; - this._temp = value; - } - compareTo(value){ - return this._temp >= value.getTemp(); - } - getTemp(){ - return this._temp; - } - toString(){ - return this._temp.toString(); - } -} -``` +**示例:** + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.clamp(tempMiDF); + ``` -### constructor8+ +## Scope8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[ScopeHelper9+](#scopehelper9)替代。 + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor(lowerObj: ScopeType, upperObj: ScopeType) @@ -1325,8 +2522,10 @@ constructor(lowerObj: ScopeType, upperObj: ScopeType) let range = new util.Scope(tempLower, tempUpper); ``` +### toString8+(deprecated) -### toString8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[toString9+](#tostring9)替代。 toString(): string @@ -1348,8 +2547,10 @@ toString(): string let result = range.toString(); ``` +### intersect8+(deprecated) -### intersect8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[intersect9+](#intersect9)替代。 intersect(range: Scope): Scope @@ -1370,6 +2571,7 @@ intersect(range: Scope): Scope | [Scope](#scope8) | 返回给定范围和当前范围的交集。 | **示例:** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -1380,8 +2582,10 @@ intersect(range: Scope): Scope range.intersect(rangeFir ); ``` +### intersect8+(deprecated) -### intersect8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[intersect9+](#intersect9)替代。 intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope @@ -1412,8 +2616,10 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope let result = range.intersect(tempMiDF, tempMidS); ``` +### getUpper8+(deprecated) -### getUpper8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[getUpper9+](#getupper9)替代。 getUpper(): ScopeType @@ -1435,8 +2641,10 @@ getUpper(): ScopeType let result = range.getUpper(); ``` +### getLower8+(deprecated) -### getLower8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[getLower9+](#getlower9)替代。 getLower(): ScopeType @@ -1458,8 +2666,10 @@ getLower(): ScopeType let result = range.getLower(); ``` +### expand8+(deprecated) -### expand8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[expand9+](#expand9)替代。 expand(lowerObj: ScopeType,upperObj: ScopeType): Scope @@ -1491,8 +2701,10 @@ expand(lowerObj: ScopeType,upperObj: ScopeType): Scope let result = range.expand(tempMiDF, tempMidS); ``` +### expand8+(deprecated) -### expand8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[expand9+](#expand9)替代。 expand(range: Scope): Scope @@ -1523,8 +2735,10 @@ expand(range: Scope): Scope let result = range.expand(rangeFir); ``` +### expand8+(deprecated) -### expand8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[expand9+](#expand9)替代。 expand(value: ScopeType): Scope @@ -1553,8 +2767,10 @@ expand(value: ScopeType): Scope let result = range.expand(tempMiDF); ``` +### contains8+(deprecated) -### contains8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[contains9+](#contains9)替代。 contains(value: ScopeType): boolean @@ -1583,8 +2799,10 @@ contains(value: ScopeType): boolean range.contains(tempMiDF); ``` +### contains8+(deprecated) -### contains8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[contains9+](#contains9)替代。 contains(range: Scope): boolean @@ -1605,6 +2823,7 @@ contains(range: Scope): boolean | boolean | 如果给定范围包含在当前范围内返回true,否则返回false。 | **示例:** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -1615,8 +2834,10 @@ contains(range: Scope): boolean let result = range.contains(rangeSec); ``` +### clamp8+(deprecated) -### clamp8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[clamp9+](#clamp9)替代。 clamp(value: ScopeType): ScopeType @@ -1645,11 +2866,217 @@ clamp(value: ScopeType): ScopeType let result = range.clamp(tempMiDF); ``` +## Base64Helper9+ -## Base648+ +### constructor9+ +constructor() -### constructor8+ +Base64Helper的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + + ```js +let base64 = new util.Base64Helper(); + ``` + +### encodeSync9+ + +encodeSync(src: Uint8Array): Uint8Array + +通过输入参数编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | 是 | 编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ----------------------------- | +| Uint8Array | 返回编码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeSync(array); + ``` + + +### encodeToStringSync9+ + +encodeToStringSync(src: Uint8Array): string + +通过输入参数编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | 是 | 编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------- | +| string | 返回编码后的字符串。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeToStringSync(array); + ``` + + +### decodeSync9+ + +decodeSync(src: Uint8Array | string): Uint8Array + +通过输入参数解码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ----------------------------- | +| src | Uint8Array \| string | 是 | 解码输入Uint8数组或者字符串。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ----------------------------- | +| Uint8Array | 返回解码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let buff = 'czEz'; +let result = that.decodeSync(buff); + ``` + + +### encode9+ + +encode(src: Uint8Array): Promise<Uint8Array> + +通过输入参数异步编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | 是 | 异步编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | 返回异步编码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let rarray = new Uint8Array([99,122,69,122]); +that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) + ``` + + +### encodeToString9+ + +encodeToString(src: Uint8Array): Promise<string> + +通过输入参数异步编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | 是 | 异步编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------ | +| Promise<string> | 返回异步编码后的字符串。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +that.encodeToString(array).then(val=>{ + console.log(val) +}) + ``` + + +### decode9+ + +decode(src: Uint8Array | string): Promise<Uint8Array> + +通过输入参数异步解码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | --------------------------------- | +| src | Uint8Array \| string | 是 | 异步解码输入Uint8数组或者字符串。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | 返回异步解码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([99,122,69,122]); +let rarray = new Uint8Array([115,49,51]); +that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) + ``` + + +## Base648+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[Base64Helper9+](#base64helper9)替代。 + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor() @@ -1662,8 +3089,10 @@ Base64的构造函数。 let base64 = new util.Base64(); ``` +### encodeSync8+(deprecated) -### encodeSync8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeSync9+](#encodesync9)替代。 encodeSync(src: Uint8Array): Uint8Array @@ -1684,14 +3113,17 @@ encodeSync(src: Uint8Array): Uint8Array | Uint8Array | 返回编码后新分配的Uint8数组。 | **示例:** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); let result = that.encodeSync(array); ``` +### encodeToStringSync8+(deprecated) -### encodeToStringSync8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeToStringSync9+](#encodetostringsync9)替代。 encodeToStringSync(src: Uint8Array): string @@ -1718,8 +3150,10 @@ encodeToStringSync(src: Uint8Array): string let result = that.encodeToStringSync(array); ``` +### decodeSync8+(deprecated) -### decodeSync8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[decodeSync9+](#decodesync9)替代。 decodeSync(src: Uint8Array | string): Uint8Array @@ -1746,8 +3180,10 @@ decodeSync(src: Uint8Array | string): Uint8Array let result = that.decodeSync(buff); ``` +### encode8+(deprecated) -### encode8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encode9+](#encode9)替代。 encode(src: Uint8Array): Promise<Uint8Array> @@ -1779,8 +3215,10 @@ encode(src: Uint8Array): Promise<Uint8Array> }) ``` +### encodeToString8+(deprecated) -### encodeToString8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeToString9+](#encodetostring9)替代。 encodeToString(src: Uint8Array): Promise<string> @@ -1809,8 +3247,10 @@ encodeToString(src: Uint8Array): Promise<string> }) ``` +### decode8+(deprecated) -### decode8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[decode9+](#decode9)替代。 decode(src: Uint8Array | string): Promise<Uint8Array> @@ -1842,7 +3282,6 @@ decode(src: Uint8Array | string): Promise<Uint8Array> }) ``` - ## types8+ @@ -2926,4 +4365,5 @@ isSharedArrayBuffer(value: Object): boolean ```js let that = new util.types(); let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); - ``` \ No newline at end of file + ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-vector.md b/zh-cn/application-dev/reference/apis/js-apis-vector.md index 921c82b5ebd90b46ab78b469c1ad0326026bf651..164f69a071584ae837c07a4ee960e0a553bbd3c7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vector.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -72,7 +72,7 @@ let vector = new Vector(); let result = vector.add("a"); let result1 = vector.add(1); let b = [1, 2, 3]; -vector.add(b); +let result2 = vector.add(b); let c = {name : "Dylon", age : "13"}; let result3 = vector.add(c); ``` @@ -285,8 +285,6 @@ vector.add(4); vector.add(5); vector.add(4); vector.removeByRange(2,4); -vector.removeByRange(4,3); -vector.removeByRange(2,6); ``` ### replaceAllElements @@ -430,9 +428,10 @@ vector.add(2); vector.add(4); vector.add(5); vector.add(4); -let result = vector.subVector(2,4); -let result1 = vector.subVector(4,3); -let result2 = vector.subVector(2,6); +vector.add(6); +vector.add(8); +let result = vector.subVector(0,4); +let result1 = vector.subVector(2,4); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md index 5f4b865d34a2b425b4764373d9ba8b00002fd874..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 eddd6ee8674b491267c08b292dadcbbd1044cd9e..b547ce6a2e72063fd916be7568995a5913aa2566 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webview.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webview.md @@ -28,8 +28,7 @@ close(): void 关闭该消息端口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -47,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 }) } @@ -61,8 +64,7 @@ postMessageEvent(message: string): void 发送消息。完整示例代码参考[postMessage](#postmessage) -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -114,8 +116,7 @@ onMessageEvent(callback: (result: string) => void): void 注册回调函数,接收HTML5侧发送过来的消息。完整示例代码参考[postMessage](#postmessage) -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -178,8 +179,7 @@ loadUrl(url: string | Resource, headers?: Array\): void 加载指定的URL。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -196,7 +196,7 @@ SystemCapability.Web.Webview.Core | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100002 | Invalid url. | -| 17100003 | Invalid resource. | +| 17100003 | Invalid resource path or file type. | **示例:** @@ -231,8 +231,7 @@ loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, his 加载指定的数据。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -289,8 +288,7 @@ accessForward(): boolean 当前页面是否可前进,即当前页面是否有前进历史记录。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -340,8 +338,7 @@ forward(): void 按照历史栈,前进一个页面。一般结合accessForward一起使用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -384,8 +381,7 @@ accessBackward(): boolean 当前页面是否可后退,即当前页面是否有返回历史记录。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -435,8 +431,7 @@ backward(): void 按照历史栈,后退一个页面。一般结合accessBackward一起使用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -479,8 +474,7 @@ onActive(): void 调用此接口通知Web组件进入前台激活状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -523,8 +517,7 @@ onInactive(): void 调用此接口通知Web组件进入未激活状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -566,8 +559,7 @@ refresh(): void 调用此接口通知Web组件刷新网页。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -610,8 +602,7 @@ accessStep(step: number): boolean 当前页面是否可前进或者后退给定的step步。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -668,8 +659,7 @@ clearHistory(): void 删除所有前进后退记录。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -712,8 +702,7 @@ getHitTest(): HitTestTypeV9 获取当前被点击区域的元素类型。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -763,8 +752,7 @@ registerJavaScriptProxy(object: object, name: string, methodList: Array\ 注入JavaScript对象到window对象中,并在window对象中调用该对象的方法。注册后,须调用[refresh](#refresh)接口生效。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -824,8 +812,7 @@ runJavaScript(script: string, callback : AsyncCallback\): void 异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果。runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -888,8 +875,7 @@ runJavaScript(script: string): Promise\ 异步执行JavaScript脚本,并通过Promise方式返回脚本执行的结果。runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -953,8 +939,7 @@ deleteJavaScriptRegister(name: string): void 删除通过registerJavaScriptProxy注册到window上的指定name的应用侧JavaScript对象。删除后立即生效,无须调用[refresh](#refresh)接口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1005,8 +990,7 @@ zoom(factor: number): void 调整当前网页的缩放比例。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1021,8 +1005,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 17100004 | Cannot delete JavaScriptProxy. | -| 17100009 | Cannot zoom in or zoom out. | +| 17100004 | Function not enable. | **示例:** @@ -1058,8 +1041,7 @@ searchAllAsync(searchString: string): void 异步查找网页中所有匹配关键字'searchString'的内容并高亮,结果通过[onSearchResultReceive](../arkui-ts/ts-basic-components-web.md#onsearchresultreceive9)异步返回。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1113,8 +1095,7 @@ clearMatches(): void 清除所有通过[searchAllAsync](#searchallasync)匹配到的高亮字符查找结果。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -1157,8 +1138,7 @@ searchNext(forward: boolean): void 滚动到下一个匹配的查找结果并高亮。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1207,8 +1187,7 @@ clearSslCache(): void 清除Web组件记录的SSL证书错误事件对应的用户操作行为。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -1251,8 +1230,7 @@ clearClientAuthenticationCache(): void 清除Web组件记录的客户端证书请求事件对应的用户操作行为。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -1295,8 +1273,7 @@ struct WebComponent { 创建Web消息端口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1347,8 +1324,7 @@ postMessage(name: string, ports: Array\, uri: string): void 发送Web消息端口到HTML5。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1411,7 +1387,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}`); } @@ -1462,7 +1442,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"); + } } ``` @@ -1472,8 +1456,7 @@ requestFocus(): void 使当前web页面获取焦点。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -1516,8 +1499,7 @@ zoomIn(): void 调用此接口将当前网页进行放大,比例为20%。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -1527,7 +1509,6 @@ SystemCapability.Web.Webview.Core | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100004 | Function not enable. | -| 17100009 | Cannot zoom in or zoom out. | **示例:** @@ -1562,8 +1543,7 @@ zoomOut(): void 调用此接口将当前网页进行缩小,比例为20%。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -1573,7 +1553,6 @@ SystemCapability.Web.Webview.Core | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100004 | Function not enable. | -| 17100009 | Cannot zoom in or zoom out. | **示例:** @@ -1608,8 +1587,7 @@ getHitTestValue(): HitTestValue 获取当前被点击区域的元素信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1660,8 +1638,7 @@ getWebId(): number 获取当前Web组件的索引值,用于多个Web组件的管理。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1711,8 +1688,7 @@ getUserAgent(): string 获取当前默认用户代理。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1762,8 +1738,7 @@ getTitle(): string 获取文件选择器标题。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1813,8 +1788,7 @@ getPageHeight(): number 获取当前网页的页面高度。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1864,8 +1838,7 @@ storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\ 以Promise方式异步保存当前页面。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1991,8 +1963,7 @@ getUrl(): string 获取当前页面的url地址。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2042,8 +2013,7 @@ stop(): void 停止页面加载。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -2086,8 +2056,7 @@ backOrForward(step: number): void 按照历史栈,前进或者后退指定步长的页面,当历史栈中不存在对应步长的页面时,不会进行页面跳转。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2102,7 +2071,6 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 17100007 | Invalid back or forward operation. | **示例:** @@ -2142,8 +2110,7 @@ static getCookie(url: string): string 获取指定url对应cookie的值。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2198,8 +2165,7 @@ static setCookie(url: string, value: string): void 为指定url设置单个cookie的值。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2250,8 +2216,7 @@ static saveCookieAsync(callback: AsyncCallback\): void 将当前存在内存中的cookie异步保存到磁盘中。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2297,8 +2262,7 @@ static saveCookieAsync(): Promise\ 将当前存在内存中的cookie以Promise方法异步保存到磁盘中。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2345,8 +2309,7 @@ static putAcceptCookieEnabled(accept: boolean): void 设置WebCookieManager实例是否拥有发送和接收cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2387,8 +2350,7 @@ static isCookieAllowed(): boolean 获取WebCookieManager实例是否拥有发送和接收cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2426,8 +2388,7 @@ static putAcceptThirdPartyCookieEnabled(accept: boolean): void 设置WebCookieManager实例是否拥有发送和接收第三方cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2468,8 +2429,7 @@ static isThirdPartyCookieAllowed(): boolean 获取WebCookieManager实例是否拥有发送和接收第三方cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2507,8 +2467,7 @@ static existCookie(): boolean 获取是否存在cookie。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2546,8 +2505,7 @@ static deleteEntireCookie(): void 清除所有cookie。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -2578,8 +2536,7 @@ static deleteSessionCookie(): void 清除所有会话cookie。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -2614,8 +2571,7 @@ static deleteOrigin(origin : string): void 清除指定源所使用的存储。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2629,7 +2585,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2667,8 +2623,7 @@ static getOrigins(callback: AsyncCallback\>) : void 以回调方式异步获取当前使用Web SQL数据库的所有源的信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2682,7 +2637,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100012 | Invalid web storage origin. | **示例:** @@ -2729,8 +2684,7 @@ static getOrigins() : Promise\> 以Promise方式异步获取当前使用Web SQL数据库的所有源的信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2744,7 +2698,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100012 | Invalid web storage origin. | **示例:** @@ -2791,8 +2745,7 @@ static getOriginQuota(origin : string, callback : AsyncCallback\) : void 使用callback回调异步获取指定源的Web SQL数据库的存储配额,配额以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2807,7 +2760,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2851,8 +2804,7 @@ static getOriginQuota(origin : string) : Promise\ 以Promise方式异步获取指定源的Web SQL数据库的存储配额,配额以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2872,7 +2824,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2916,8 +2868,7 @@ static getOriginUsage(origin : string, callback : AsyncCallback\) : void 以回调方式异步获取指定源的Web SQL数据库的存储量,存储量以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2932,7 +2883,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2976,8 +2927,7 @@ static getOriginUsage(origin : string) : Promise\ 以Promise方式异步获取指定源的Web SQL数据库的存储量,存储量以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2997,7 +2947,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ----------------------------------------------------- | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3041,8 +2991,7 @@ static deleteAllData(): void 清除Web SQL数据库当前使用的所有存储。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -3082,8 +3031,7 @@ static getHttpAuthCredentials(host: string, realm: string): Array\ 检索给定主机和域的HTTP身份验证凭据,该方法为同步方法。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3138,8 +3086,7 @@ static saveHttpAuthCredentials(host: string, realm: string, username: string, pa 保存给定主机和域的HTTP身份验证凭据,该方法为同步方法。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3185,8 +3132,7 @@ static existHttpAuthCredentials(): boolean 判断是否存在任何已保存的HTTP身份验证凭据,该方法为同步方法。存在返回true,不存在返回false。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -3227,8 +3173,7 @@ static deleteHttpAuthCredentials(): void 清除所有已保存的HTTP身份验证凭据,该方法为同步方法。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -3267,8 +3212,7 @@ static allowGeolocation(origin: string): void 允许指定来源使用地理位置接口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3281,7 +3225,7 @@ SystemCapability.Web.Webview.Core 以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3317,8 +3261,7 @@ static deleteGeolocation(origin: string): void 清除指定来源的地理位置权限状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3332,7 +3275,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3368,8 +3311,7 @@ static getAccessibleGeolocation(origin: string, callback: AsyncCallback\ 以Promise方式异步获取指定源的地理位置权限状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3447,7 +3388,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3488,8 +3429,7 @@ static getStoredGeolocation(callback: AsyncCallback\>): void 以回调方式异步获取已存储地理位置权限状态的所有源信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3537,8 +3477,7 @@ static getStoredGeolocation(): Promise\> 以Promise方式异步获取已存储地理位置权限状态的所有源信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -3585,8 +3524,7 @@ static deleteAllGeolocation(): void 清除所有来源的地理位置权限状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -3615,9 +3553,10 @@ struct WebComponent { } ``` ## HeaderV9 - Web组件返回的请求/响应头对象。 +**系统能力:** SystemCapability.Web.Webview.Core + | 名称 | 类型 | 说明 | | ----------- | ------ | :------------------- | | headerKey | string | 请求/响应头的key。 | @@ -3625,6 +3564,8 @@ Web组件返回的请求/响应头对象。 ## HitTestTypeV9 +**系统能力:** SystemCapability.Web.Webview.Core + | 名称 | 描述 | | ------------- | ----------------------------------------- | | EditText | 可编辑的区域。 | @@ -3640,6 +3581,8 @@ Web组件返回的请求/响应头对象。 提供点击区域的元素信息。示例代码参考getHitTestValue。 +**系统能力:** SystemCapability.Web.Webview.Core + | 名称 | 类型 | 说明 | | ----- | ------------- | :----------------------------------------------------------- | | type | [HitTestTypeV9](#hittesttypev9) | 当前被点击区域的元素类型。 | @@ -3649,8 +3592,7 @@ Web组件返回的请求/响应头对象。 提供Web SQL数据库的使用信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core | 名称 | 类型 | 必填 | 说明 | | ------ | ------ | :--- | -------------------- | 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 2e652be786490c6796e8b9860aabd542ed5e5794..162f75d0804a942d1d97097dbfcc6c006a7b63fb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -777,10 +777,10 @@ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): v **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | -| callback | Callback<[SystemBarTintState](#systembartintstate)> | 是 | 回调函数。返回当前的状态栏、导航栏信息集合。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | +| callback | Callback<[SystemBarTintState](#systembartintstate8)> | 是 | 回调函数。返回当前的状态栏、导航栏信息集合。 | **示例:** @@ -806,10 +806,10 @@ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | -| callback | Callback<[SystemBarTintState](#systembartintstate)> | 否 | 回调函数。返回当前的状态栏、导航栏信息集合。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | +| callback | Callback<[SystemBarTintState](#systembartintstate8)> | 否 | 回调函数。返回当前的状态栏、导航栏信息集合。 | **示例:** @@ -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)); }) @@ -1638,6 +1638,12 @@ resize(width: number, height: number, callback: AsyncCallback<void>): void 改变当前窗口大小,使用callback异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + **系统能力:** SystemCapability.WindowManager.WindowManager.Core **参数:** @@ -1679,6 +1685,12 @@ resize(width: number, height: number): Promise<void> 改变当前窗口大小,使用Promise异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + **系统能力:** SystemCapability.WindowManager.WindowManager.Core **参数:** @@ -1844,7 +1856,7 @@ try { getWindowAvoidArea(type: AvoidAreaType): AvoidArea -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4369,6 +4381,12 @@ resetSize(width: number, height: number, callback: AsyncCallback<void>): v 改变当前窗口大小,使用callback异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + > **说明:** > > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[resize()](#resize9)。 @@ -4401,6 +4419,12 @@ resetSize(width: number, height: number): Promise<void> 改变当前窗口大小,使用Promise异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + > **说明:** > > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[resize()](#resize9-1)。 @@ -4566,7 +4590,7 @@ promise.then((data)=> { getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 > **说明:** > @@ -4598,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 @@ -5829,10 +5853,10 @@ WindowStage生命周期。 | 名称 | 默认值 | 说明 | | ---------- | ------ | ---------- | -| FOREGROUND | 1 | 切到前台。 | +| SHOWN | 1 | 切到前台。 | | ACTIVE | 2 | 获焦状态。 | | INACTIVE | 3 | 失焦状态。 | -| BACKGROUND | 4 | 切到后台。 | +| HIDDEN | 4 | 切到后台。 | ## WindowStage9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 483a26e968c80663a800b432589434dd0e4440c9..b7daa69d0787b677544129f7117517f77fe83a14 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -1495,7 +1495,7 @@ workerInstance.onexit = function() { } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 @@ -1508,7 +1508,7 @@ const parentPort = worker.workerPort parentPort.onmessage = function(e) { // data:主线程发送的信息 let data = e.data; - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); // worker线程向主线程发送信息 parentPort.postMessage("123") @@ -1516,7 +1516,7 @@ parentPort.onmessage = function(e) { // worker线程发生error的回调 parentPort.onerror= function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` build-profile.json5 配置 : @@ -1557,7 +1557,7 @@ workerInstance.onexit = function() { } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 @@ -1567,7 +1567,7 @@ const parentPort = worker.workerPort parentPort.onmessage = function(e) { // data:主线程发送的信息 let data = e.data; - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); // worker线程向主线程发送信息 parentPort.postMessage("123") @@ -1575,7 +1575,7 @@ parentPort.onmessage = function(e) { // worker线程发生error的回调 parentPort.onerror= function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` build-profile.json5 配置: diff --git a/zh-cn/application-dev/reference/apis/js-apis-xml.md b/zh-cn/application-dev/reference/apis/js-apis-xml.md index a9b0b31194d67d5adea06869f9f342079035a209..e137f45c98981154d20a0e2e876ded514bb2f369 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-xml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-xml.md @@ -58,7 +58,9 @@ setAttributes(name: string, value: string): void let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setAttributes("importance", "high"); +thatSer.startElement("note"); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-zlib.md b/zh-cn/application-dev/reference/apis/js-apis-zlib.md index 8138283e12eac6f85872a718f035bf00670afb64..3c85311c4ba3748b49b6d4ce1764531a94f26dcc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-zlib.md +++ b/zh-cn/application-dev/reference/apis/js-apis-zlib.md @@ -13,7 +13,7 @@ import zlib from '@ohos.zlib'; ``` ## zlib.zipFile(deprecated) - zipFile(inFile:string, outFile:string, options: Options): Promise<void> +zipFile(inFile: string, outFile: string, options: Options): Promise<void> 压缩接口(Promise形式)。 @@ -26,7 +26,7 @@ import zlib from '@ohos.zlib'; | 参数名 | 类型 | 必填 | 描述 | | ------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[Stage模型](js-apis-application-context.md) | -| outFile | string | 是 | 指定的压缩结果的文件路径(文件的扩展名zip) | +| outFile | string | 是 | 指定压缩结果的文件路径(文件的扩展名zip) | | options | [Options](#options) | 否 | 压缩的可选参数 | **返回值:** @@ -37,43 +37,41 @@ import zlib from '@ohos.zlib'; **示例1:** -```javascript - +```typescript //【压缩文件 例子1】 -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.zipFile(inFile, outFile, options).then((data) => { - console.log("zipFile result:" + data); -}).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('zipFile result is ' + JSON.Stringify(data)); +}).catch((err) => { + console.log('error is ' + JSON.Stringify(err)); }); - ``` **示例2:** -``` +```typescript // 【压缩文件夹 例子2】 -import zlib from '@ohos.zlib' -var inFile = "/xxx/xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.zipFile(inFile , outFile, options).then((data) => { - console.log("zipFile result:" + data); + console.log('zipFile result is ' + JSON.Stringify(data)); }).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('error is ' + JSON.Stringify(err)); }); ``` @@ -103,11 +101,11 @@ unzipFile(inFile:string, outFile:string, options: Options): Promise<void> **示例:** -```javascript -// 【解压例子1】 -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; +```typescript +// 【解压缩 例子1】 +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, @@ -115,16 +113,15 @@ let options = { strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.unzipFile(inFile, outFile, options).then((data) => { - console.log("unzipFile result:" + data); + console.log('unzipFile result is ' + JSON.Stringify(data)); }).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('error is ' + JSON.Stringify(err)); }) - ``` ## zlib.compressFile9+ -**function** compressFile(inFile: **string**, outFile: **string**, options: Options, callback: AsyncCallback<**void**>): **void**; +compressFile(inFile: string, outFile: string, options: Options, callback: AsyncCallback\): void; 压缩文件,压缩的结果通过callback返回。成功时返回null,失败时返回错误码。 @@ -149,13 +146,13 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { **示例** -```javascript -// 【压缩例子1】 +```typescript +// 【压缩文件 例子1】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY @@ -163,16 +160,16 @@ var options = { try { zlib.compressFile(inFile, outFile, options, (errData) => { - if (erData != null) { - console.log("errData is " + errData.errCode + " " + errData.message) + if (erData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); } }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` -**function** compressFile(inFile:**string**, outFile:**string**, options: Options): Promise<**void**>; +compressFile(inFile: string, outFile: string, options: Options): Promise\; 压缩文件,压缩的结果通过promise返回,成功时返回null,失败时返回错误码。 @@ -180,12 +177,11 @@ try { **参数:** -| 参数名 | 类型 | 必填 | 描述 | -| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | -| outFile | string | 是 | 指定的解压文件路径 | -| options | [Options](#options) | 是 | 压缩的配置参数 | -| AsyncCallback<**void**> | callback | 否 | 压缩时的回调函数 | +| 参数名 | 类型 | 必填 | 描述 | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | +| outFile | string | 是 | 指定的解压文件路径 | +| options | [Options](#options) | 是 | 压缩的配置参数 | **相关错误码** @@ -195,37 +191,39 @@ try { | 900001 | The Input source file is invalid. | | 900002 | The Input destination file is invalid. | -```javascript -// 【压缩例子2】 +```typescript +// 【压缩文件 例子2】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; try { - zlib.compressFile(inFile, outFile, options).then(data => { - console.info("compressFile success") - }).catch(errData => { - console.info("catch err " + errData.errCode + " " + errData.message) + zlib.compressFile(inFile, outFile, options).then((data) => { + console.info('compressFile success'); + }).catch((errData) => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` ## zlib.decompressFile9+ -**function** decompressFile(inFile: **string**, outFile: **string**, options: Options, callback: AsyncCallback<**void**>): **void**; +decompressFile(inFile: string, outFile: string, options: Options, callback: AsyncCallback\): void; 解压文件,解压的结果通过callback返回,成功时返回null,失败时返回错误码。 +**系统能力:** SystemCapability.BundleManager.Zlib + **参数:** | 参数名 | 类型 | 必填 | 描述 | @@ -245,32 +243,35 @@ try { **示例** -```javascript -// 【解压缩例子1】 +```typescript +// 【解压缩 例子1】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; + try { zlib.decompressFile(inFile, outFile, options, (errData) => { - if (erData != null) { - console.log("errData is " + errData.errCode + " " + errData.message) + if (erData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); } }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` -**function** decompressFile(inFile: **string**, outFile: **string**, options: Options): Promise<**void**>; +decompressFile(inFile: string, outFile: string, options: Options): Promise\; 解压文件,解压的结果通过promise返回,成功时返回null,失败时返回错误码。 +**系统能力:** SystemCapability.BundleManager.Zlib + **参数:** | 参数名 | 类型 | 必填 | 描述 | @@ -287,26 +288,27 @@ try { | 900001 | The Input source file is invalid. | | 900002 | The Input destination file is invalid. | -```javascript -// 【解压缩例子2】 +```typescript +// 【解压缩 例子2】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; + try { - zlib.compressFile(inFile, outFile, options).then(data => { - console.info("compressFile success") - }).catch(errData => { - console.info("catch err " + errData.errCode + " " + errData.message) + zlib.deCompressFile(inFile, outFile, options).then((data) => { + console.info('deCompressFile success'); + }).catch((errData) => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` ## Options @@ -319,16 +321,6 @@ try { | memLevel | MemLevel | 否 | 参考[zip.MemLevel枚举定义](#zipmemlevel) | | strategy | CompressStrategy | 否 | 参考[zip.CompressStrategy枚举定义](#zipcompressstrategy) | -## zip.MemLevel - -**系统能力:** SystemCapability.BundleManager.Zlib - -| 名称 | 值 | 说明 | -| ----------------- | ---- | -------------------------------- | -| MEM_LEVEL_MIN | 1 | zip 接口在压缩过程中最小使用内存 | -| MEM_LEVEL_MAX | 9 | zip 接口在压缩过程中最大使用内存 | -| MEM_LEVEL_DEFAULT | 8 | zip 接口在压缩过程中默认使用内存 | - ## zip.CompressLevel **系统能力:** SystemCapability.BundleManager.Zlib @@ -340,6 +332,16 @@ try { | COMPRESS_LEVEL_BEST_COMPRESSION | 9 | 最佳压缩等级 | | COMPRESS_LEVEL_DEFAULT_COMPRESSION | -1 | 默认压缩等级 | +## zip.MemLevel + +**系统能力:** SystemCapability.BundleManager.Zlib + +| 名称 | 值 | 说明 | +| ----------------- | ---- | -------------------------------- | +| MEM_LEVEL_MIN | 1 | zip 接口在压缩过程中最小使用内存 | +| MEM_LEVEL_MAX | 9 | zip 接口在压缩过程中最大使用内存 | +| MEM_LEVEL_DEFAULT | 8 | zip 接口在压缩过程中默认使用内存 | + ## zip.CompressStrategy **系统能力:** SystemCapability.BundleManager.Zlib diff --git a/zh-cn/application-dev/reference/arkui-js/Readme-CN.md b/zh-cn/application-dev/reference/arkui-js/Readme-CN.md index c67743da8b03297fba24172d508281d34d56e64a..7c34e92d3b7f9e55b5c90b2221eebfabd6539ae6 100644 --- a/zh-cn/application-dev/reference/arkui-js/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-js/Readme-CN.md @@ -102,4 +102,5 @@ - [事件参数](js-components-custom-event-parameter.md) - [slot插槽](js-components-custom-slot.md) - [生命周期定义](js-components-custom-lifecycle.md) +- [动态创建组件](js-components-create-elements.md) - [数据类型说明](js-appendix-types.md) diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001127284934.gif b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001127284934.gif deleted file mode 100644 index 6168a14aa67c866abf6185ba3a3c2ae9f595153c..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001127284934.gif and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001176075554.gif b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001176075554.gif new file mode 100644 index 0000000000000000000000000000000000000000..16e7ff213bd5caf5a9802001d3ced2996c66e0bc Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001176075554.gif differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001177265268.png b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001177265268.png deleted file mode 100644 index 2ed837e111c3ac1ba1eafb5b28da581ef4de5d22..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001177265268.png and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_000000117726526811.png b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_000000117726526811.png new file mode 100644 index 0000000000000000000000000000000000000000..d9d9a17fe607c8acc99d3a7e26c6b4316e0b7f5b Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_000000117726526811.png differ diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md index 1bf885a86bb1120ccb2819a402aadac3c7b01ec5..8e8894ff6e0c33cbd3681f8ee9b174bcc1f5f943 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md @@ -64,74 +64,77 @@ ```html -
- {{marqueeCustomData}} -
- - +
+
+ + Life is a journey, not the destination. + +
+
+ +
``` ```css /* xxx.css */ -.container { +.tutorial-page { + width: 750px; + height: 100%; flex-direction: column; - justify-content: center; align-items: center; - background-color: #ffffff; + justify-content: center; } -.customMarquee { - width: 100%; - height: 80px; - padding: 10px; - margin: 20px; - border: 4px solid #ff8888; - border-radius: 20px; - font-size: 40px; - color: #ff8888; - font-weight: bolder; - font-family: serif; - background-color: #ffdddd; +.marqueetext { + font-size: 37px; } -.content { - flex-direction: row; +.mymarquee { + margin-top: 20px; + width:100%; + height: 100px; + margin-left: 50px; + margin-right: 50px; + border: 1px solid #dc0f27; + border-radius: 15px; + align-items: center; } -.controlButton { - flex-grow: 1; - background-color: #F2F2F2; - text-color: #0D81F2; +button{ + width: 200px; + height: 80px; + margin-top: 100px; } ``` ```js // xxx.js export default { - data: { - scrollAmount: 30, - loop: 3, - marqueeDir: 'left', - marqueeCustomData: 'Custom marquee', - }, - onMarqueeBounce: function() { - console.log("onMarqueeBounce"); + private: { + loopval: 1, + scroll: 8, + color1: 'red' }, - onMarqueeStart: function() { - console.log("onMarqueeStart"); + onInit(){ }, - onMarqueeFinish: function() { - console.log("onMarqueeFinish"); + setfinish(e) { + this.loopval= this.loopval + 1, + this.r = Math.floor(Math.random()*255), + this.g = Math.floor(Math.random()*255), + this.b = Math.floor(Math.random()*255), + this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)', + this.$element('testmarquee').start(), + this.loopval= this.loopval - 1 }, - onStartClick (evt) { - this.$element('customMarquee').start(); + makestart(e) { + this.$element('testmarquee').start() }, - onStopClick (evt) { - this.$element('customMarquee').stop(); + makestop(e) { + this.$element('testmarquee').stop() } } ``` -![zh-cn_image_0000001127284934](figures/zh-cn_image_0000001127284934.gif) +![zh-cn_image_0000001176075554](figures/zh-cn_image_0000001176075554.gif) diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md index 3c38f3db2dc824e700b7488b53373b5a83bc7ae1..ae142ab4eef9c42886d9cf1d52b2f12571376f8a 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -165,52 +165,59 @@ ```html
- - - - - - - - - - - + + + + + + + + + +
``` ```css /* xxx.css */ -.container { - flex-direction: column; - justify-content: center; - align-items: center; +.container { + flex-direction: column; + justify-content: center; + align-items: center; } - picker{ - width:60%; - height:80px; - border-radius:20px; - text-color:white; - font-size:15px; - background-color:#4747e3; - margin-left:20%; + +picker { + width: 60%; + height: 80px; + border-radius: 20px; + text-color: white; + font-size: 15px; + background-color: #4747e3; + margin-left: 20%; } - select{ - background-color: #efecec; - height: 50px; - width: 60%; - margin-left: 20%; - margin-top: 300px; - margin-bottom: 50px; - font-size: 22px; + +select { + background-color: #efecec; + height: 50px; + width: 60%; + margin-left: 20%; + margin-top: 300px; + margin-bottom: 50px; + font-size: 22px; } ``` @@ -218,72 +225,96 @@ // xxx.js import router from '@system.router'; import prompt from '@system.prompt'; + export default { - data: { - selectList:["text","data","time","datetime","multitext"], - rangetext:['15', "20", "25"], - multitext:[["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]], - textvalue:'default textvalue', - datevalue:'default datevalue', - timevalue:'default timevalue', - datetimevalue:'default datetimevalue', - multitextvalue:'default multitextvalue', - containsecond:true, - multitextselect:[1,2,0], - datetimeselect:'2012-5-6-11-25', - timeselect:'11:22:30', - dateselect:'2021-3-2', - textselect:'2' - }, - selectChange(e){ - for(let i = 0;i **说明:** +> > 从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 滑动条组件,用来快速调节设置值,如音量、亮度等。 @@ -94,7 +95,7 @@ export default { } else if (e.mode == "end") { this.value = e.value; this.endValue = e.value; - } else if (e.mode == "click) { + } else if (e.mode == "click") { this.value = e.value; this.currentValue = e.value; } diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-badge.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-badge.md index 4548a4b060b3d45f19b93524e7e6509e495b7bc1..6540036839c1a5e73a0b38dbd9bb42ae6c62dbb6 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-badge.md @@ -23,14 +23,14 @@ 除支持[通用属性](js-components-common-attributes.md)外,还支持如下属性: -| 名称 | 类型 | 默认值 | 必填 | 描述 | -| ------------------ | ----------- | -------- | ---- | ---------------------------------------- | -| placement | string | rightTop | 否 | 事件提醒的数字标记或者圆点标记的位置,可选值为:
- right:位于组件右边框。
- rightTop:位于组件边框右上角。
- left:位于组件左边框。 | -| count | number | 0 | 否 | 设置提醒的消息数,默认为0。当设置相应的提醒消息数大于0时,消息提醒会变成数字标记类型,未设置消息数或者消息数不大于0时,消息提醒将采用圆点标记。
当数字设置大于maxcount时,将使用maxcount显示。count属性最大支持整数值为2147483647。 | -| visible | boolean | false | 否 | 是否显示消息提醒,当收到新信息提醒时可以设置该属性为true,显示相应的消息提醒,如果需要使用数字标记类型,同时需要设置相应的count属性。 | -| maxcount | number | 99 | 否 | 最大消息数限制,当收到新信息提醒大于该限制时,标识数字会进行省略,仅显示maxcount+。
maxcount属性支持的最大整数值为2147483647。 | -| config | BadgeConfig | - | 否 | 设置新事件标记相关配置属性。 | -| label6+ | string | - | 否 | 设置新事件提醒的文本值。
使用该属性时,count和maxcount属性不生效。 | +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| ------------------ | ----------- | -------- | ---- | ------------------------------------------------------------ | +| placement | string | rightTop | 否 | 事件提醒的数字标记或者圆点标记的位置,可选值为:
- right:位于组件右边框。
- rightTop:位于组件边框右上角。
- left:位于组件左边框。 | +| count | number | 0 | 否 | 设置提醒的消息数,默认为0,为0时不显示。当设置相应的提醒消息数大于0时,消息提醒会变成数字标记类型。
当数字设置大于maxcount时,将使用maxcount显示。count属性最大支持整数值为2147483647。 | +| visible | boolean | false | 否 | 是否显示消息提醒,当收到新信息提醒时可以设置该属性为true,显示相应的消息提醒,如果需要使用数字标记类型,同时需要设置相应的count属性。 | +| maxcount | number | 99 | 否 | 最大消息数限制,当收到新信息提醒大于该限制时,标识数字会进行省略,仅显示maxcount+。
maxcount属性支持的最大整数值为2147483647。 | +| config | BadgeConfig | - | 否 | 设置新事件标记相关配置属性。 | +| label6+ | string | - | 否 | 设置新事件提醒的文本值。
使用该属性时,count和maxcount属性不生效。 | **表1** BadgeConfig @@ -107,4 +107,4 @@ export default { } ``` -![zh-cn_image_0000001177265268](figures/zh-cn_image_0000001177265268.png) +![zh-cn_image_000000117726526811](figures/zh-cn_image_000000117726526811.png) diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-list.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-list.md index 396137bfec9a550a7d5e615c397cdfd1470cbae2..7414bbdc09505ec7ba9523eeaf200349bbcb1fbd 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 @@ -118,10 +118,10 @@ export default { data: { todolist: [{ title: '刷题', - date: '2021-12-31 10:00:00', + date: '2021-12-31 10:00:00' }, { title: '看电影', - date: '2021-12-31 20:00:00', + date: '2021-12-31 20:00:00' }], }, } diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md index 2b91d44ae98b9d706c0cf8c6c64631f827406159..fad69559050a21e56ed32a0004645d6459722c55 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md @@ -85,58 +85,63 @@ ```html
-
- -
- -
-
- Simple panel in {{modeFlag}} mode -
-
- -
+
+
- + +
+
+ Simple panel in {{ modeFlag }} mode +
+
+ +
+
+
``` ```css /* xxx.css */ .doc-page { - flex-direction: column; - justify-content: center; - align-items: center; + flex-direction: column; + justify-content: center; + align-items: center; } + .btn-div { - width: 100%; - height: 200px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 200px; + flex-direction: column; + align-items: center; + justify-content: center; } + .txt { - color: #000000; - font-weight: bold; - font-size: 39px; + color: #000000; + font-weight: bold; + font-size: 39px; } + .panel-div { - width: 100%; - flex-direction: column; - align-items: center; + width: 100%; + flex-direction: column; + align-items: center; } + .inner-txt { - width: 100%; - height: 160px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 160px; + flex-direction: column; + align-items: center; + justify-content: center; } + .inner-btn { - width: 100%; - height: 120px; - justify-content: center; - align-items: center; + width: 100%; + height: 120px; + justify-content: center; + align-items: center; } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md index b6681a3a43402e11518ee088d097236faf4a0deb..47cfbf39da7cbadfc63acc8b9fe5b131e06303b3 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md @@ -115,7 +115,7 @@ export default { visibilitychange(e) { prompt.showToast({ message: 'visibility change visibility: ' + e.visibility, - duration: 3000, + duration: 3000 }); }, showpopup() { @@ -123,7 +123,7 @@ export default { }, hidepopup() { this.$element("popup").hide(); - }, + } } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md index a62cc034ebbc4af29821b30aaf386be70afe5b15..a026e81bd9e1646cb37f4f6fdbbebe8104e99ebb 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md @@ -62,93 +62,97 @@ ```html -
- - -
- First screen -
- -
- -
- Second screen -
- -
- -
- Third screen -
- -
-
+
+ + +
+ First screen +
+ +
+ +
+ Second screen +
+ +
+ +
+ Third screen +
+ +
+
``` ```css /* xxx.css */ .container { - margin-top: 20px; - flex-direction: column; - align-items: center; - height: 300px; + margin-top: 20px; + flex-direction: column; + align-items: center; + height: 300px; } + .stepperItem { - width: 100%; - flex-direction: column; - align-items: center; + width: 100%; + flex-direction: column; + align-items: center; } + .stepperItemContent { - color: #0000ff; - font-size: 50px; - justify-content: center; + font-size: 50px; + justify-content: center; } + .button { - width: 60%; - margin-top: 30px; - justify-content: center; + width: 60%; + margin-top: 30px; + justify-content: center; } ``` ```js // xxx.js export default { - data: { - label_1: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_2: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_3: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - }, - setRightButton(e) { - this.$element('mystepper').setNextButtonStatus({status: 'skip', label: 'SKIP'}); - }, - nextclick(e) { - var index = { - pendingIndex: e.pendingIndex - } - return index; - }, - backclick(e) { - var index = { - pendingIndex: e.pendingIndex + data: { + label_1: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_2: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_3: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + } + }, + setRightButton(e) { + this.$element('mystepper').setNextButtonStatus({ + status: 'skip', label: 'SKIP' + }); + }, + nextclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; + }, + backclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; } - return index; - }, } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md index 71823ace1f55c72bab674028c058be15050a906c..57b9e1b4212ff391a200353282c426ad1200e0c8 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md @@ -12,8 +12,7 @@ tab页签容器。 ## 子组件 -仅支持最多一个<[tab-bar](../arkui-js/js-components-container-tab-bar.md)>和最多一个<[tab-content](../arkui-js/js-components-container-tab-content.md)>。 - +仅支持<[tab-bar](../arkui-js/js-components-container-tab-bar.md)>和<[tab-content](../arkui-js/js-components-container-tab-content.md)>。 ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-create-elements.md b/zh-cn/application-dev/reference/arkui-js/js-components-create-elements.md new file mode 100644 index 0000000000000000000000000000000000000000..5c86727d5b714f5be38752746d48e91e8a855954 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-js/js-components-create-elements.md @@ -0,0 +1,145 @@ +# 动态创建组件 + +提供在页面中动态添加组件,并为动态添加的组件设置属性与样式的能力。 + +> **说明:** +> +> - 从API version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## createElement + +createElement(tag: string): Element + +创建一个组件对象。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| tag | string | 是 | 组件名称。 | + +**返回值:** + +| 类型 | 说明 | +| ----------- | ------------- | +| Element | 对应tag名称的组件对象。 | + +```js +let newImage = dom.createElement('image') +``` + + +## setAttribute + +setAttribute(name: string, value: string): void + +动态设置组件的属性。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| name | string | 是 | 属性名称。 | +| value | string | 是 | 属性值。 | + +```js +newImage.setAttribute('src', 'common/testImage.jpg') +``` + + +## setStyle + +setStyle(name: string, value: string): boolean + +动态设置组件的样式。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| name | string | 是 | 样式名称。 | +| value | string | 是 | 样式值。 | + +**返回值:** + +| 类型 | 说明 | +| ----------- | ------------- | +| boolean | 设置成功时返回true,失败时返回false。 | + +```js +newImage.setStyle('width', '120px') +``` + + +## addChild + +addChild(child: Element): void + +将动态创建的组件添加到父组件当中。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| child | Element | 是 | 组件对象。 | + +```js +newDiv.addChild(newImage) +``` + + +## 示例 + +```html + +
+
+ + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + align-items: center; + width: 100%; +} + +.parent { + flex-direction: column; +} + +.btn { + width: 70%; + height: 60px; + margin: 15px; +} +``` + +```js +// xxx.js +let newDiv = null +let newImage = null + +export default { + appendDiv() { + let parent = this.$element('parentDiv') + newDiv = dom.createElement('div') + newDiv.setStyle('width', '150px') + newDiv.setStyle('height', '150px') + newDiv.setStyle('backgroundColor', '#AEEEEE') + newDiv.setStyle('marginTop', '15px') + parent.addChild(newDiv) + }, + appendImage() { + newImage = dom.createElement('image') + newImage.setAttribute('src', 'common/testImage.jpg') + newImage.setStyle('width', '120px') + newImage.setStyle('height', '120px') + newDiv.addChild(newImage) + } +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/borderImage.gif b/zh-cn/application-dev/reference/arkui-ts/figures/borderImage.gif new file mode 100644 index 0000000000000000000000000000000000000000..dd8d0f1a9f9a786de94abf348130c526ecb09641 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/borderImage.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/borderImage.png b/zh-cn/application-dev/reference/arkui-ts/figures/borderImage.png deleted file mode 100644 index 22285e0910e3c447036d2144194a2e4301c2df6f..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/borderImage.png and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif b/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif new file mode 100644 index 0000000000000000000000000000000000000000..b00b7fad991682b2cd81b0afdd149a3b7f73dc49 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/imageAnimator.gif b/zh-cn/application-dev/reference/arkui-ts/figures/imageAnimator.gif new file mode 100644 index 0000000000000000000000000000000000000000..9686185c04ef6c0a764fa7fcb91b8270d503f79d Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/imageAnimator.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/list1.gif b/zh-cn/application-dev/reference/arkui-ts/figures/list1.gif new file mode 100644 index 0000000000000000000000000000000000000000..0b8a734b8fbafb33d47a774d772ec81da8197740 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/list1.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/textArea.gif b/zh-cn/application-dev/reference/arkui-ts/figures/textArea.gif new file mode 100644 index 0000000000000000000000000000000000000000..52253c3693b7626a5959a2e88e4744d01b80d057 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/textArea.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif b/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif new file mode 100644 index 0000000000000000000000000000000000000000..9ae06ee5b27f1b4ce369b8e90ef5602a1ea0f846 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/timePicker.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/transform.PNG b/zh-cn/application-dev/reference/arkui-ts/figures/transform.PNG new file mode 100644 index 0000000000000000000000000000000000000000..a840e7050d1ae79179722dd9f23e4f383d1db2ec Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/transform.PNG differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174264386.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174264386.png index 2ff75f958a860f1ed483d799e2ef6431fbce5a74..8e96bc78a4ab3e3d5c44201def12d73fea1b6db2 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174264386.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174264386.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174582844.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174582844.gif index 30e89347337d9e358d4b823c7658490e032eb435..639261bd9e9997074cd45491807a58bb79a5def2 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174582844.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174582844.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001186807708.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001186807708.gif index 8eceb3bf5313485a1fedda5768e70cdb5febc464..c2468d1491af049673574a097a107a3e6c1b417d 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001186807708.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001186807708.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001241668363.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001241668363.gif index 502888c25bb21b3803858f9c436cca23d9dc29d0..fba237dad5fc43609bb5ebcf6b0310328800d9f6 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001241668363.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001241668363.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001251007721.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001251007721.gif index 32d2334360f9fd90afd1709f50a39add4e2196c1..3c7f41bb43465b26d9545482a6c42621a42b360b 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001251007721.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001251007721.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md index bdb96903ab434ebd9d742c651c8e2c3cdd02880f..01bd2021d811cf64c04b249a092e45ba3c45a858 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -1,4 +1,4 @@ -# 文档中涉及到的内置枚举值 +# 枚举说明 ## Color diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index 7437c6f33f8f96175ee6e81101ebe75d08cf09f1..74c48383609667735a7bd7a1ef1e9adf97f80a00 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -28,24 +28,24 @@ DatePicker(options?: {start?: Date, end?: Date, selected?: Date}) ## 属性 -| 名称 | 参数类型 | 描述 | +| 名称 | 参数类型 | 描述 | | ------| -------------- | -------- | -| lunar | boolean | 日期是否显示农历。
- true:展示农历。
- false:不展示农历。
默认值:false | +| lunar | boolean | 日期是否显示农历。
- true:展示农历。
- false:不展示农历。
默认值:false | ## 事件 -| 名称 | 功能描述 | -| -------- | -------- | -| onChange(callback: (value: DatePickerResult) => void) | 选择日期时触发该事件。 | +| 名称 | 功能描述 | +| -------- | -------- | +| onChange(callback: (value: DatePickerResult) => void) | 选择日期时触发该事件。 | ## DatePickerResult对象说明 -| 名称 | 参数类型 | 描述 | +| 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| year | number | 选中日期的年。 | -| month | number | 选中日期的月(0~11),0表示1月,11表示12月。 | -| day | number | 选中日期的日。 | +| year | number | 选中日期的年。 | +| month | number | 选中日期的月(0~11),0表示1月,11表示12月。 | +| day | number | 选中日期的日。 | ## 示例 @@ -69,7 +69,7 @@ struct DatePickerExample { DatePicker({ start: new Date('1970-1-1'), end: new Date('2100-1-1'), - selected: this.selectedDate, + selected: this.selectedDate }) .lunar(this.isLunar) .onChange((value: DatePickerResult) => { @@ -82,3 +82,4 @@ struct DatePickerExample { } ``` +![datePicker](figures/datePicker.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md index a6031d9440bc49619853cc154bd01b5d5e13852f..16884200f16f3521dcd875a035f242050afb282a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -64,7 +64,7 @@ struct GaugeExample { // 参数设置当前值为75,属性设置值为25,属性设置优先级高 Gauge({ value: 75 }) - .value(25) //属性和参数都设置时以参数为准 + .value(25) // 属性和参数都设置时以参数为准 .width(200).height(200) .colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]]) 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 79c635647e64f55a94a02962f91b4952bb00998c..95ea376b2a4dec554b07cc11bcb75c95eff7dbf1 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 @@ -27,7 +27,7 @@ Image(src: string | PixelMap | Resource) | 参数名 | 参数类型 | 必填 | 参数描述 | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource类型) | 是 | 图片的数据源,支持本地图片和网络图片。
当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。
\- 支持的图片格式包括png、jpg、bmp、svg和gif。
\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
\- 支持`dataability://`路径前缀的字符串,用于访问通过data ability提供的图片路径。
\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。 | +| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource类型) | 是 | 图片的数据源,支持本地图片和网络图片。
当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。
\- 支持的图片格式包括png、jpg、bmp、svg和gif。
\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
\- 支持`datashare://`路径前缀的字符串,用于访问通过data ability提供的图片路径。
\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。 | ## 属性 @@ -320,7 +320,7 @@ struct ImageExample3 { .onError(() => { console.log('load image fail') }) - .overlay('\nwidth: ' + String(this.width) + ' height: ' + String(this.height), { + .overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) @@ -353,17 +353,17 @@ struct ImageExample3 { ### 渲染沙箱路径图片 ``` -import fileio from '@ohos.fileio'; -import image from '@ohos.multimedia.image'; +import fileio from '@ohos.fileio' +import image from '@ohos.multimedia.image' -const EMPTY_PATH = 'file://'; +const EMPTY_PATH = 'file://' @Entry @Component struct LoadImageExample { - @State fileContent: string = ''; - @State path: string = EMPTY_PATH; - @State accountInfoHeadPic: any = ''; + @State fileContent: string = '' + @State path: string = EMPTY_PATH + @State accountInfoHeadPic: any = '' build() { Column() { @@ -371,22 +371,22 @@ struct LoadImageExample { .margin({ bottom: 10 }) .onClick(() => { try { - this.path = EMPTY_PATH; - let context = getContext(this); - let path = context.getApplicationContext().filesDir + '/icon.png'; - console.log(`读取沙箱图片=========>${path}`); - let fd = fileio.openSync(path, 0o100, 0o666); - console.log(`create file========>${fd}`); - let srcPath = context.bundleCodeDir + '/entry/resource/base/media/icon.png'; - fileio.copyFileSync(srcPath, path); - console.log(`error:=============>${e.message}`); + this.path = EMPTY_PATH + let context = getContext(this) + let path = context.getApplicationContext().filesDir + '/icon.png' + console.log(`读取沙箱图片=========>${path}`) + let fd = fileio.openSync(path, 0o100, 0o666) + console.log(`create file========>${fd}`) + let srcPath = context.bundleCodeDir + '/entry/resource/base/media/icon.png' + fileio.copyFileSync(srcPath, path) + console.log(`error:=============>${e.message}`) } }) Button('读取资源图片') .margin({ bottom: 10 }) .onClick(() => { this.path = EMPTY_PATH; - this.path += getContext(this.bundleCodeDir + '/entry/resource/base/media/icon.png'); + this.path += getContext(this.bundleCodeDir + '/entry/resource/base/media/icon.png') }) Text(`图片路径:${this.path}`) .fontSize(20) 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 d53835eadcd4162b1fffcd075e9d504d3e874927..9b838578ffc69b47438dd1ae96ec56e90bb7c9dd 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 @@ -22,13 +22,13 @@ ImageAnimator() | 参数名称 | 参数类型 |参数描述 | | ---------- | ----------------------- |-------- | -| images | Array<[ImageFrameInfo](imageframeinfo对象说明)> | 设置图片帧信息集合。每一帧的帧信息(ImageFrameInfo)包含图片路径、图片大小、图片位置和图片播放时长信息,详见ImageFrameInfo属性说明。
默认值:[] | +| images | Array<[ImageFrameInfo](#imageframeinfo对象说明)> | 设置图片帧信息集合。每一帧的帧信息(ImageFrameInfo)包含图片路径、图片大小、图片位置和图片播放时长信息,详见ImageFrameInfo属性说明。
默认值:[]
**说明:**
不支持动态更新。 | | state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | 默认为初始状态,用于控制播放状态。
默认值:AnimationStatus.Initial | | duration | number | 单位为毫秒,默认时长为1000ms;duration为0时,不播放图片;值的改变只会在下一次循环开始时生效;当images中任意一帧图片设置了单独的duration后,该属性设置无效。
默认值:1000 | | reverse | boolean | 设置播放顺序。false表示从第1张图片播放到最后1张图片; true表示从最后1张图片播放到第1张图片。
默认值:false | | fixedSize | boolean | 设置图片大小是否固定为组件大小。 true表示图片大小与组件大小一致,此时设置图片的width 、height 、top 和left属性是无效的。false表示每一张图片的width 、height 、top和left属性都要单独设置。
默认值:true | | preDecode | number | 是否启用预解码,默认值为0,即不启用预解码,如该值设为2,则播放当前页时会提前加载后面两张图片至缓存以提升性能。
默认值:0 | -| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | 否 | 设置动画开始前和结束后的状态,可选值参见FillMode说明。
默认值:FillMode.Forwards | +| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | 设置动画开始前和结束后的状态,可选值参见FillMode说明。
默认值:FillMode.Forwards | | iterations | number | 默认播放一次,设置为-1时表示无限次播放。
默认值:1 | ## ImageFrameInfo对象说明 @@ -148,3 +148,4 @@ struct ImageAnimatorExample { } ``` +![imageAnimator](figures/imageAnimator.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md index 7edd6d11691ffaa297f809d16372f6ebe4bb6662..13653c27a6f350091794ea36af4c6847209fe355 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-patternlock.md @@ -66,9 +66,9 @@ reset(): void @Entry @Component struct PatternLockExample { - @State passwords: Number[] = []; - @State message: string = 'please input password!'; - private patternLockController: PatternLockController = new PatternLockController(); + @State passwords: Number[] = [] + @State message: string = 'please input password!' + private patternLockController: PatternLockController = new PatternLockController() build() { Column() { @@ -85,29 +85,29 @@ struct PatternLockExample { .onPatternComplete((input: Array) => { // 输入的密码长度小于5时,提示重新输入 if (input === null || input === undefined || input.length < 5) { - this.message = 'The password length needs to be greater than 5, please enter again.'; - return; + this.message = 'The password length needs to be greater than 5, please enter again.' + return } // 判断密码长度是否大于0 if (this.passwords.length > 0) { // 判断两次输入的密码是否相同,相同则提示密码设置成功,否则提示重新输入 if (this.passwords.toString() === input.toString()) { - this.passwords = input; - this.message = 'Set password successfully: ' + this.passwords.toString(); + this.passwords = input + this.message = 'Set password successfully: ' + this.passwords.toString() } else { - this.message = 'Inconsistent passwords, please enter again.'; + this.message = 'Inconsistent passwords, please enter again.' } } else { // 提示第二次输入密码 - this.passwords = input; - this.message = "Please enter again."; + this.passwords = input + this.message = "Please enter again." } }) Button('Reset PatternLock').margin(30).onClick(() => { // 重置密码锁 - this.patternLockController.reset(); - this.passwords = []; - this.message = 'Please input password'; + this.patternLockController.reset() + this.passwords = [] + this.message = 'Please input password' }) }.width('100%').height('100%') } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md index 77e5cd47836947ba9efe003504a41147cf1508c2..a336251138f20d8f02d64fefbe30e18b423d0dbb 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -75,9 +75,9 @@ caretPosition(value: number): void @Entry @Component struct SearchExample { - @State changeValue: string = ''; - @State submitValue: string = ''; - controller: SearchController = new SearchController(); + @State changeValue: string = '' + @State submitValue: string = '' + controller: SearchController = new SearchController() build() { Column() { @@ -92,16 +92,16 @@ struct SearchExample { .placeholderFont({ size: 14, weight: 400 }) .textFont({ size: 14, weight: 400 }) .onSubmit((value: string) => { - this.submitValue = value; + this.submitValue = value }) .onChange((value: string) => { - this.changeValue = value; + this.changeValue = value }) .margin(20) Button('Set caretPosition 1') .onClick(() => { // 设置光标位置到输入的第一个字符后 - this.controller.caretPosition(1); + this.controller.caretPosition(1) }) }.width('100%') } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md index 80ff26bdd482cdd46e2ac803bd0b896274f4e336..4ee4b62624d053f2198c44f1cfa14d60d83d6d87 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -75,14 +75,14 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty @Entry @Component struct SliderExample { - @State outSetValueOne: number = 40; - @State inSetValueOne: number = 40; - @State outSetValueTwo: number = 40; - @State inSetValueTwo: number = 40; - @State vOutSetValueOne: number = 40; - @State vInSetValueOne: number = 40; - @State vOutSetValueTwo: number = 40; - @State vInSetValueTwo: number = 40; + @State outSetValueOne: number = 40 + @State inSetValueOne: number = 40 + @State outSetValueTwo: number = 40 + @State inSetValueTwo: number = 40 + @State vOutSetValueOne: number = 40 + @State vInSetValueOne: number = 40 + @State vOutSetValueTwo: number = 40 + @State vInSetValueTwo: number = 40 build() { Column({ space: 8 }) { @@ -96,8 +96,8 @@ struct SliderExample { }) .showTips(true) .onChange((value: number, mode: SliderChangeMode) => { - this.outSetValueOne = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.outSetValueOne = value + console.info('value:' + value + 'mode:' + mode.toString()) }) // toFixed(0)将滑动条返回值处理为整数精度 Text(this.outSetValueOne.toFixed(0)).fontSize(12) @@ -111,8 +111,8 @@ struct SliderExample { }) .showSteps(true) .onChange((value: number, mode: SliderChangeMode) => { - this.outSetValueTwo = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.outSetValueTwo = value + console.info('value:' + value + 'mode:' + mode.toString()) }) Text(this.outSetValueTwo.toFixed(0)).fontSize(12) } @@ -131,8 +131,8 @@ struct SliderExample { .selectedColor('#4169E1') .showTips(true) .onChange((value: number, mode: SliderChangeMode) => { - this.inSetValueOne = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.inSetValueOne = value + console.info('value:' + value + 'mode:' + mode.toString()) }) Text(this.inSetValueOne.toFixed(0)).fontSize(12) } @@ -148,8 +148,8 @@ struct SliderExample { .selectedColor('#4169E1') .showSteps(true) .onChange((value: number, mode: SliderChangeMode) => { - this.inSetValueTwo = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.inSetValueTwo = value + console.info('value:' + value + 'mode:' + mode.toString()) }) Text(this.inSetValueTwo.toFixed(0)).fontSize(12) } @@ -169,8 +169,8 @@ struct SliderExample { .selectedColor('#4169E1') .showTips(true) .onChange((value: number, mode: SliderChangeMode) => { - this.vOutSetValueOne = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.vOutSetValueOne = value + console.info('value:' + value + 'mode:' + mode.toString()) }) Slider({ value: this.vOutSetValueTwo, @@ -183,8 +183,8 @@ struct SliderExample { .selectedColor('#4169E1') .showSteps(true) .onChange((value: number, mode: SliderChangeMode) => { - this.vOutSetValueTwo = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.vOutSetValueTwo = value + console.info('value:' + value + 'mode:' + mode.toString()) }) } }.width('50%').height(300) @@ -200,8 +200,8 @@ struct SliderExample { }) .showTips(true) .onChange((value: number, mode: SliderChangeMode) => { - this.vInSetValueOne = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.vInSetValueOne = value + console.info('value:' + value + 'mode:' + mode.toString()) }) Slider({ value: this.vInSetValueTwo, @@ -212,8 +212,8 @@ struct SliderExample { }) .showSteps(true) .onChange((value: number, mode: SliderChangeMode) => { - this.vInSetValueTwo = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.vInSetValueTwo = value + console.info('value:' + value + 'mode:' + mode.toString()) }) } }.width('50%').height(300) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md index 12b32146b34e2ac75dd03e2e887037c7a6a0e016..d289dd65cb227bd32f908925cd2947812e73411d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md @@ -48,10 +48,10 @@ Stepper(value?: { index?: number }) @Entry @Component struct StepperExample { - @State currentIndex: number = 0; - @State firstState: ItemState = ItemState.Normal; - @State secondState: ItemState = ItemState.Normal; - @State thirdState: ItemState = ItemState.Normal; + @State currentIndex: number = 0 + @State firstState: ItemState = ItemState.Normal + @State secondState: ItemState = ItemState.Normal + @State thirdState: ItemState = ItemState.Normal build() { Stepper({ @@ -67,7 +67,7 @@ struct StepperExample { .margin({ top: 250, bottom: 50 }) Button('change status:' + this.firstState) .onClick(() => { - this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip; + this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip }) }.width('100%') } @@ -83,7 +83,7 @@ struct StepperExample { .margin({ top: 250, bottom: 50 }) Button('change status:' + this.secondState) .onClick(() => { - this.secondState = this.secondState === ItemState.Disabled ? ItemState.Normal : ItemState.Disabled; + this.secondState = this.secondState === ItemState.Disabled ? ItemState.Normal : ItemState.Disabled }) }.width('100%') } @@ -100,7 +100,7 @@ struct StepperExample { .margin({ top: 250, bottom: 50 }) Button('change status:' + this.thirdState) .onClick(() => { - this.thirdState = this.thirdState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting; + this.thirdState = this.thirdState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting }) }.width('100%') } @@ -119,14 +119,14 @@ struct StepperExample { } .onFinish(() => { // 此处可处理点击最后一页的Finish时的逻辑,例如路由跳转等 - console.info('onFinish'); + console.info('onFinish') }) .onSkip(() => { // 此处可处理点击跳过时的逻辑,例如动态修改Stepper的index值使其跳转到某一步骤页等 - console.info('onSkip'); + console.info('onSkip') }) .onChange((prevIndex: number, index: number) => { - this.currentIndex = index; + this.currentIndex = index }) } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index d13a14c6835699a69d9f5e88211b0ef8d0e8bf11..a36b7afae827d0421190ad5d788fcf06ce0a2080 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -85,9 +85,10 @@ struct TextAreaExample { build() { Column() { - TextArea({ placeholder: 'input your word', controller: this.controller }) + TextArea({ placeholder: 'The text area can hold an unlimited amount of text. input your word', controller: this.controller }) .placeholderFont({ size: 14, weight: 400 }) .width(400) + .height(50) .margin(20) .fontSize(14) .onChange((value: string) => { @@ -104,3 +105,5 @@ struct TextAreaExample { } } ``` + +![textArea](figures/textArea.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md index d3201827e9f9528d5b449a760534c996958e5ab5..d03b65792c3c407408870796225e0bbada42f951 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md @@ -65,9 +65,9 @@ stop() @Entry @Component struct Second { - @State accumulateTime: number = 0; + @State accumulateTime: number = 0 // 导入对象 - controller: TextClockController = new TextClockController(); + controller: TextClockController = new TextClockController() build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text('Current milliseconds is ' + this.accumulateTime) @@ -76,7 +76,7 @@ struct Second { TextClock({ timeZoneOffset: -8, controller: this.controller }) .format('hms') .onDateChange((value: number) => { - this.accumulateTime = value; + this.accumulateTime = value }) .margin(20) .fontSize(30) @@ -84,12 +84,12 @@ struct Second { .margin({ bottom: 10 }) .onClick(() => { // 启动文本时钟 - this.controller.start(); + this.controller.start() }) Button("stop TextClock") .onClick(() => { // 停止文本时钟 - this.controller.stop(); + this.controller.stop() }) } .width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index cc71f7e53cf4147ce72488e148a7659bce8c4662..8853f258c7bb80d731dcaf6d78319d005cd94d43 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -112,8 +112,8 @@ caretPosition(value: number): void @Entry @Component struct TextInputExample { - @State text: string = ''; - controller: TextInputController = new TextInputController(); + @State text: string = '' + controller: TextInputController = new TextInputController() build() { Column() { @@ -127,14 +127,14 @@ struct TextInputExample { .fontSize(14) .fontColor(Color.Black) .onChange((value: string) => { - this.text = value; + this.text = value }) Text(this.text) Button('Set caretPosition 1') .margin(15) .onClick(() => { // 将光标移动至第一个字符后 - this.controller.caretPosition(1); + this.controller.caretPosition(1) }) // 密码输入框 TextInput({ placeholder: 'input your password...' }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md index d5e0b6879170894cd859e1882783c798a6afeb76..8396476e8ad0867408a4cd801fd7d65e9758a88c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md @@ -71,11 +71,11 @@ reset() @Component struct TextTimerExample { textTimerController: TextTimerController = new TextTimerController() - @State format: string = 'HH:mm:ss.SS' + @State format: string = 'mm:ss.SS' build() { Column() { - TextTimer({controller: this.textTimerController}) + TextTimer({ controller: this.textTimerController, isCountDown: true, count: 30000 }) .format(this.format) .fontColor(Color.Black) .fontSize(50) @@ -84,14 +84,14 @@ struct TextTimerExample { }) Row() { Button("start").onClick(() => { - this.textTimerController.start(); - }); + this.textTimerController.start() + }) Button("pause").onClick(() => { - this.textTimerController.pause(); - }); + this.textTimerController.pause() + }) Button("reset").onClick(() => { - this.textTimerController.reset(); - }); + this.textTimerController.reset() + }) } } } 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 5fe82d03d5c5180727483648a4882153c6812322..c2bdbd8b10ce8588b99e41090ac5c27b34bad87c 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 @@ -77,3 +77,5 @@ struct TimePickerExample { } } ``` + +![timePicker](figures/timePicker.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index 3928f356b22cc0066f87e55ad2ebd6ea136ff530..bf56800c5b2345d524b0d321b9986e3a0dbb99d6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -23,7 +23,7 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) | 参数名 | 参数类型 | 必填 | 参数描述 | | ---- | ---------- | -----| -------------- | -| type | ToggleType | 是 | 开关类型。 | +| type | [ToggleType](#toggletype枚举说明) | 是 | 开关类型。 | | isOn | boolean | 否 | 开关是否打开,true:打开,false:关闭。
默认值:false | 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 6a53c8b54acf74ecb26f23dbd4e38b1f397cb5b3..5e5b34dd01d28eda65afd2d00ebfacd037055eb3 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 @@ -37,7 +37,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -52,7 +52,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) @Entry @Component struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -67,7 +67,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: $rawfile("index.html"), controller: this.controller }) @@ -109,7 +109,7 @@ domStorageAccess(domStorageAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -138,7 +138,7 @@ fileAccess(fileAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -167,7 +167,7 @@ fileFromUrlAccess(fileFromUrlAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -195,7 +195,7 @@ imageAccess(imageAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -228,16 +228,16 @@ javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Arr @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() testObj = { test: (data1, data2, data3) => { - console.log("data1:" + data1); - console.log("data2:" + data2); - console.log("data3:" + data3); - return "AceString"; + console.log("data1:" + data1) + console.log("data2:" + data2) + console.log("data3:" + data3) + return "AceString" }, toString: () => { - console.log('toString' + "interface instead."); + console.log('toString' + "interface instead.") } } build() { @@ -261,16 +261,16 @@ javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Arr @Entry @Component struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); + controller: web_webview.WebviewController = new web_webview.WebviewController() testObj = { test: (data1, data2, data3) => { - console.log("data1:" + data1); - console.log("data2:" + data2); - console.log("data3:" + data3); - return "AceString"; + console.log("data1:" + data1) + console.log("data2:" + data2) + console.log("data3:" + data3) + return "AceString" }, toString: () => { - console.log('toString' + "interface instead."); + console.log('toString' + "interface instead.") } } build() { @@ -307,7 +307,7 @@ javaScriptAccess(javaScriptAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -336,8 +336,8 @@ mixedMode(mixedMode: MixedMode) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State mode: MixedMode = MixedMode.All; + controller: WebController = new WebController() + @State mode: MixedMode = MixedMode.All build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -366,7 +366,7 @@ onlineImageAccess(onlineImageAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -395,7 +395,7 @@ zoomAccess(zoomAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -424,7 +424,7 @@ overviewModeAccess(overviewModeAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -453,7 +453,7 @@ databaseAccess(databaseAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -482,7 +482,7 @@ geolocationAccess(geolocationAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -511,8 +511,8 @@ mediaPlayGestureAccess(access: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State access: boolean = true; + controller: WebController = new WebController() + @State access: boolean = true build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -541,7 +541,7 @@ multiWindowAccess(multiWindow: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -570,8 +570,8 @@ cacheMode(cacheMode: CacheMode) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State mode: CacheMode = CacheMode.None; + controller: WebController = new WebController() + @State mode: CacheMode = CacheMode.None build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -581,7 +581,7 @@ cacheMode(cacheMode: CacheMode) } ``` -### textZoomRatio +### textZoomRatio9+ textZoomRatio(textZoomRatio: number) @@ -600,8 +600,8 @@ textZoomRatio(textZoomRatio: number) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State atio: number = 150; + controller: WebController = new WebController() + @State atio: number = 150 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -611,6 +611,36 @@ textZoomRatio(textZoomRatio: number) } ``` +### initialScale9+ + +initialScale(percent: number) + +设置整体页面的缩放百分比,默认为100%。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ------------ | ------ | ---- | ---- | --------------- | +| percent | number | 是 | 100 | 要设置的整体页面的缩放百分比。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + @State percent: number = 100 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .initialScale(this.percent) + } + } + } + ``` + ### userAgent userAgent(userAgent: string) @@ -630,8 +660,8 @@ userAgent(userAgent: string) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'; + controller: WebController = new WebController() + @State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36' build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -660,8 +690,8 @@ webDebuggingAccess(webDebuggingAccess: boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State webDebuggingAccess: boolean = true; + controller: WebController = new WebController() + @State webDebuggingAccess: boolean = true build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -706,7 +736,7 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) = @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -730,7 +760,7 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) = event.result.handleCancel() } }) - return true; + return true }) } } @@ -764,14 +794,14 @@ onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResu @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onBeforeUnload((event) => { - console.log("event.url:" + event.url); - console.log("event.message:" + event.message); + console.log("event.url:" + event.url) + console.log("event.message:" + event.message) AlertDialog.show({ title: 'onBeforeUnload', message: 'text', @@ -791,7 +821,7 @@ onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResu event.result.handleCancel() } }) - return true; + return true }) } } @@ -825,15 +855,15 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onConfirm((event) => { - console.log("event.url:" + event.url); - console.log("event.message:" + event.message); - console.log("event.result:" + event.result); + console.log("event.url:" + event.url) + console.log("event.message:" + event.message) + console.log("event.result:" + event.result) AlertDialog.show({ title: 'onConfirm', message: 'text', @@ -853,7 +883,7 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) event.result.handleCancel() } }) - return true; + return true }) } } @@ -885,15 +915,15 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onPrompt((event) => { - console.log("url:" + event.url); - console.log("message:" + event.message); - console.log("value:" + event.value); + console.log("url:" + event.url) + console.log("message:" + event.message) + console.log("value:" + event.value) AlertDialog.show({ title: 'onPrompt', message: 'text', @@ -913,7 +943,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul event.result.handleCancel() } }) - return true; + return true }) } } @@ -945,17 +975,17 @@ onConsole(callback: (event?: { message: ConsoleMessage }) => boolean) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onConsole((event) => { - console.log('getMessage:' + event.message.getMessage()); - console.log('getSourceId:' + event.message.getSourceId()); - console.log('getLineNumber:' + event.message.getLineNumber()); - console.log('getMessageLevel:' + event.message.getMessageLevel()); - return false; + console.log('getMessage:' + event.message.getMessage()) + console.log('getSourceId:' + event.message.getSourceId()) + console.log('getLineNumber:' + event.message.getLineNumber()) + console.log('getMessageLevel:' + event.message.getMessageLevel()) + return false }) } } @@ -982,17 +1012,17 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onDownloadStart((event) => { - console.log('url:' + event.url); - console.log('userAgent:' + event.userAgent); - console.log('contentDisposition:' + event.contentDisposition); - console.log('contentLength:' + event.contentLength); - console.log('mimetype:' + event.mimetype); + console.log('url:' + event.url) + console.log('userAgent:' + event.userAgent) + console.log('contentDisposition:' + event.contentDisposition) + console.log('contentLength:' + event.contentLength) + console.log('mimetype:' + event.mimetype) }) } } @@ -1019,23 +1049,23 @@ onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResou @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onErrorReceive((event) => { - console.log('getErrorInfo:' + event.error.getErrorInfo()); - console.log('getErrorCode:' + event.error.getErrorCode()); - console.log('url:' + event.request.getRequestUrl()); - console.log('isMainFrame:' + event.request.isMainFrame()); - console.log('isRedirect:' + event.request.isRedirect()); - console.log('isRequestGesture:' + event.request.isRequestGesture()); - console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString()); - let result = event.request.getRequestHeader(); - console.log('The request header result size is ' + result.length); + console.log('getErrorInfo:' + event.error.getErrorInfo()) + console.log('getErrorCode:' + event.error.getErrorCode()) + console.log('url:' + event.request.getRequestUrl()) + console.log('isMainFrame:' + event.request.isMainFrame()) + console.log('isRedirect:' + event.request.isRedirect()) + console.log('isRequestGesture:' + event.request.isRequestGesture()) + console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString()) + let result = event.request.getRequestHeader() + console.log('The request header result size is ' + result.length) for (let i of result) { - console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue); + console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue) } }) } @@ -1063,30 +1093,30 @@ onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: W @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onHttpErrorReceive((event) => { - console.log('url:' + event.request.getRequestUrl()); - console.log('isMainFrame:' + event.request.isMainFrame()); - console.log('isRedirect:' + event.request.isRedirect()); - console.log('isRequestGesture:' + event.request.isRequestGesture()); - console.log('getResponseData:' + event.response.getResponseData()); - console.log('getResponseEncoding:' + event.response.getResponseEncoding()); - console.log('getResponseMimeType:' + event.response.getResponseMimeType()); - console.log('getResponseCode:' + event.response.getResponseCode()); - console.log('getReasonMessage:' + event.response.getReasonMessage()); - let result = event.request.getRequestHeader(); - console.log('The request header result size is ' + result.length); + console.log('url:' + event.request.getRequestUrl()) + console.log('isMainFrame:' + event.request.isMainFrame()) + console.log('isRedirect:' + event.request.isRedirect()) + console.log('isRequestGesture:' + event.request.isRequestGesture()) + console.log('getResponseData:' + event.response.getResponseData()) + console.log('getResponseEncoding:' + event.response.getResponseEncoding()) + console.log('getResponseMimeType:' + event.response.getResponseMimeType()) + console.log('getResponseCode:' + event.response.getResponseCode()) + console.log('getReasonMessage:' + event.response.getReasonMessage()) + let result = event.request.getRequestHeader() + console.log('The request header result size is ' + result.length) for (let i of result) { - console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); + console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue) } - let resph = event.response.getResponseHeader(); - console.log('The response header result size is ' + resph.length); + let resph = event.response.getResponseHeader() + console.log('The response header result size is ' + resph.length) for (let i of resph) { - console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue); + console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue) } }) } @@ -1114,13 +1144,13 @@ onPageBegin(callback: (event?: { url: string }) => void) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onPageBegin((event) => { - console.log('url:' + event.url); + console.log('url:' + event.url) }) } } @@ -1147,13 +1177,13 @@ onPageEnd(callback: (event?: { url: string }) => void) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onPageEnd((event) => { - console.log('url:' + event.url); + console.log('url:' + event.url) }) } } @@ -1179,7 +1209,7 @@ onProgressChange(callback: (event?: { newProgress: number }) => void) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -1211,7 +1241,7 @@ onTitleReceive(callback: (event?: { title: string }) => void) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -1244,13 +1274,13 @@ onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onRefreshAccessedHistory((event) => { - console.log('url:' + event.url + ' isReload:' + event.isRefreshed); + console.log('url:' + event.url + ' isReload:' + event.isRefreshed) }) } } @@ -1276,13 +1306,13 @@ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => voi @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'chrome://crash/', controller: this.controller }) .onRenderExited((event) => { - console.log('reason:' + event.renderExitReason); + console.log('reason:' + event.renderExitReason) }) } } @@ -1315,7 +1345,7 @@ onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -1338,7 +1368,72 @@ onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector event.result.handleFileList(fileList) } }) - return true; + return true + }) + } + } + } + ``` + +### onResourceLoad9+ + +onResourceLoad(callback: (event: {url: string}) => void) + +通知Web组件所加载的资源文件url信息。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ---- | ---------------------------------------- | --------- | +| url | string | 所加载的资源文件url信息。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onResourceLoad((event) => { + console.log('onResourceLoad: ' + event.url) + }) + } + } + } + ``` + +### onScaleChange9+ + +onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void) + +当前页面显示比例的变化时触发该回调。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ---- | ---------------------------------------- | --------- | +| oldScale | number | 变化前的显示比例百分比。 | +| newScale | number | 变化后的显示比例百分比。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onScaleChange((event) => { + console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale) }) } } @@ -1370,14 +1465,14 @@ onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => b @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onUrlLoadIntercept((event) => { console.log('onUrlLoadIntercept ' + event.data.toString()) - return true; + return true }) } } @@ -1409,9 +1504,9 @@ onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebReso @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - responseweb: WebResourceResponse = new WebResourceResponse(); - heads:Header[] = new Array(); + controller: WebController = new WebController() + responseweb: WebResourceResponse = new WebResourceResponse() + heads:Header[] = new Array() @State webdata: string = "\n" + "\n"+ "\n"+ @@ -1425,7 +1520,7 @@ onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebReso Column() { Web({ src: 'www.example.com', controller: this.controller }) .onInterceptRequest((event) => { - console.log('url:' + event.request.getRequestUrl()); + console.log('url:' + event.request.getRequestUrl()) var head1:Header = { headerKey:"Connection", headerValue:"keep-alive" @@ -1434,15 +1529,15 @@ onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebReso headerKey:"Cache-Control", headerValue:"no-cache" } - var length = this.heads.push(head1); - length = this.heads.push(head2); - this.responseweb.setResponseHeader(this.heads); - this.responseweb.setResponseData(this.webdata); - this.responseweb.setResponseEncoding('utf-8'); - this.responseweb.setResponseMimeType('text/html'); - this.responseweb.setResponseCode(200); - this.responseweb.setReasonMessage('OK'); - return this.responseweb; + var length = this.heads.push(head1) + length = this.heads.push(head2) + this.responseweb.setResponseHeader(this.heads) + this.responseweb.setResponseData(this.webdata) + this.responseweb.setResponseEncoding('utf-8') + this.responseweb.setResponseMimeType('text/html') + this.responseweb.setResponseCode(200) + this.responseweb.setReasonMessage('OK') + return this.responseweb }) } } @@ -1477,8 +1572,8 @@ onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, r @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - httpAuth: boolean = false; + controller: WebController = new WebController() + httpAuth: boolean = false build() { Column() { @@ -1490,13 +1585,13 @@ onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, r primaryButton: { value: 'cancel', action: () => { - event.handler.cancel(); + event.handler.cancel() } }, secondaryButton: { value: 'ok', action: () => { - this.httpAuth = event.handler.isHttpAuthInfoSaved(); + this.httpAuth = event.handler.isHttpAuthInfoSaved() if (this.httpAuth == false) { web_webview.WebDataBase.saveHttpAuthCredentials( event.host, @@ -1504,15 +1599,15 @@ onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, r "2222", "2222" ) - event.handler.cancel(); + event.handler.cancel() } } }, cancel: () => { - event.handler.cancel(); + event.handler.cancel() } }) - return true; + return true }) } } @@ -1539,7 +1634,7 @@ onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslE @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -1551,20 +1646,20 @@ onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslE primaryButton: { value: 'confirm', action: () => { - event.handler.handleConfirm(); + event.handler.handleConfirm() } }, secondaryButton: { value: 'cancel', action: () => { - event.handler.handleCancel(); + event.handler.handleCancel() } }, cancel: () => { - event.handler.handleCancel(); + event.handler.handleCancel() } }) - return true; + return true }) } } @@ -1594,7 +1689,7 @@ onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationH @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -1606,20 +1701,20 @@ onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationH primaryButton: { value: 'confirm', action: () => { - event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem"); + event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem") } }, secondaryButton: { value: 'cancel', action: () => { - event.handler.cancel(); + event.handler.cancel() } }, cancel: () => { - event.handler.ignore(); + event.handler.ignore() } }) - return true; + return true }) } } @@ -1645,7 +1740,7 @@ onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1656,17 +1751,17 @@ onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) primaryButton: { value: 'deny', action: () => { - event.request.deny(); + event.request.deny() } }, secondaryButton: { value: 'onConfirm', action: () => { - event.request.grant(event.request.getAccessibleResource()); + event.request.grant(event.request.getAccessibleResource()) } }, cancel: () => { - event.request.deny(); + event.request.deny() } }) }) @@ -1701,14 +1796,14 @@ onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebCo @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onContextMenuShow((event) => { - console.info("x coord = " + event.param.x()); - console.info("link url = " + event.param.getLinkUrl()); - return true; + console.info("x coord = " + event.param.x()) + console.info("link url = " + event.param.getLinkUrl()) + return true }) } } @@ -1735,13 +1830,13 @@ onScroll(callback: (event: {xOffset: number, yOffset: number}) => void) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onScroll((event) => { - console.info("x = " + event.xOffset); - console.info("y = " + event.yOffset); + console.info("x = " + event.xOffset) + console.info("y = " + event.yOffset) }) } } @@ -1768,7 +1863,7 @@ onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocatio @Entry @Component struct WebComponent { - controller:WebController = new WebController(); + controller:WebController = new WebController() build() { Column() { Web({ src:'www.example.com', controller:this.controller }) @@ -1780,11 +1875,11 @@ onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocatio confirm: { value: 'onConfirm', action: () => { - event.geolocation.invoke(event.origin, true, true); + event.geolocation.invoke(event.origin, true, true) } }, cancel: () => { - event.geolocation.invoke(event.origin, false, true); + event.geolocation.invoke(event.origin, false, true) } }) }) @@ -1793,6 +1888,38 @@ onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocatio } ``` +### onGeolocationHide + +onGeolocationHide(callback: () => void) + +通知用户先前被调用[onGeolocationShow](#ongeolocationshow)时收到地理位置信息获取请求已被取消。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ----------- | ------------------------------- | ---------------- | +| callback | () => void | 地理位置信息获取请求已被取消的回调函数。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller:WebController = new WebController() + build() { + Column() { + Web({ src:'www.example.com', controller:this.controller }) + .geolocationAccess(true) + .onGeolocationHide(() => { + console.log("onGeolocationHide...") + }) + } + } + } + ``` + ### onFullScreenEnter9+ onFullScreenEnter(callback: (event: { handler: FullScreenExitHandler }) => void) @@ -1812,14 +1939,14 @@ onFullScreenEnter(callback: (event: { handler: FullScreenExitHandler }) => void) @Entry @Component struct WebComponent { - controller:WebController = new WebController(); - handler: FullScreenExitHandler = null; + controller:WebController = new WebController() + handler: FullScreenExitHandler = null build() { Column() { Web({ src:'www.example.com', controller:this.controller }) .onFullScreenEnter((event) => { - console.log("onFullScreenEnter..."); - this.handler = event.handler; + console.log("onFullScreenEnter...") + this.handler = event.handler }) } } @@ -1845,17 +1972,17 @@ onFullScreenExit(callback: () => void) @Entry @Component struct WebComponent { - controller:WebController = new WebController(); - handler: FullScreenExitHandler = null; + controller:WebController = new WebController() + handler: FullScreenExitHandler = null build() { Column() { Web({ src:'www.example.com', controller:this.controller }) .onFullScreenExit(() => { - console.log("onFullScreenExit..."); - this.handler.exitFullScreen(); + console.log("onFullScreenExit...") + this.handler.exitFullScreen() }) .onFullScreenEnter((event) => { - this.handler = event.handler; + this.handler = event.handler }) } } @@ -1884,15 +2011,15 @@ onWindowNew(callback: (event: {isAlert: boolean, isUserTrigger: boolean, targetU @Entry @Component struct WebComponent { - controller:WebController = new WebController(); + controller:WebController = new WebController() build() { Column() { Web({ src:'www.example.com', controller: this.controller }) .multiWindowAccess(true) .onWindowNew((event) => { - console.log("onWindowNew..."); - var popController: WebController = new WebController(); - event.handler.setWebController(popController); + console.log("onWindowNew...") + var popController: WebController = new WebController() + event.handler.setWebController(popController) }) } } @@ -1918,12 +2045,12 @@ onWindowExit(callback: () => void) @Entry @Component struct WebComponent { - controller:WebController = new WebController(); + controller:WebController = new WebController() build() { Column() { Web({ src:'www.example.com', controller: this.controller }) - .onWindowExit((event) => { - console.log("onWindowExit..."); + .onWindowExit(() => { + console.log("onWindowExit...") }) } } @@ -2619,13 +2746,13 @@ requestFocus() @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('requestFocus') .onClick(() => { - this.controller.requestFocus(); + this.controller.requestFocus() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2652,14 +2779,14 @@ accessBackward(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('accessBackward') .onClick(() => { - let result = this.controller.accessBackward(); - console.log('result:' + result); + let result = this.controller.accessBackward() + console.log('result:' + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2686,14 +2813,14 @@ accessForward(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('accessForward') .onClick(() => { - let result = this.controller.accessForward(); - console.log('result:' + result); + let result = this.controller.accessForward() + console.log('result:' + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2726,15 +2853,15 @@ accessStep(step: number): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State steps: number = 2; + controller: WebController = new WebController() + @State steps: number = 2 build() { Column() { Button('accessStep') .onClick(() => { - let result = this.controller.accessStep(this.steps); - console.log('result:' + result); + let result = this.controller.accessStep(this.steps) + console.log('result:' + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2755,13 +2882,13 @@ backward(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('backward') .onClick(() => { - this.controller.backward(); + this.controller.backward() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2782,13 +2909,13 @@ forward(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('forward') .onClick(() => { - this.controller.forward(); + this.controller.forward() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2815,14 +2942,14 @@ backOrForward(step: number): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State step: number = -2; + controller: WebController = new WebController() + @State step: number = -2 build() { Column() { Button('backOrForward') .onClick(() => { - this.controller.backOrForward(this.step); + this.controller.backOrForward(this.step) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2849,14 +2976,14 @@ deleteJavaScriptRegister(name: string) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State name: string = 'Object'; + controller: WebController = new WebController() + @State name: string = 'Object' build() { Column() { Button('deleteJavaScriptRegister') .onClick(() => { - this.controller.deleteJavaScriptRegister(this.name); + this.controller.deleteJavaScriptRegister(this.name) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2883,14 +3010,14 @@ getHitTest(): HitTestType @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getHitTest') .onClick(() => { - let hitType = this.controller.getHitTest(); - console.log("hitType: " + hitType); + let hitType = this.controller.getHitTest() + console.log("hitType: " + hitType) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2916,15 +3043,15 @@ getHitTestValue(): HitTestValue @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getHitTestValue') .onClick(() => { - let hitValue = this.controller.getHitTestValue(); - console.log("hitType: " + hitValue.getType()); - console.log("extra: " + hitValue.getExtra()); + let hitValue = this.controller.getHitTestValue() + console.log("hitType: " + hitValue.getType()) + console.log("extra: " + hitValue.getExtra()) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2950,14 +3077,14 @@ getWebId(): number @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getWebId') .onClick(() => { - let id = this.controller.getWebId(); - console.log("id: " + id); + let id = this.controller.getWebId() + console.log("id: " + id) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -2983,14 +3110,14 @@ getTitle(): string @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getTitle') .onClick(() => { - let title = this.controller.getTitle(); - console.log("title: " + title); + let title = this.controller.getTitle() + console.log("title: " + title) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3016,14 +3143,14 @@ getPageHeight(): number @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getPageHeight') .onClick(() => { - let pageHeight = this.controller.getPageHeight(); - console.log("pageHeight: " + pageHeight); + let pageHeight = this.controller.getPageHeight() + console.log("pageHeight: " + pageHeight) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3049,14 +3176,14 @@ getDefaultUserAgent(): string @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getDefaultUserAgent') .onClick(() => { - let userAgent = this.controller.getDefaultUserAgent(); - console.log("userAgent: " + userAgent); + let userAgent = this.controller.getDefaultUserAgent() + console.log("userAgent: " + userAgent) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3091,7 +3218,7 @@ baseUrl为空时,通过”data“协议加载指定的一段字符串。 @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -3101,7 +3228,7 @@ baseUrl为空时,通过”data“协议加载指定的一段字符串。 data: "Source:
source
", mimeType: "text/html", encoding: "UTF-8" - }); + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3133,13 +3260,13 @@ loadUrl(options: { url: string | Resource, headers?: Array\ }) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('loadUrl') .onClick(() => { - this.controller.loadUrl({ url: 'www.example.com' }); + this.controller.loadUrl({ url: 'www.example.com' }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3160,13 +3287,13 @@ onActive(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('onActive') .onClick(() => { - this.controller.onActive(); + this.controller.onActive() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3187,13 +3314,13 @@ onInactive(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('onInactive') .onClick(() => { - this.controller.onInactive(); + this.controller.onInactive() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3219,14 +3346,14 @@ zoom(factor: number): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State factor: number = 1; + controller: WebController = new WebController() + @State factor: number = 1 build() { Column() { Button('zoom') .onClick(() => { - this.controller.zoom(this.factor); + this.controller.zoom(this.factor) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3252,14 +3379,14 @@ zoomIn(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('zoomIn') .onClick(() => { - let result = this.controller.zoomIn(); - console.log("result: " + result); + let result = this.controller.zoomIn() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3285,14 +3412,14 @@ zoomOut(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('zoomOut') .onClick(() => { - let result = this.controller.zoomOut(); - console.log("result: " + result); + let result = this.controller.zoomOut() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3313,13 +3440,13 @@ refresh() @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('refresh') .onClick(() => { - this.controller.refresh(); + this.controller.refresh() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3351,10 +3478,10 @@ registerJavaScriptProxy(options: { object: object, name: string, methodList: Arr controller: WebController = new WebController() testObj = { test: (data) => { - return "ArkUI Web Component"; + return "ArkUI Web Component" }, toString: () => { - console.log('Web Component toString'); + console.log('Web Component toString') } } build() { @@ -3365,7 +3492,7 @@ registerJavaScriptProxy(options: { object: object, name: string, methodList: Arr object: this.testObj, name: "objName", methodList: ["test", "toString"], - }); + }) }) } Web({ src: $rawfile('index.html'), controller: this.controller }) @@ -3385,8 +3512,8 @@ registerJavaScriptProxy(options: { object: object, name: string, methodList: Arr @@ -3413,7 +3540,7 @@ runJavaScript(options: { script: string, callback?: (result: string) => void }) @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() @State webResult: string = '' build() { Column() { @@ -3426,8 +3553,8 @@ runJavaScript(options: { script: string, callback?: (result: string) => void }) callback: (result: string)=> { this.webResult = result console.info(`The test() return value is: ${result}`) - }}); - console.info('url: ', e.url); + }}) + console.info('url: ', e.url) }) } } @@ -3444,7 +3571,7 @@ runJavaScript(options: { script: string, callback?: (result: string) => void }) @@ -3465,13 +3592,13 @@ stop() @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('stop') .onClick(() => { - this.controller.stop(); + this.controller.stop() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3492,13 +3619,13 @@ clearHistory(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('clearHistory') .onClick(() => { - this.controller.clearHistory(); + this.controller.clearHistory() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3519,13 +3646,13 @@ clearSslCache(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('clearSslCache') .onClick(() => { - this.controller.clearSslCache(); + this.controller.clearSslCache() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3546,13 +3673,13 @@ clearClientAuthenticationCache(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('clearClientAuthenticationCache') .onClick(() => { - this.controller.clearClientAuthenticationCache(); + this.controller.clearClientAuthenticationCache() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3579,13 +3706,13 @@ getCookieManager(): WebCookie @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getCookieManager') .onClick(() => { - let cookieManager = this.controller.getCookieManager(); + let cookieManager = this.controller.getCookieManager() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3613,13 +3740,13 @@ createWebMessagePorts(): Array\ @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - ports: WebMessagePort[] = null; + controller: WebController = new WebController() + ports: WebMessagePort[] = null build() { Column() { Button('createWebMessagePorts') .onClick(() => { - this.ports = this.controller.createWebMessagePorts(); + this.ports = this.controller.createWebMessagePorts() console.log("createWebMessagePorts size:" + this.ports.length) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -3648,10 +3775,10 @@ postMessage(options: { message: WebMessageEvent, uri: string}): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - ports: WebMessagePort[] = null; - @State sendFromEts: string = 'Send this message from ets to HTML'; - @State receivedFromHtml: string = 'Display received message send from HTML'; + controller: WebController = new WebController() + ports: WebMessagePort[] = null + @State sendFromEts: string = 'Send this message from ets to HTML' + @State receivedFromHtml: string = 'Display received message send from HTML' build() { Column() { @@ -3660,41 +3787,41 @@ postMessage(options: { message: WebMessageEvent, uri: string}): void // 输入框的内容发送到HTML TextInput({placeholder: 'Send this message from ets to HTML'}) .onChange((value: string) => { - this.sendFromEts = value; + this.sendFromEts = value }) // 1、创建两个消息端口 Button('1.CreateWebMessagePorts') .onClick(() => { - this.ports = this.controller.createWebMessagePorts(); + this.ports = this.controller.createWebMessagePorts() console.log("createWebMessagePorts size:" + this.ports.length) }) // 2、将其中一个消息端口发送到HTML侧,由HTML侧保存并使用。 Button('2.PostMessagePort') .onClick(() => { - var sendPortArray = new Array(this.ports[1]); - var msgEvent = new WebMessageEvent(); - msgEvent.setData("__init_port__"); - msgEvent.setPorts(sendPortArray); - this.controller.postMessage({message: msgEvent, uri: "*"}); + var sendPortArray = new Array(this.ports[1]) + var msgEvent = new WebMessageEvent() + msgEvent.setData("__init_port__") + msgEvent.setPorts(sendPortArray) + this.controller.postMessage({message: msgEvent, uri: "*"}) }) // 3、另一个消息端口在应用侧注册回调事件。 Button('3.RegisterCallback') .onClick(() => { this.ports[0].onMessageEvent((result: string) => { - var msg = 'Got msg from HTML: ' + result; - this.receivedFromHtml = msg; + var msg = 'Got msg from HTML: ' + result + this.receivedFromHtml = msg }) }) // 4、使用应用侧的端口给另一个已经发送到HTML的消息端口发送消息。 Button('4.SendDataToHtml5') .onClick(() => { - var msg = new WebMessageEvent(); - msg.setData(this.sendFromEts); - this.ports[0].postMessageEvent(msg); + var msg = new WebMessageEvent() + msg.setData(this.sendFromEts) + this.ports[0].postMessageEvent(msg) }) Web({ src: $rawfile("index.html"), controller: this.controller }) .javaScriptAccess(true) @@ -3758,12 +3885,12 @@ getUrl(): string @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getUrl') .onClick(() => { - console.log("url: " + this.controller.getUrl()); + console.log("url: " + this.controller.getUrl()) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3826,14 +3953,14 @@ setCookie(url: string, value: string): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('setCookie') .onClick(() => { - let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b"); - console.log("result: " + result); + let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b") + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3859,14 +3986,14 @@ saveCookieSync(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('saveCookieSync') .onClick(() => { - let result = this.controller.getCookieManager().saveCookieSync(); - console.log("result: " + result); + let result = this.controller.getCookieManager().saveCookieSync() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3899,14 +4026,14 @@ getCookie(url: string): string @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getCookie') .onClick(() => { - let value = webview.WebCookieManager.getCookie('www.example.com'); - console.log("value: " + value); + let value = webview.WebCookieManager.getCookie('www.example.com') + console.log("value: " + value) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3940,14 +4067,14 @@ setCookie(url: string, value: string): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('setCookie') .onClick(() => { - let result = web_webview.WebCookieManager.setCookie('www.example.com', 'a=b'); - console.log("result: " + result); + let result = web_webview.WebCookieManager.setCookie('www.example.com', 'a=b') + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -3974,14 +4101,14 @@ saveCookieSync(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('saveCookieSync') .onClick(() => { - let result = web_webview.WebCookieManager.saveCookieSync(); - console.log("result: " + result); + let result = web_webview.WebCookieManager.saveCookieSync() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4008,7 +4135,7 @@ saveCookieAsync(): Promise\ @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { @@ -4016,11 +4143,11 @@ saveCookieAsync(): Promise\ .onClick(() => { web_webview.WebCookieManager.saveCookieAsync() .then (function(result) { - console.log("result: " + result); + console.log("result: " + result) }) .catch(function(error) { - console.error("error: " + error); - }); + console.error("error: " + error) + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4047,15 +4174,15 @@ saveCookieAsync(callback: AsyncCallback\): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('saveCookieAsync') .onClick(() => { web_webview.WebCookieManager.saveCookieAsync(function(result) { - console.log("result: " + result); - }); + console.log("result: " + result) + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4082,14 +4209,14 @@ isCookieAllowed(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('isCookieAllowed') .onClick(() => { - let result = web_webview.WebCookieManager.isCookieAllowed(); - console.log("result: " + result); + let result = web_webview.WebCookieManager.isCookieAllowed() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4116,13 +4243,13 @@ putAcceptCookieEnabled(accept: boolean): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('putAcceptCookieEnabled') .onClick(() => { - web_webview.WebCookieManager.putAcceptCookieEnabled(false); + web_webview.WebCookieManager.putAcceptCookieEnabled(false) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4149,14 +4276,14 @@ isThirdCookieAllowed(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('isThirdPartyCookieAllowed') .onClick(() => { - let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed(); - console.log("result: " + result); + let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4183,13 +4310,13 @@ putAcceptThirdPartyCookieEnabled(accept: boolean): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('putAcceptThirdPartyCookieEnabled') .onClick(() => { - web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); + web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4216,14 +4343,14 @@ existCookie(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('existCookie') .onClick(() => { - let result = web_webview.WebCookieManager.existCookie(); - console.log("result: " + result); + let result = web_webview.WebCookieManager.existCookie() + console.log("result: " + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4244,13 +4371,13 @@ deleteEntireCookie(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('deleteEntireCookie') .onClick(() => { - web_webview.WebCookieManager.deleteEntireCookie(); + web_webview.WebCookieManager.deleteEntireCookie() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4271,13 +4398,13 @@ deleteSessionCookie(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('deleteSessionCookie') .onClick(() => { - webview.WebCookieManager.deleteSessionCookie(); + webview.WebCookieManager.deleteSessionCookie() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4308,14 +4435,14 @@ static existHttpAuthCredentials(): boolean @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('existHttpAuthCredentials') .onClick(() => { - let result = web_webview.WebDataBase.existHttpAuthCredentials(); - console.log('result: ' + result); + let result = web_webview.WebDataBase.existHttpAuthCredentials() + console.log('result: ' + result) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4337,13 +4464,13 @@ static deleteHttpAuthCredentials(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('deleteHttpAuthCredentials') .onClick(() => { - web_webview.WebDataBase.deleteHttpAuthCredentials(); + web_webview.WebDataBase.deleteHttpAuthCredentials() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4378,18 +4505,18 @@ static getHttpAuthCredentials(host: string, realm: string): Array\ @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - host: string = "www.spincast.org"; - realm: string = "protected example"; - username_password: string[]; + controller: WebController = new WebController() + host: string = "www.spincast.org" + realm: string = "protected example" + username_password: string[] build() { Column() { Button('getHttpAuthCredentials') .onClick(() => { - this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); - console.log('num: ' + this.username_password.length); + this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm) + console.log('num: ' + this.username_password.length) ForEach(this.username_password, (item) => { - console.log('username_password: ' + item); + console.log('username_password: ' + item) }, item => item) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4421,14 +4548,14 @@ static saveHttpAuthCredentials(host: string, realm: string, username: string, pa @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - host: string = "www.spincast.org"; - realm: string = "protected example"; + controller: WebController = new WebController() + host: string = "www.spincast.org" + realm: string = "protected example" build() { Column() { Button('saveHttpAuthCredentials') .onClick(() => { - web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); + web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche") }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4456,17 +4583,17 @@ static allowGeolocation(origin: string): void ```ts // xxx.ets - import web_webview from '@ohos.web.webview'; + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "file:///"; + controller: WebController = new WebController() + origin: string = "file:///" build() { Column() { Button('allowGeolocation') .onClick(() => { - web_webview.GeolocationPermissions.allowGeolocation(this.origin); + web_webview.GeolocationPermissions.allowGeolocation(this.origin) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4490,17 +4617,17 @@ static deleteGeolocation(origin: string): void ```ts // xxx.ets - import web_webview from '@ohos.web.webview'; + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "file:///"; + controller: WebController = new WebController() + origin: string = "file:///" build() { Column() { Button('deleteGeolocation') .onClick(() => { - web_webview.GeolocationPermissions.deleteGeolocation(this.origin); + web_webview.GeolocationPermissions.deleteGeolocation(this.origin) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4518,16 +4645,16 @@ static deleteAllGeolocation(): void ```ts // xxx.ets - import web_webview from '@ohos.web.webview'; + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('deleteAllGeolocation') .onClick(() => { - web_webview.GeolocationPermissions.deleteAllGeolocation(); + web_webview.GeolocationPermissions.deleteAllGeolocation() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4552,23 +4679,23 @@ static getAccessibleGeolocation(origin: string, callback: AsyncCallback\ { web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { if (error) { - console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)); - return; + console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)) + return } - console.log('getAccessibleGeolocationAsync result: ' + result); - }); + console.log('getAccessibleGeolocationAsync result: ' + result) + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4598,21 +4725,21 @@ static getAccessibleGeolocation(origin: string): Promise\ ```ts // xxx.ets - import web_webview from '@ohos.web.webview'; + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "file:///"; + controller: WebController = new WebController() + origin: string = "file:///" build() { Column() { Button('getAccessibleGeolocationPromise') .onClick(() => { web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => { - console.log('getAccessibleGeolocationPromise result: ' + result); + console.log('getAccessibleGeolocationPromise result: ' + result) }).catch(error => { - console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)); - }); + console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)) + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4636,23 +4763,23 @@ static getStoredGeolocation(callback: AsyncCallback\\>): void ```ts // xxx.ets - import web_webview from '@ohos.web.webview'; + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getStoredGeolocationAsync') .onClick(() => { web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { if (error) { - console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)); - return; + console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)) + return } - let origins_str: string = origins.join(); - console.log('getStoredGeolocationAsync origins: ' + origins_str); - }); + let origins_str: string = origins.join() + console.log('getStoredGeolocationAsync origins: ' + origins_str) + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4682,21 +4809,21 @@ static getStoredGeolocation(): Promise\\> ```ts // xxx.ets - import web_webview from '@ohos.web.webview'; + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('getStoredGeolocationPromise') .onClick(() => { web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => { - let origins_str: string = origins.join(); - console.log('getStoredGeolocationPromise origins: ' + origins_str); + let origins_str: string = origins.join() + console.log('getStoredGeolocationPromise origins: ' + origins_str) }).catch(error => { - console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)); - }); + console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)) + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -4719,12 +4846,12 @@ static deleteAllData(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('deleteAllData') .onClick(() => { - web_webview.WebStorage.deleteAllData(); + web_webview.WebStorage.deleteAllData() }) Web({ src: 'www.example.com', controller: this.controller }) .databaseAccess(true) @@ -4752,13 +4879,13 @@ static deleteOrigin(origin : string): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin"; + controller: WebController = new WebController() + origin: string = "origin" build() { Column() { Button('getHttpAuthCredentials') .onClick(() => { - web_webview.WebStorage.deleteOrigin(this.origin); + web_webview.WebStorage.deleteOrigin(this.origin) }) Web({ src: 'www.example.com', controller: this.controller }) .databaseAccess(true) @@ -4786,21 +4913,21 @@ static getOrigins(callback: AsyncCallback\>) : void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin"; + controller: WebController = new WebController() + origin: string = "origin" build() { Column() { Button('getOrigins') .onClick(() => { web_webview.WebStorage.getOrigins((error, origins) => { if (error) { - console.log('error: ' + error); - return; + console.log('error: ' + error) + return } for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin); - console.log('usage: ' + origins[i].usage); - console.log('quota: ' + origins[i].quota); + console.log('origin: ' + origins[i].origin) + console.log('usage: ' + origins[i].usage) + console.log('quota: ' + origins[i].quota) } }) }) @@ -4830,8 +4957,8 @@ static getOrigins() : Promise\> @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin"; + controller: WebController = new WebController() + origin: string = "origin" build() { Column() { Button('getOrigins') @@ -4839,13 +4966,13 @@ static getOrigins() : Promise\> web_webview.WebStorage.getOrigins() .then(origins => { for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin); - console.log('usage: ' + origins[i].usage); - console.log('quota: ' + origins[i].quota); + console.log('origin: ' + origins[i].origin) + console.log('usage: ' + origins[i].usage) + console.log('quota: ' + origins[i].quota) } }) .catch(error => { - console.log('error: ' + error); + console.log('error: ' + error) }) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4875,18 +5002,18 @@ static getOriginQuota(origin : string, callback : AsyncCallback\) : void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin"; + controller: WebController = new WebController() + origin: string = "origin" build() { Column() { Button('getOriginQuota') .onClick(() => { web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { if (error) { - console.log('error: ' + error); - return; + console.log('error: ' + error) + return } - console.log('quota: ' + quota); + console.log('quota: ' + quota) }) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4922,17 +5049,17 @@ static getOriginQuota(origin : string) : Promise\ @Component struct WebComponent { controller: WebController = new WebController(); - origin: string = "origin"; + origin: string = "origin" build() { Column() { Button('getOriginQuota') .onClick(() => { web_webview.WebStorage.getOriginQuota(this.origin) .then(quota => { - console.log('quota: ' + quota); + console.log('quota: ' + quota) }) .catch(error => { - console.log('error: ' + error); + console.log('error: ' + error) }) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4963,17 +5090,17 @@ static getOriginUsage(origin : string, callback : AsyncCallback\) : void @Component struct WebComponent { controller: WebController = new WebController(); - origin: string = "origin"; + origin: string = "origin" build() { Column() { Button('getOriginUsage') .onClick(() => { web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { if (error) { - console.log('error: ' + error); - return; + console.log('error: ' + error) + return } - console.log('usage: ' + usage); + console.log('usage: ' + usage) }) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -5009,17 +5136,17 @@ static getOriginUsage(origin : string) : Promise\ @Component struct WebComponent { controller: WebController = new WebController(); - origin: string = "origin"; + origin: string = "origin" build() { Column() { Button('getOriginQuota') .onClick(() => { web_webview.WebStorage.getOriginUsage(this.origin) .then(usage => { - console.log('usage: ' + usage); + console.log('usage: ' + usage) }) .catch(error => { - console.log('error: ' + error); + console.log('error: ' + error) }) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -5047,27 +5174,27 @@ searchAllAsync(searchString: string): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - @State searchString: string = "xxx"; + controller: WebController = new WebController() + @State searchString: string = "xxx" build() { Column() { Button('searchString') .onClick(() => { - this.controller.searchAllAsync(this.searchString); + this.controller.searchAllAsync(this.searchString) }) Button('clearMatches') .onClick(() => { - this.controller.clearMatches(); + this.controller.clearMatches() }) Button('searchNext') .onClick(() => { - this.controller.searchNext(true); + 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); + "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) }) } } @@ -5087,13 +5214,13 @@ clearMatches(): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('clearMatches') .onClick(() => { - this.controller.clearMatches(); + this.controller.clearMatches() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5121,13 +5248,13 @@ searchNext(forward: boolean): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: WebController = new WebController() build() { Column() { Button('searchNext') .onClick(() => { - this.controller.searchNext(true); + this.controller.searchNext(true) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5156,14 +5283,14 @@ onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMa @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + 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); + "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) }) } } @@ -5290,17 +5417,17 @@ storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback { - let webAsyncController = new web_webview.WebAsyncController(this.controller); + let webAsyncController = new web_webview.WebAsyncController(this.controller) webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { if (filename != null) { console.info(`save web archive success: ${filename}`) } - }); + }) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5381,16 +5508,16 @@ postMessageEvent(message: WebMessageEvent): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - ports: WebMessagePort[] = null; + controller: WebController = new WebController() + ports: WebMessagePort[] = null build() { Column() { Button('postMessageEvent') .onClick(() => { - var msg = new WebMessageEvent(); - msg.setData("post message from ets to html5"); - this.ports[0].postMessageEvent(msg); + var msg = new WebMessageEvent() + msg.setData("post message from ets to html5") + this.ports[0].postMessageEvent(msg) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5416,8 +5543,8 @@ onMessageEvent(callback: (result: string) => void): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - ports: WebMessagePort[] = null; + controller: WebController = new WebController() + ports: WebMessagePort[] = null build() { Column() { @@ -5461,9 +5588,9 @@ getData(): string Button('getPorts') .onClick(() => { var msgEvent = new WebMessageEvent(); - msgEvent.setData("message event data"); - var messageData = msgEvent.getData(); - console.log("message is:" + messageData); + msgEvent.setData("message event data") + var messageData = msgEvent.getData() + console.log("message is:" + messageData) }) } } @@ -5488,16 +5615,16 @@ setData(data: string): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - ports: WebMessagePort[] = null; + controller: WebController = new WebController() + ports: WebMessagePort[] = null build() { Column() { Button('setData') .onClick(() => { - var msg = new WebMessageEvent(); - msg.setData("post message from ets to HTML5"); - this.ports[0].postMessageEvent(msg); + var msg = new WebMessageEvent() + msg.setData("post message from ets to HTML5") + this.ports[0].postMessageEvent(msg) }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5522,16 +5649,16 @@ getPorts(): Array\ @Entry @Component struct WebComponent { - ports: WebMessagePort[] = null; + ports: WebMessagePort[] = null build() { Column() { Button('getPorts') .onClick(() => { - var sendPortArray = new Array(this.ports[0]); - var msgEvent = new WebMessageEvent(); - msgEvent.setPorts(sendPortArray); - var getPorts = msgEvent.getPorts(); - console.log("Ports is:" + getPorts); + var sendPortArray = new Array(this.ports[0]) + var msgEvent = new WebMessageEvent() + msgEvent.setPorts(sendPortArray) + var getPorts = msgEvent.getPorts() + console.log("Ports is:" + getPorts) }) } } @@ -5556,18 +5683,18 @@ setPorts(ports: Array\): void @Entry @Component struct WebComponent { - controller: WebController = new WebController(); - ports: WebMessagePort[] = null; + controller: WebController = new WebController() + ports: WebMessagePort[] = null build() { Column() { Button('setPorts') .onClick(() => { - var sendPortArray = new Array(this.ports[1]); - var msgEvent = new WebMessageEvent(); - msgEvent.setData("__init_ports__"); - msgEvent.setPorts(sendPortArray); - this.controller.postMessage({message: msgEvent, uri: "*"}); + var sendPortArray = new Array(this.ports[1]) + var msgEvent = new WebMessageEvent() + msgEvent.setData("__init_ports__") + msgEvent.setPorts(sendPortArray) + this.controller.postMessage({message: msgEvent, uri: "*"}) }) Web({ src: 'www.example.com', controller: this.controller }) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index a46b23d875209a0e3d4c1102829b4db44c3a542e..e047ed2da951bb898627b9830bdb12737d6ad4c5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -107,7 +107,7 @@ getXComponentContext() ```ts // xxx.ets -import camera from '@ohos.multimedia.camera'; +import camera from '@ohos.multimedia.camera' @Entry @Component struct PreviewArea { @@ -122,9 +122,9 @@ struct PreviewArea { }) .onLoad(() => { this.xcomponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); - this.surfaceId = this.xcomponentController.getXComponentSurfaceId(); + this.surfaceId = this.xcomponentController.getXComponentSurfaceId() camera.createPreviewOutput(this.surfaceId).then((previewOutput) => { - console.log('Promise returned with the PreviewOutput instance'); + console.log('Promise returned with the PreviewOutput instance') }) }) .width('640px') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md index 3afc63f5d272ee02dd2d8fbea1b9e45144bd4d2e..1073d8738dbf000826b4a9ab70ef4dcda1079bf5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md @@ -36,7 +36,7 @@ LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number @Entry @Component struct LongPressGestureExample { - @State count: number = 0; + @State count: number = 0 build() { Column() { @@ -47,12 +47,12 @@ struct LongPressGestureExample { // 由于repeat设置为true,长按动作存在时会连续触发,触发间隔为duration(默认值500ms) .onAction((event: GestureEvent) => { if (event.repeat) { - this.count++; + this.count++ } }) // 长按动作一结束触发 .onActionEnd(() => { - this.count = 0; + this.count = 0 }) ) } 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 0ed73fb6fbf0ea42b8d0343791b18f374f94b88e..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枚举说明 @@ -47,7 +47,7 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance | --------- | ------------ | ---- | ------------------------------------------------------------ | | fingers | number | 否 | 触发滑动的最少手指数,最小为1指, 最大取值为10指。
默认值:1 | | direction | PanDirection | 否 | 设置滑动方向,此枚举值支持逻辑与(&)和逻辑或(\|)运算。
默认值:All | -| distance | number | 否 | 最小滑动识别距离,单位为vp。
默认值:5.0
**说明:**
> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | +| distance | number | 否 | 最小滑动识别距离,单位为vp。
默认值:5.0
**说明:**
> [Tabs组件](ts-container-tabs.md)滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | **接口** @@ -75,11 +75,11 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance @Entry @Component struct PanGestureExample { - @State offsetX: number = 0; - @State offsetY: number = 0; - @State positionX: number = 0; - @State positionY: number = 0; - private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right }); + @State offsetX: number = 0 + @State offsetY: number = 0 + @State positionX: number = 0 + @State positionY: number = 0 + private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right }) build() { Column() { @@ -96,24 +96,24 @@ struct PanGestureExample { .gesture( PanGesture(this.panOption) .onActionStart((event: GestureEvent) => { - console.info('Pan start'); + console.info('Pan start') }) .onActionUpdate((event: GestureEvent) => { - this.offsetX = this.positionX + event.offsetX; - this.offsetY = this.positionY + event.offsetY; + this.offsetX = this.positionX + event.offsetX + this.offsetY = this.positionY + event.offsetY }) .onActionEnd(() => { - this.positionX = this.offsetX; - this.positionY = this.offsetY; - console.info('Pan end'); + this.positionX = this.offsetX + this.positionY = this.offsetY + console.info('Pan end') }) ) Button('修改PanGesture触发条件') .onClick(() => { // 将PanGesture手势事件触发条件改为双指以任意方向拖动 - this.panOption.setDirection(PanDirection.All); - this.panOption.setFingers(2); + this.panOption.setDirection(PanDirection.All) + this.panOption.setFingers(2) }) } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md index 4de9579ea246c83950967a078c48cb10e223bfcf..59a11311a2beb9e089a1a1f8e7d491f810c3f84f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md @@ -36,10 +36,10 @@ PinchGesture(value?: { fingers?: number, distance?: number }) @Entry @Component struct PinchGestureExample { - @State scaleValue: number = 1; - @State pinchValue: number = 1; - @State pinchX: number = 0; - @State pinchY: number = 0; + @State scaleValue: number = 1 + @State pinchValue: number = 1 + @State pinchX: number = 0 + @State pinchY: number = 0 build() { Column() { @@ -57,16 +57,16 @@ struct PinchGestureExample { .gesture( PinchGesture({ fingers: 3 }) .onActionStart((event: GestureEvent) => { - console.info('Pinch start'); + console.info('Pinch start') }) .onActionUpdate((event: GestureEvent) => { - this.scaleValue = this.pinchValue * event.scale; - this.pinchX = event.pinchCenterX; - this.pinchY = event.pinchCenterY; + this.scaleValue = this.pinchValue * event.scale + this.pinchX = event.pinchCenterX + this.pinchY = event.pinchCenterY }) .onActionEnd(() => { - this.pinchValue = this.scaleValue; - console.info('Pinch end'); + this.pinchValue = this.scaleValue + console.info('Pinch end') }) ) }.width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md index 35d0bf0f5dac4a4c7cfd34adffa646be1c995ea2..3c4a56b76cf7c8d7866566b80a38af8be0587f0f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md @@ -36,8 +36,8 @@ RotationGesture(value?: { fingers?: number, angle?: number }) @Entry @Component struct RotationGestureExample { - @State angle: number = 0; - @State rotateValue: number = 0; + @State angle: number = 0 + @State rotateValue: number = 0 build() { Column() { @@ -54,14 +54,14 @@ struct RotationGestureExample { .gesture( RotationGesture() .onActionStart((event: GestureEvent) => { - console.info('Rotation start'); + console.info('Rotation start') }) .onActionUpdate((event: GestureEvent) => { - this.angle = this.rotateValue + event.angle; + this.angle = this.rotateValue + event.angle }) .onActionEnd(() => { - this.rotateValue = this.angle; - console.info('Rotation end'); + this.rotateValue = this.angle + console.info('Rotation end') }) ) }.width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md index 7e5706a19f443340a02512f055539332cd6f3e8c..6a2daf6dff7daad928caefbb6e2ed4aa32f3c5a9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md @@ -42,8 +42,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num @Entry @Component struct SwipeGestureExample { - @State rotateAngle: number = 0; - @State speed: number = 1; + @State rotateAngle: number = 0 + @State speed: number = 1 build() { Column() { @@ -60,8 +60,8 @@ struct SwipeGestureExample { .gesture( SwipeGesture({ direction: SwipeDirection.Vertical }) .onAction((event: GestureEvent) => { - this.speed = event.speed; - this.rotateAngle = event.angle; + this.speed = event.speed + this.rotateAngle = event.angle }) ) }.width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md index d71847aebda3c1dadd06d24f135060bd3faff079..0bc8ae2307857deca73d21c02c55a1be8f53c17f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md @@ -33,7 +33,7 @@ TapGesture(value?: { count?: number, fingers?: number }) @Entry @Component struct TapGestureExample { - @State value: string = ''; + @State value: string = '' build() { Column() { @@ -42,7 +42,7 @@ struct TapGestureExample { .gesture( TapGesture({ count: 2 }) .onAction((event: GestureEvent) => { - this.value = JSON.stringify(event.fingerList[0]); + this.value = JSON.stringify(event.fingerList[0]) }) ) Text(this.value) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 40a3f6611fba38b4e552c80c95246e8ec951c5cc..d93f1e3aff2614ef0662a3ac91cf528835f750e3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -34,25 +34,25 @@ RenderingContextSettings(antialias?: boolean) ## 属性 -| 名称 | 类型 | 描述 | -| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | -| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 | -| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | -| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt'。 | -| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter'。 | -| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10。 | -| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
默认值:'normal normal 14px sans-serif'。 | -| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
默认值:'left'。 | -| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
默认值:'alphabetic'。 | -| [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。 | -| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。
默认值:0.0。 | -| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。
默认值:'source-over'。 | -| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。
默认值:0.0。 | -| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。 | -| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 | -| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
默认值:true。 | +| 名称 | 类型 | 描述 | +| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | +| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 | +| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | +| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt' | +| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter' | +| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10 | +| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
默认值:'normal normal 14px sans-serif' | +| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
默认值:'left' | +| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
默认值:'alphabetic' | +| [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。 | +| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。
默认值:0.0 | +| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。
默认值:'source-over' | +| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。
默认值:0.0 | +| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。 | +| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 | +| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 | +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
默认值:true | > **说明:** > @@ -66,8 +66,8 @@ RenderingContextSettings(antialias?: boolean) @Entry @Component struct FillStyleExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -96,8 +96,8 @@ struct FillStyleExample { @Entry @Component struct LineWidthExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -126,8 +126,8 @@ struct LineWidthExample { @Entry @Component struct StrokeStyleExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -158,8 +158,8 @@ struct StrokeStyleExample { @Entry @Component struct LineCapExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -192,8 +192,8 @@ struct LineCapExample { @Entry @Component struct LineJoinExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -227,8 +227,8 @@ struct LineJoinExample { @Entry @Component struct MiterLimit { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -262,8 +262,8 @@ struct MiterLimit { @Entry @Component struct Fonts { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -292,8 +292,8 @@ struct Fonts { @Entry @Component struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -306,9 +306,7 @@ struct CanvasExample { this.context.moveTo(140, 10) this.context.lineTo(140, 160) this.context.stroke() - this.context.font = '18px sans-serif' - this.context.textAlign = 'start' this.context.fillText('textAlign=start', 140, 60) this.context.textAlign = 'end' @@ -337,8 +335,8 @@ struct CanvasExample { @Entry @Component struct TextBaseline { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -351,9 +349,7 @@ struct TextBaseline { this.context.moveTo(0, 120) this.context.lineTo(400, 120) this.context.stroke() - this.context.font = '20px sans-serif' - this.context.textBaseline = 'top' this.context.fillText('Top', 10, 120) this.context.textBaseline = 'bottom' @@ -382,8 +378,8 @@ struct TextBaseline { @Entry @Component struct GlobalAlpha { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -415,8 +411,8 @@ struct GlobalAlpha { @Entry @Component struct LineDashOffset { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -427,8 +423,8 @@ struct LineDashOffset { .onReady(() =>{ this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) - this.context.lineDashOffset = 10.0; - this.context.stroke(); + this.context.lineDashOffset = 10.0 + this.context.stroke() }) } .width('100%') @@ -461,8 +457,8 @@ struct LineDashOffset { @Entry @Component struct GlobalCompositeOperation { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -499,8 +495,8 @@ struct GlobalCompositeOperation { @Entry @Component struct ShadowBlur { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -531,8 +527,8 @@ struct ShadowBlur { @Entry @Component struct ShadowColor { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -563,8 +559,8 @@ struct ShadowColor { @Entry @Component struct ShadowOffsetX { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -596,8 +592,8 @@ struct ShadowOffsetX { @Entry @Component struct ShadowOffsetY { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -628,9 +624,9 @@ struct ShadowOffsetY { @Entry @Component struct ImageSmoothingEnabled { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg"); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -677,8 +673,8 @@ fillRect(x: number, y: number, w: number, h: number): void @Entry @Component struct FillRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -721,8 +717,8 @@ strokeRect(x: number, y: number, w: number, h: number): void @Entry @Component struct StrokeRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -765,8 +761,8 @@ clearRect(x: number, y: number, w: number, h: number): void @Entry @Component struct ClearRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -797,12 +793,12 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void **参数:** -| 参数 | 类型 | 必填 | 默认值 | 说明 | -| -------- | ------ | ---- | ---- | --------------- | -| text | string | 是 | "" | 需要绘制的文本内容。 | -| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 | -| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 | -| maxWidth | number | 否 | - | 指定文本允许的最大宽度。 | +| 参数 | 类型 | 必填 | 默认值 | 说明 | +| -------- | ------ | ---- | ------ | ----------------------------- | +| text | string | 是 | '' | 需要绘制的文本内容。 | +| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 | +| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 | +| maxWidth | number | 否 | - | 指定文本允许的最大宽度。 | **示例:** @@ -811,8 +807,8 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void @Entry @Component struct FillText { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -842,12 +838,12 @@ strokeText(text: string, x: number, y: number, maxWidth?:number): void **参数:** -| 参数 | 类型 | 必填 | 默认值 | 描述 | -| -------- | ------ | ---- | ---- | --------------- | -| text | string | 是 | “” | 需要绘制的文本内容。 | -| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 | -| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 | -| maxWidth | number | 否 | - | 需要绘制的文本的最大宽度 。 | +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| -------- | ------ | ---- | ------ | ----------------------------- | +| text | string | 是 | '' | 需要绘制的文本内容。 | +| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 | +| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 | +| maxWidth | number | 否 | - | 需要绘制的文本的最大宽度 。 | **示例:** @@ -856,8 +852,8 @@ strokeText(text: string, x: number, y: number, maxWidth?:number): void @Entry @Component struct StrokeText { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -887,15 +883,15 @@ measureText(text: string): TextMetrics **参数:** -| 参数 | 类型 | 必填 | 默认值 | 说明 | -| ---- | ------ | ---- | ---- | ---------- | -| text | string | 是 | "" | 需要进行测量的文本。 | +| 参数 | 类型 | 必填 | 默认值 | 说明 | +| ---- | ------ | ---- | ------ | -------------------- | +| text | string | 是 | '' | 需要进行测量的文本。 | **返回值:** -| 类型 | 说明 | -| ----------- | ------- | -| TextMetrics | 文本的尺寸信息 | +| 类型 | 说明 | +| ----------- | ---------------- | +| TextMetrics | 文本的尺寸信息。 | **TextMetrics类型描述:** @@ -925,8 +921,8 @@ measureText(text: string): TextMetrics @Entry @Component struct MeasureText { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -968,8 +964,8 @@ stroke(path?: Path2D): void @Entry @Component struct Stroke { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1008,8 +1004,8 @@ beginPath(): void @Entry @Component struct BeginPath { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1055,8 +1051,8 @@ moveTo(x: number, y: number): void @Entry @Component struct MoveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1100,8 +1096,8 @@ lineTo(x: number, y: number): void @Entry @Component struct LineTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1138,8 +1134,8 @@ closePath(): void @Entry @Component struct ClosePath { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1173,10 +1169,10 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu **参数:** -| 参数 | 类型 | 必填 | 默认值 | 描述 | -| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | null | 图源对象,具体参考ImageBitmap对象。 | -| repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'。 | +| 参数 | 类型 | 必填 | 描述 | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | 图源对象,具体参考ImageBitmap对象。 | +| repetition | string | 是 | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'。
默认值:'' | **返回值:**: @@ -1191,9 +1187,9 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu @Entry @Component struct CreatePattern { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg"); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1240,8 +1236,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, @Entry @Component struct BezierCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1287,8 +1283,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void @Entry @Component struct QuadraticCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1297,10 +1293,10 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.beginPath(); - this.context.moveTo(20, 20); - this.context.quadraticCurveTo(100, 100, 200, 20); - this.context.stroke(); + this.context.beginPath() + this.context.moveTo(20, 20) + this.context.quadraticCurveTo(100, 100, 200, 20) + this.context.stroke() }) } .width('100%') @@ -1336,8 +1332,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, @Entry @Component struct Arc { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1383,8 +1379,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void @Entry @Component struct ArcTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1393,9 +1389,9 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.moveTo(100, 20); - this.context.arcTo(150, 20, 150, 70, 50); - this.context.stroke(); + this.context.moveTo(100, 20) + this.context.arcTo(150, 20, 150, 70, 50) + this.context.stroke() }) } .width('100%') @@ -1433,8 +1429,8 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number @Entry @Component struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1479,8 +1475,8 @@ rect(x: number, y: number, w: number, h: number): void @Entry @Component struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1522,8 +1518,8 @@ fill(fillRule?: CanvasFillRule): void @Entry @Component struct Fill { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1574,17 +1570,17 @@ struct Fill { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let region = new Path2D(); - region.moveTo(30, 90); - region.lineTo(110, 20); - region.lineTo(240, 130); - region.lineTo(60, 130); - region.lineTo(190, 20); - region.lineTo(270, 90); - region.closePath(); + let region = new Path2D() + region.moveTo(30, 90) + region.lineTo(110, 20) + region.lineTo(240, 130) + region.lineTo(60, 130) + region.lineTo(190, 20) + region.lineTo(270, 90) + region.closePath() // Fill path - this.context.fillStyle = 'green'; - this.context.fill(region, "evenodd"); + this.context.fillStyle = 'green' + this.context.fill(region, "evenodd") }) } .width('100%') @@ -1615,8 +1611,8 @@ clip(fillRule?: CanvasFillRule): void @Entry @Component struct Clip { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1669,9 +1665,9 @@ struct Clip { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let region = new Path2D(); - region.rect(80,10,20,130); - region.rect(40,50,100,50); + let region = new Path2D() + region.rect(80,10,20,130) + region.rect(40,50,100,50) this.context.clip(region,"evenodd") this.context.fillStyle = "rgb(255,0,0)" this.context.fillRect(0, 0, this.context.width, this.context.height) @@ -1739,8 +1735,8 @@ rotate(angle: number): void @Entry @Component struct Rotate { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1782,8 +1778,8 @@ scale(x: number, y: number): void @Entry @Component struct Scale { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1838,8 +1834,8 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时 @Entry @Component struct Transform { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1891,8 +1887,8 @@ setTransform方法使用的参数和transform()方法相同,但setTransform() @Entry @Component struct SetTransform { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1942,8 +1938,8 @@ translate(x: number, y: number): void @Entry @Component struct Translate { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1998,9 +1994,9 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: @Entry @Component struct ImageExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2009,7 +2005,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.drawImage( this.img,0,0,500,500,0,0,400,200); + this.context.drawImage( this.img,0,0,500,500,0,0,400,200) }) } .width('100%') @@ -2102,8 +2098,8 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData @Entry @Component struct GetImageData { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") build() { @@ -2113,9 +2109,9 @@ struct GetImageData { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.drawImage(this.img,0,0,130,130); - var imagedata = this.context.getImageData(50,50,130,130); - this.context.putImageData(imagedata,150,150); + this.context.drawImage(this.img,0,0,130,130) + var imagedata = this.context.getImageData(50,50,130,130) + this.context.putImageData(imagedata,150,150) }) } .width('100%') @@ -2154,8 +2150,8 @@ putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirty @Entry @Component struct PutImageData { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2268,7 +2264,7 @@ struct CanvasGetLineDash { .onReady(() => { this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) - this.context.stroke(); + this.context.stroke() let res = this.context.getLineDash() }) } @@ -2382,7 +2378,7 @@ struct ToDataURL { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var dataURL = this.context.toDataURL(); + var dataURL = this.context.toDataURL() }) } .width('100%') @@ -2405,8 +2401,8 @@ restore(): void @Entry @Component struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2415,11 +2411,11 @@ restore(): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.save(); // save the default state - this.context.fillStyle = "green"; - this.context.fillRect(20, 20, 100, 100); - this.context.restore(); // restore to the default state - this.context.fillRect(150, 75, 100, 100); + this.context.save() // save the default state + this.context.fillStyle = "green" + this.context.fillRect(20, 20, 100, 100) + this.context.restore() // restore to the default state + this.context.fillRect(150, 75, 100, 100) }) } .width('100%') @@ -2443,8 +2439,8 @@ save(): void @Entry @Component struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2453,11 +2449,11 @@ save(): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.save(); // save the default state - this.context.fillStyle = "green"; - this.context.fillRect(20, 20, 100, 100); - this.context.restore(); // restore to the default state - this.context.fillRect(150, 75, 100, 100); + this.context.save() // save the default state + this.context.fillStyle = "green" + this.context.fillRect(20, 20, 100, 100) + this.context.restore() // restore to the default state + this.context.fillRect(150, 75, 100, 100) }) } .width('100%') @@ -2490,8 +2486,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void @Entry @Component struct CreateLinearGradient { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2541,8 +2537,8 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, @Entry @Component struct CreateRadialGradient { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md b/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md index 583aa6775a1a807995a5d3c2e9628c8dfb8fae77..ec9d2e8021068ffde8cf932df2ca0fea5612f381 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md @@ -39,12 +39,12 @@ GestureGroup(mode: GestureMode, ...gesture: GestureType[]) @Entry @Component struct GestureGroupExample { - @State count: number = 0; - @State offsetX: number = 0; - @State offsetY: number = 0; - @State positionX: number = 0; - @State positionY: number = 0; - @State borderStyles: BorderStyle = BorderStyle.Solid; + @State count: number = 0 + @State offsetX: number = 0 + @State offsetY: number = 0 + @State positionX: number = 0 + @State positionY: number = 0 + @State borderStyles: BorderStyle = BorderStyle.Solid build() { Column() { @@ -57,37 +57,37 @@ struct GestureGroupExample { .margin(20) .border({ width: 3, style: this.borderStyles }) .gesture( - //以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件 + // 以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件 GestureGroup(GestureMode.Sequence, LongPressGesture({ repeat: true }) .onAction((event: GestureEvent) => { if (event.repeat) { - this.count++; + this.count++ } - console.info('LongPress onAction'); + console.info('LongPress onAction') }) .onActionEnd(() => { - console.info('LongPress end'); + console.info('LongPress end') }), PanGesture() .onActionStart(() => { - this.borderStyles = BorderStyle.Dashed; - console.info('pan start'); + this.borderStyles = BorderStyle.Dashed + console.info('pan start') }) .onActionUpdate((event: GestureEvent) => { - this.offsetX = this.positionX + event.offsetX; - this.offsetY = this.positionY + event.offsetY; - console.info('pan update'); + this.offsetX = this.positionX + event.offsetX + this.offsetY = this.positionY + event.offsetY + console.info('pan update') }) .onActionEnd(() => { - this.positionX = this.offsetX; - this.positionY = this.offsetY; - this.borderStyles = BorderStyle.Solid; - console.info('pan end'); + this.positionX = this.offsetX + this.positionY = this.offsetY + this.borderStyles = BorderStyle.Solid + console.info('pan end') }) ) .onCancel(() => { - console.info('sequence gesture canceled'); + console.info('sequence gesture canceled') }) ) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 191b9ffab8e744a75626d610f1ade17d89d61025..165735247a627b14db1e3f5b33575d59beb61038 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -17,40 +17,41 @@ addColorStop(offset: number, color: string): void **参数:** - | 参数 | 类型 | 必填 | 默认值 | 描述 | - | ------ | ------ | ---- | --------- | ---------------------------- | - | offset | number | 是 | 0 | 设置渐变点距离起点的位置占总体长度的比例,范围为0到1。 | - | color | string | 是 | '#ffffff' | 设置渐变的颜色。 | +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ------ | ------ | ---- | --------- | ---------------------------- | +| offset | number | 是 | 0 | 设置渐变点距离起点的位置占总体长度的比例,范围为0到1。 | +| color | string | 是 | '#ffffff' | 设置渐变的颜色。 | **示例:** ```ts - // xxx.ets - @Entry - @Component - struct Page45 { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') - this.context.fillStyle = grad - this.context.fillRect(0, 0, 500, 500) - }) - } - .width('100%') - .height('100%') - }} +// xxx.ets +@Entry +@Component +struct Page45 { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() => { + var grad = this.context.createLinearGradient(50, 0, 300, 100) + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') + this.context.fillStyle = grad + this.context.fillRect(0, 0, 500, 500) + }) + } + .width('100%') + .height('100%') + } +} ``` ![zh-cn_image_0000001194032516](figures/zh-cn_image_0000001194032516.png) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index 12063d494b68b2c694ec35090730d4625a81e620..8785206dcef551053042f745837aa8e664757c5d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -10,10 +10,10 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 ## 属性 -| 属性 | 类型 | 描述 | +| 属性 | 类型 | 描述 | | -------- | -------- | -------- | -| width | number | ImageBitmap的像素宽度。 | -| height | number | ImageBitmap的像素高度。 | +| width | number | ImageBitmap的像素宽度。 | +| height | number | ImageBitmap的像素高度。 | **示例:** @@ -22,9 +22,9 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 @Entry @Component struct ImageExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -33,7 +33,7 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.drawImage( this.img,0,0,500,500,0,0,400,200); + this.context.drawImage( this.img,0,0,500,500,0,0,400,200) }) } .width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md index 00ca2d47e15d1efc2e71777f11fef69a70e1eeb7..f3dd34c03f3578b435ded7faa34f7d3e01ea65a7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md @@ -10,11 +10,11 @@ ImageData对象可以存储canvas渲染的像素数据。 ## 属性 -| 属性 | 类型 | 描述 | +| 属性 | 类型 | 描述 | | -------- | -------- | -------- | -| width | number | 矩形区域实际像素宽度。 | -| height | number | 矩形区域实际像素高度。 | -| data | Uint8ClampedArray | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 | +| width | number | 矩形区域实际像素宽度。 | +| height | number | 矩形区域实际像素高度。 | +| data | Uint8ClampedArray | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 | **示例:** @@ -23,8 +23,8 @@ ImageData对象可以存储canvas渲染的像素数据。 @Entry @Component struct Translate { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") build() { @@ -34,9 +34,9 @@ struct Translate { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.drawImage(this.img,0,0,130,130); - var imagedata = this.context.getImageData(50,50,130,130); - this.context.putImageData(imagedata,150,150); + this.context.drawImage(this.img,0,0,130,130) + var imagedata = this.context.getImageData(50,50,130,130) + this.context.putImageData(imagedata,150,150) }) } .width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-ability-component.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-ability-component.md index 86c6d07bdfa37959bf8e15714ade8ce4786e2c22..086230f8b37b74650ed96120f8daf35916d14f7e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-ability-component.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-ability-component.md @@ -65,10 +65,10 @@ struct MyComponent { }, }) .onConnect(() => { - console.log('AbilityComponent connect'); + console.log('AbilityComponent connect') }) .onDisconnect(() => { - console.log('AbilityComponent disconnect'); + console.log('AbilityComponent disconnect') }) } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index 7e03805a45bfb67da494a67a7025450c05ffa42f..f22276a4149d4b76c62151cd5ca19dd0579ca9f3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -51,7 +51,7 @@ | ---------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.White | 文本颜色。 | | fontSize | number \| string | 否 | 10 | 文本大小,单位vp。 | -| badgeSize | number \| string | 否 | 16 | Badge的大小,单位vp。不支持百分比形式设置。 | +| badgeSize | number \| string | 否 | 16 | Badge的大小,单位vp。不支持百分比形式设置。当设置为非法值时,按照默认值处理。 | | badgeColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.Red | Badge的颜色。 | ## 示例 @@ -61,8 +61,8 @@ @Entry @Component struct BadgeExample { - @State counts: number = 1; - @State message: string = 'new'; + @State counts: number = 1 + @State message: string = 'new' build() { Column() { @@ -77,7 +77,7 @@ struct BadgeExample { }) { Button('message') .onClick(() => { - this.counts++; + this.counts++ }) .width(100).height(50).backgroundColor(0x317aff) }.width(100).height(50) @@ -91,7 +91,7 @@ struct BadgeExample { }) { Button('message') .onClick(() => { - this.counts++; + this.counts++ }) .width(100).height(50).backgroundColor(0x317aff) }.width(100).height(50) @@ -106,7 +106,7 @@ struct BadgeExample { }) { Button('message') .onClick(() => { - this.counts++; + this.counts++ }) .width(100).height(50).backgroundColor(0x317aff) }.width(100).height(50) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md index 27fbd173f704132eb302d27c2191d258761e8533..0628db7cfcfb691e410c71a17e98d5bcb432e0ec 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-counter.md @@ -6,10 +6,6 @@ > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - - - - ## 子组件 可以包含子组件。 @@ -24,10 +20,10 @@ Counter() 不支持通用事件和手势, 仅支持如下事件: -| 名称 | 功能描述 | +| 名称 | 功能描述 | | -------- | -------- | -| onInc(event: () => void) | 监听数值增加事件。 | -| onDec(event: () => void) | 监听数值减少事件。 | +| onInc(event: () => void) | 监听数值增加事件。 | +| onDec(event: () => void) | 监听数值减少事件。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md index 1dfbaaab730dc3fb5b98040b5a75af0c0a304f50..b04c09c7804046cfdce174a35b9291371f34ffaa 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md @@ -148,7 +148,7 @@ struct FlexExample2 { // xxx.ets @Component struct JustifyContentFlex { - @Prop justifyContent : number + justifyContent : number build() { Flex({ justifyContent: this.justifyContent }) { @@ -197,7 +197,7 @@ struct FlexExample3 { // xxx.ets @Component struct AlignItemsFlex { - @Prop alignItems : number + alignItems : number build() { Flex({ alignItems: this.alignItems }) { @@ -246,7 +246,7 @@ struct FlexExample4 { // xxx.ets @Component struct AlignContentFlex { - @Prop alignContent: number + alignContent: number build() { Flex({ wrap: FlexWrap.Wrap, alignContent: this.alignContent }) { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md index 70faec26cdd7476b88fc73e4c878f0b4cc888e9a..09544a366d55618f9b6b11f1cf57148ec0983d5a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md @@ -183,7 +183,7 @@ struct ListLanesExample { .width("90%") .editMode(true) .border({ width: 3, color: Color.Red }) - .lanes({ minLength: 40, maxLength: 60 }) + .lanes({ minLength: 40, maxLength: 40 }) .alignListItem(this.alignListItem) Button("点击更改alignListItem:" + this.alignListItem).onClick(() => { @@ -200,3 +200,4 @@ struct ListLanesExample { } ``` +![list](figures/list1.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md index 59b184476c6458269984d678abb4df476e9b576c..a5c39cd63bb5a4d76bf939a4748781b1187ebace 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md @@ -49,21 +49,21 @@ Navigator(value?: {target: string, type?: NavigationType}) @Entry @Component struct NavigatorExample { - @State active: boolean = false; + @State active: boolean = false @State Text: object = {name: 'news'} build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { Navigator({ target: 'pages/container/navigator/Detail', type: NavigationType.Push }) { Text('Go to ' + this.Text['name'] + ' page') - .width('100%').textAlign(TextAlign.Center) + .width('100%').textAlign(TextAlign.Center) }.params({ text: this.Text }) // 传参数到Detail页面 Navigator() { Text('Back to previous page').width('100%').textAlign(TextAlign.Center) }.active(this.active) .onClick(() => { - this.active = true; + this.active = true }) }.height(150).width(350).padding(35) } @@ -78,7 +78,7 @@ import router from '@ohos.router' @Component struct DetailExample { // 接收Navigator.ets的传参 - @State text: any = router.getParams().text; + @State text: any = router.getParams().text build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { @@ -87,7 +87,7 @@ struct DetailExample { } Text('This is ' + this.text['name'] + ' page') - .width('100%').textAlign(TextAlign.Center) + .width('100%').textAlign(TextAlign.Center) } .width('100%').height(200).padding({ left: 35, right: 35, top: 35 }) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index b6e0e30f1490ec2b2a80d57893ee97f41058d19d..4afb957f54b269836a33bbebba12473ce1811ba0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -168,8 +168,8 @@ scrollBy(dx: Length, dy: Length): void @Entry @Component struct ScrollExample { - scroller: Scroller = new Scroller(); - private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + scroller: Scroller = new Scroller() + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] build() { Stack({ alignContent: Alignment.TopStart }) { @@ -193,33 +193,33 @@ struct ScrollExample { .scrollBarWidth(30) // 滚动条宽度 .edgeEffect(EdgeEffect.None) .onScroll((xOffset: number, yOffset: number) => { - console.info(xOffset + ' ' + yOffset); + console.info(xOffset + ' ' + yOffset) }) .onScrollEdge((side: Edge) => { - console.info('To the edge'); + console.info('To the edge') }) .onScrollEnd(() => { - console.info('Scroll Stop'); + console.info('Scroll Stop') }) Button('scroll 150') .onClick(() => { // 点击后下滑指定距离150.0vp - this.scroller.scrollBy(0,150); + this.scroller.scrollBy(0,150) }) .margin({ top: 10, left: 20 }) Button('scroll 100') .onClick(() => { // 点击后滑动到指定位置,即下滑100.0vp的距离 - this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }); + this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) }) .margin({ top: 60, left: 20 }) Button('back top') .onClick(() => { // 点击后回到顶部 - this.scroller.scrollEdge(Edge.Top); + this.scroller.scrollEdge(Edge.Top) }) .margin({ top: 110, left: 20 }) Button('next page') .onClick(() => { // 点击后滑到下一页 - this.scroller.scrollPage({ next: true }); + this.scroller.scrollPage({ next: true }) }) .margin({ top: 170, left: 20 }) }.width('100%').height('100%').backgroundColor(0xDCDCDC) @@ -235,8 +235,8 @@ struct ScrollExample { @Component struct NestedScroll { @State listPosition: number = 0; // 0代表滚动到List顶部,1代表中间值,2代表滚动到List底部。 - private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - private scroller: Scroller = new Scroller(); + private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + private scroller: Scroller = new Scroller() build() { Flex() { @@ -245,8 +245,11 @@ struct NestedScroll { Text("Scroll Area") .width("100%").height("40%").backgroundColor(0X330000FF) .fontSize(16).textAlign(TextAlign.Center) + .onClick(() => { + this.scroller.scrollToIndex(5) + }) - List({ space: 20 }) { + List({ space: 20, scroller: this.scroller }) { ForEach(this.arr, (item) => { ListItem() { Text("ListItem" + item) @@ -255,19 +258,21 @@ struct NestedScroll { }.width("100%").height(100) }, item => item) } - .width("100%").height("50%").edgeEffect(EdgeEffect.None) + .width("100%") + .height("50%") + .edgeEffect(EdgeEffect.None) .onReachStart(() => { - this.listPosition = 0; + this.listPosition = 0 }) .onReachEnd(() => { - this.listPosition = 2; + this.listPosition = 2 }) .onScrollBegin((dx: number, dy: number) => { if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) { - this.scroller.scrollBy(0, -dy); - return { dxRemain: dx, dyRemain: 0 }; + this.scroller.scrollBy(0, -dy) + return { dxRemain: dx, dyRemain: 0 } } - this.listPosition = 1; + this.listPosition = 1 return { dxRemain: dx, dyRemain: dy }; }) 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 4ca95460bcf93cc1c07c5ea44f8de0f412d43f86..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) | 否 | 可滚动组件的控制器,与可滚动组件绑定。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ---------- | ----------------------------------------------- | ------ | -------------------------------------------- | +| footer | [CustomBuilder](ts-types.md#custombuilder8) | 否 | 设置WaterFlow尾部组件。 | +| scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器,与可滚动组件绑定。
目前瀑布流仅支持Scroller组件的scrollToIndex接口。 | ## 属性 @@ -40,8 +40,21 @@ WaterFlow(options?: {footer?: CustomBuilder, scroller?: Scroller}) | itemConstraintSize | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | 设置约束尺寸,子组件布局时,进行尺寸范围限制。 | | columnsGap | Length |设置列与列的间距。
默认值:0| | rowsGap | Length |设置行与行的间距。
默认值:0| -| layoutDirection | [FlexDirection](ts-appendix-enums.md#flexdirection) |设置布局的主轴方向。| +| layoutDirection | [FlexDirection](ts-appendix-enums.md#flexdirection) |设置布局的主轴方向。
默认值:FlexDirection.Column| +layoutDirection优先级高于rowsTemplate和columnsTemplate。根据layoutDirection设置情况,分为以下三种设置模式: + +- layoutDirection设置纵向布局(FlexDirection.Column 或 FlexDirection.ColumnReverse) + + 此时columnsTemplate有效(如果未设置,取默认值)。例如columnsTemplate设置为"1fr 1fr"、rowsTemplate设置为"1fr 1fr 1fr"时,瀑布流组件纵向布局,辅轴均分成横向2列。 + +- layoutDirection设置横向布局(FlexDirection.Row 或 FlexDirection.RowReverse) + + 此时rowsTemplate有效(如果未设置,取默认值)。例如columnsTemplate设置为"1fr 1fr"、rowsTemplate设置为"1fr 1fr 1fr"时,瀑布流组件横向布局,辅轴均分成纵向3列。 + +- layoutDirection未设置布局方向 + + 布局方向为layoutDirection的默认值:FlexDirection.Column,此时columnsTemplate有效。例如columnsTemplate设置为"1fr 1fr"、rowsTemplate设置为"1fr 1fr 1fr"时,瀑布流组件纵向布局,辅轴均分成横向2列。 ## 事件 @@ -79,8 +92,8 @@ export class WaterFlowDataSource implements IDataSource { private listeners: DataChangeListener[] = [] constructor() { - for (let i = 0; i <= 100; i++) { - this.dataArray.push(i); + for (let i = 0; i < 100; i++) { + this.dataArray.push(i) } } @@ -138,7 +151,7 @@ export class WaterFlowDataSource implements IDataSource { // 注销改变数据的控制器 unregisterDataChangeListener(listener: DataChangeListener): void { - const pos = this.listeners.indexOf(listener); + const pos = this.listeners.indexOf(listener) if (pos >= 0) { this.listeners.splice(pos, 1) } @@ -182,9 +195,9 @@ export class WaterFlowDataSource implements IDataSource { // 重新加载数据 public Reload(): void { - this.dataArray.splice(1, 1); - this.dataArray.splice(3, 2); - this.notifyDataReload(); + this.dataArray.splice(1, 1) + this.dataArray.splice(3, 2) + this.notifyDataReload() } } ``` @@ -200,8 +213,10 @@ struct WaterflowDemo { @State maxSize: number = 100 @State fontSize: number = 24 @State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F] - scroller: Scroller = new Scroller(); - datasource: WaterFlowDataSource = new WaterFlowDataSource(); + scroller: Scroller = new Scroller() + datasource: WaterFlowDataSource = new WaterFlowDataSource() + private itemWidthArray: number[] = [] + private itemHeightArray: number[] = [] // 计算flow item宽/高 getSize() { @@ -209,6 +224,18 @@ struct WaterflowDemo { return (ret > this.minSize ? ret : this.minSize) } + // 保存flow item宽/高 + getItemSizeArray() { + for (let i = 0; i < 100; i++) { + this.itemWidthArray.push(this.getSize()) + this.itemHeightArray.push(this.getSize()) + } + } + + aboutToAppear() { + this.getItemSizeArray() + } + @Builder itemFoot() { Column() { Text(`Footer`) @@ -232,8 +259,8 @@ struct WaterflowDemo { .objectFit(ImageFit.Fill) } } - .width(this.getSize()) - .height(this.getSize()) + .width(this.itemWidthArray[item]) + .height(this.itemHeightArray[item]) .backgroundColor(this.colors[item % 5]) }, item => item) } @@ -261,4 +288,4 @@ struct WaterflowDemo { } ``` -![zh-cn_image_WaterFlow.gif](figures/waterflow.gif) \ No newline at end of file +![zh-cn_image_WaterFlow.gif](figures/waterflow.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md index d2549d5bb3d22419b36aae65fc144f9bd56fb3fb..9ea5950c76a29569a4352278022675b9d4235e67 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md @@ -61,27 +61,35 @@ struct RectExample { Column({ space: 10 }) { Text('normal').fontSize(11).fontColor(0xCCCCCC).width('90%') // 绘制90% * 50的矩形 - Rect({ width: '90%', height: 50 }) - .fill(Color.Pink) - // 绘制90% * 50的矩形框 - Rect() - .width('90%') - .height(50) - .fillOpacity(0) - .stroke(Color.Red) - .strokeWidth(3) - - Text('with rounded corners').fontSize(11).fontColor(0xCCCCCC).width('90%') - // 绘制90% * 80的矩形, 圆角宽高分别为40、20 - Rect({ width: '90%', height: 80 }) - .radiusHeight(20) - .radiusWidth(40) - .fill(Color.Pink) - // 绘制90% * 80的矩形, 圆角宽高为20 + Column({ space: 5 }) { + Text('normal').fontSize(9).fontColor(0xCCCCCC).width('90%') + // 绘制90% * 50矩形 + Rect({ width: '90%', height: 50 }) + .fill(Color.Pink) + // 绘制90% * 50的矩形框 + Rect() + .width('90%') + .height(50) + .fillOpacity(0) + .stroke(Color.Red) + .strokeWidth(3) + + Text('with rounded corners').fontSize(11).fontColor(0xCCCCCC).width('90%') + // 绘制90% * 80的矩形, 圆角宽高分别为40、20 + Rect({ width: '90%', height: 80 }) + .radiusHeight(20) + .radiusWidth(40) + .fill(Color.Pink) + // 绘制90% * 80的矩形, 圆角宽高为20 + Rect({ width: '90%', height: 80 }) + .radius(20) + .fill(Color.Pink) + }.width('100%').margin({ top: 10 }) + // 绘制90% * 50矩形, 左上圆角宽高40,右上圆角宽高20,右下圆角宽高40,左下圆角宽高20 Rect({ width: '90%', height: 80 }) - .radius(20) + .radius([[40, 40], [20, 20], [40, 40], [20, 20]]) .fill(Color.Pink) - }.width('100%').margin({ top: 10 }) + }.width('100%').margin({ top: 5 }) } } ``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index c6634faf732e678e7609827cb81606410f185645..365f1333b677c98e55b5323b45cb20c2daa6ebde 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -152,12 +152,12 @@ struct ShapeExample { @Entry @Component struct ShapeMeshExample { - @State columnVal: number = 0; - @State rowVal: number = 0; - @State count: number = 0; - @State verts: Array = []; - @State shapeWidth: number = 600; - @State shapeHeight: number = 600; + @State columnVal: number = 0 + @State rowVal: number = 0 + @State count: number = 0 + @State verts: Array = [] + @State shapeWidth: number = 600 + @State shapeHeight: number = 600 build() { Column() { @@ -186,34 +186,34 @@ struct ShapeMeshExample { .height(this.shapeHeight + 'px') // 手指触摸Shape组件时会显示mesh扭曲效果 .onTouch((event: TouchEvent) => { - var touchX = event.touches[0].x * 2; - var touchY = event.touches[0].y * 2; - this.columnVal = 20; - this.rowVal = 20; - this.count = (this.columnVal + 1) * (this.rowVal + 1); - var orig = [this.count * 2]; - var index = 0; + var touchX = event.touches[0].x * 2 + var touchY = event.touches[0].y * 2 + this.columnVal = 20 + this.rowVal = 20 + this.count = (this.columnVal + 1) * (this.rowVal + 1) + var orig = [this.count * 2] + var index = 0 for (var i = 0; i <= this.rowVal; i++) { - var fy = this.shapeWidth * i / this.rowVal; + var fy = this.shapeWidth * i / this.rowVal for (var j = 0; j <= this.columnVal; j++) { - var fx = this.shapeWidth * j / this.columnVal; - orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx; - orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy; + var fx = this.shapeWidth * j / this.columnVal + orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx + orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy index++; } } for (var k = 0; k < this.count * 2; k += 2) { - var dx = touchX - orig[k + 0]; - var dy = touchY - orig[k + 1]; - var dd = dx * dx + dy * dy; - var d = Math.sqrt(dd); - var pull = 80000 / (dd * d); + var dx = touchX - orig[k + 0] + var dy = touchY - orig[k + 1] + var dd = dx * dx + dy * dy + var d = Math.sqrt(dd) + var pull = 80000 / (dd * d) if (pull >= 1) { - this.verts[k + 0] = touchX; - this.verts[k + 1] = touchY; + this.verts[k + 0] = touchX + this.verts[k + 1] = touchY } else { - this.verts[k + 0] = orig[k + 0] + dx * pull; - this.verts[k + 1] = orig[k + 1] + dy * pull; + this.verts[k + 0] = orig[k + 0] + dx * pull + this.verts[k + 1] = orig[k + 1] + dy * pull } } }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md b/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md index dcc4bf1065fbf418faf35acfe9b4392ee82ee600..d31658612f6d098d7bac990af1899929c541aed6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md @@ -85,8 +85,8 @@ @Entry @Component struct GestureSettingsExample { - @State priorityTestValue: string = ''; - @State parallelTestValue: string = ''; + @State priorityTestValue: string = '' + @State parallelTestValue: string = '' build() { Column() { @@ -95,7 +95,7 @@ struct GestureSettingsExample { .gesture( TapGesture() .onAction(() => { - this.priorityTestValue += '\nText'; + this.priorityTestValue += '\nText' })) } .height(200) @@ -107,7 +107,7 @@ struct GestureSettingsExample { .priorityGesture( TapGesture() .onAction((event: GestureEvent) => { - this.priorityTestValue += '\nColumn'; + this.priorityTestValue += '\nColumn' }), GestureMask.IgnoreInternal) Column() { @@ -115,7 +115,7 @@ struct GestureSettingsExample { .gesture( TapGesture() .onAction(() => { - this.parallelTestValue += '\nText'; + this.parallelTestValue += '\nText' })) } .height(200) @@ -127,7 +127,7 @@ struct GestureSettingsExample { .parallelGesture( TapGesture() .onAction((event: GestureEvent) => { - this.parallelTestValue += '\nColumn'; + this.parallelTestValue += '\nColumn' }), GestureMask.Normal) } } 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 b00ecd9c6be46ac428f017c744e1115b1a07cd35..eefeda849adbbaa2e4d9333f31da124de59ce010 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 @@ -3,13 +3,9 @@ 列表弹窗。 > **说明:** -> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -## 权限 - -无 - ## ActionSheet.show @@ -21,10 +17,10 @@ show(value: { title: string | Resource, message: string  | 参数名 | 参数类型 | 必填 | 参数描述 | | ---------- | -------------------------- | ------- | ----------------------------- | -| title | string \| [Resource](ts-types.md#resource) | 是 | 弹窗标题。 | -| message | string \| [Resource](ts-types.md#resource) | 是 | 弹窗内容。 | +| title | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗标题。 | +| message | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗内容。 | | autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true | -| confirm | {
value: string \| [Resource](ts-types.md#resource),
action: () => void
} | 否 | 确认按钮的文本内容和点击回调。
默认值:
value:按钮文本内容。
action: 按钮选中时的回调。 | +| confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
action: () => void
} | 否 | 确认按钮的文本内容和点击回调。
默认值:
value:按钮文本内容。
action: 按钮选中时的回调。 | | cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | | alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Bottom | | offset | {
dx: Length,
dy: Length
} | 否 | 弹窗相对alignment所在位置的偏移量。{
dx: 0,
dy: 0
} | @@ -34,8 +30,8 @@ show(value: { title: string | Resource, message: string  | 参数名 | 参数类型 | 必填 | 参数描述 | | ------ | ------------------------------------------------------------ | ---- | ----------------- | -| title | string \| [Resource](ts-types.md#resource) | 是 | 选项的文本内容。 | -| icon | string \| [Resource](ts-types.md#resource) | 否 | 选项的图标,默认无图标显示。 | +| title | [ResourceStr](ts-types.md#resourcestr) | 是 | 选项的文本内容。 | +| icon | [ResourceStr](ts-types.md#resourcestr) | 否 | 选项的图标,默认无图标显示。 | | action | ()=>void | 是 | 选项选中的回调。 | @@ -43,7 +39,6 @@ show(value: { title: string | Resource, message: string  ```ts -// xxx.ets @Entry @Component struct ActionSheetExample { @@ -54,29 +49,35 @@ struct ActionSheetExample { ActionSheet.show({ title: 'ActionSheet title', message: 'message', + autoCancel: true, confirm: { value: 'Confirm button', action: () => { - console.log('Get Alert Dialog handled'); + console.log('Get Alert Dialog handled') } }, + cancel: () => { + console.log('actionSheet canceled') + }, + alignment: DialogAlignment.Bottom, + offset: { dx: 0, dy: -10 }, sheets: [ { title: 'apples', action: () => { - console.log('apples'); + console.log('apples') } }, { title: 'bananas', action: () => { - console.log('bananas'); + console.log('bananas') } }, { title: 'pears', action: () => { - console.log('pears'); + console.log('pears') } } ] diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md index ffb54ddf303b00aa927bdc538a69dfd4022c9c66..4b3bdc23ba12b695df9873770610be0362a31628 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md @@ -11,7 +11,7 @@ | 名称 | 参数类型 | 参数描述 | | ---- | --------------- | -------- | -| show | AlertDialogParamWithConfirm \| AlertDialogParamWithButtons | 定义并显示AlertDialog组件。 | +| show | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons对象说明) | 定义并显示AlertDialog组件。 | ## AlertDialogParamWithConfirm对象说明 | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -19,11 +19,11 @@ | title | [ResourceStr](ts-types.md#resourcestr) | 否 | 弹窗标题。 | | message | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗内容。 | | autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true | -| confirm | {
value: string \| [Resource](ts-types.md#resource),
fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),
backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),
action: () => void
} | 否 | 确认按钮的文本内容、文本色、按钮背景色和点击回调。 | +| confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?:  [ResourceColor](ts-types.md#resourcecolor),
action: () => void
} | 否 | 确认按钮的文本内容、文本色、按钮背景色和点击回调。 | | cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | | alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | | offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | -| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。
**说明:**
当gridCount小于等于0时,弹窗宽度是固定的;大于0时,按照设置的数值显示宽度,最大值为4,若值为小数,则向下取整。 | +| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 | ## AlertDialogParamWithButtons对象说明 | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -31,12 +31,12 @@ | title | [ResourceStr](ts-types.md#resourcestr) | 否 | 弹窗标题。 | | message | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗内容。 | | autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true | -| primaryButton | {
value: string \| [Resource](ts-types.md#resource),
fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),
backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),
action: () => void;
} | 否 | 按钮的文本内容、文本色、按钮背景色和点击回调。 | -| secondaryButton | {
value: string \| [Resource](ts-types.md#resource),
fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),
backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),
action: () => void;
} | 否 | 按钮的文本内容、文本色、按钮背景色和点击回调。 | +| primaryButton | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void;
} | 否 | 按钮的文本内容、文本色、按钮背景色和点击回调。 | +| secondaryButton | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void;
} | 否 | 按钮的文本内容、文本色、按钮背景色和点击回调。 | | cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | | alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | | offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | -| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 | +| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 | ## DialogAlignment枚举说明 @@ -60,7 +60,6 @@ @Entry @Component struct AlertDialogExample { - build() { Column({ space: 5 }) { Button('one button dialog') @@ -69,6 +68,10 @@ struct AlertDialogExample { { title: 'title', message: 'text', + autoCancel: true, + alignment: DialogAlignment.Bottom, + offset: { dx: 0, dy: -20 }, + gridCount: 3, confirm: { value: 'button', action: () => { @@ -80,7 +83,7 @@ struct AlertDialogExample { } } ) - }) + }) .backgroundColor(0x317aff) Button('two button dialog') .onClick(() => { @@ -88,6 +91,10 @@ struct AlertDialogExample { { title: 'title', message: 'text', + autoCancel: true, + alignment: DialogAlignment.Bottom, + gridCount: 4, + offset: { dx: 0, dy: -20 }, primaryButton: { value: 'cancel', action: () => { @@ -105,7 +112,7 @@ struct AlertDialogExample { } } ) - }).backgroundColor(0x317aff) + }).backgroundColor(0x317aff) }.width('100%').margin({ top: 5 }) } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 69dce85187ccc50c4f54e253fe9ce85b5c4fcf77..86965454a213ad5db466bdbf9e2e4ac8a1f6c8ba 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -22,24 +22,9 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | cancel | () => void | 否 | 点击遮障层退出时的回调。 | | autoCancel | boolean | 否 | 是否允许点击遮障层退出。
默认值:true | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | -| offset | {
dx: Length \| [Resource](ts-types.md#resource),
dy: Length  \| [Resource](ts-types.md#resource)
} | 否 | 弹窗相对alignment所在位置的偏移量。 | +| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | | customStyle | boolean | 否 | 弹窗容器样式是否自定义。
默认值:false | -| gridCount8+ | number | 否 | 弹窗宽度占栅格宽度的个数。 | - -## DialogAlignment枚举说明 - -| 名称 | 描述 | -| ------------------------ | ------------------------------------------------------ | -| Top | 垂直顶部对齐。 | -| Center | 垂直居中对齐。 | -| Bottom | 垂直底部对齐。 | -| Default | 默认对齐。
**说明:**
与枚举值Center效果相同。 | -| TopStart8+ | 左上对齐。 | -| TopEnd8+ | 右上对齐。 | -| CenterStart8+ | 左中对齐。 | -| CenterEnd8+ | 右中对齐。 | -| BottomStart8+ | 左下对齐。 | -| BottomEnd8+ | 右下对齐。 | +| gridCount8+ | number | 否 | 弹窗宽度占[栅格宽度](../../ui/ui-ts-layout-grid-container-new.md)的个数。 | ## CustomDialogController @@ -107,17 +92,28 @@ struct CustomDialogUser { @State textValue: string = '' @State inputValue: string = 'click me' dialogController: CustomDialogController = new CustomDialogController({ - builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept, textValue: $textValue, inputValue: $inputValue }), + builder: CustomDialogExample({ + cancel: this.onCancel, + confirm: this.onAccept, + textValue: $textValue, + inputValue: $inputValue + }), cancel: this.existApp, - autoCancel: true + autoCancel: true, + alignment: DialogAlignment.Default, + offset: { dx: 0, dy: -20 }, + gridCount: 4, + customStyle: false }) onCancel() { console.info('Callback when the first button is clicked') } + onAccept() { console.info('Callback when the second button is clicked') } + existApp() { console.info('Click the callback in the blank area') } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md index df6b4f8b24e75937f0d1109893055cd3b00a03a5..25616026704a2146cdc171cd6ceb250a3aee3e79 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md @@ -49,7 +49,7 @@ struct Index { .bindContextMenu(this.MenuBuilder, ResponseType.LongPress) .onDragStart(()=>{ // 拖拽时关闭菜单 - ContextMenu.close(); + ContextMenu.close() }) } .width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 76ea01dc98ffc8ac952cba14b5192b8bebcc26da..61dd5ab8e724f97b8e9d0b4a87bc71627980d9da 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -41,13 +41,13 @@ struct TimePickerDialogExample { onAccept: (value: TimePickerResult) => { // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间 this.selectTime.setHours(value.hour, value.minute) - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) }, onCancel: () => { - console.info("TimePickerDialog:onCancel()"); + console.info("TimePickerDialog:onCancel()") }, onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) } }) }) @@ -59,13 +59,13 @@ struct TimePickerDialogExample { useMilitaryTime: true, onAccept: (value: TimePickerResult) => { this.selectTime.setHours(value.hour, value.minute) - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) }, onCancel: () => { - console.info("TimePickerDialog:onCancel()"); + console.info("TimePickerDialog:onCancel()") }, onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) } }) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 5928d2c9c52ee3b4d17d4c72b6e86853d92d4a90..f243c3342ad7ee14e6d77fece525d2c149cd1e78 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -67,8 +67,8 @@ struct FillStyleExample { .onReady(() =>{ this.offContext.fillStyle = '#0000ff' this.offContext.fillRect(20, 160, 150, 100) - var image = this.offContext.transferToImageBitmap(); - this.context.transferFromImageBitmap(image); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) }) } .width('100%') @@ -445,8 +445,8 @@ struct LineDashOffset { .onReady(() =>{ this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) - this.offContext.lineDashOffset = 10.0; - this.offContext.stroke(); + this.offContext.lineDashOffset = 10.0 + this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1016,7 +1016,7 @@ stroke(path?: Path2D): void | path | [Path2D](ts-components-canvas-path2d.md) | 否 | null | 需要绘制的Path2D。 | **示例:** - + ```ts // xxx.ets @Entry @@ -1373,10 +1373,10 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath(); - this.offContext.moveTo(20, 20); - this.offContext.quadraticCurveTo(100, 100, 200, 20); - this.offContext.stroke(); + this.offContext.beginPath() + this.offContext.moveTo(20, 20) + this.offContext.quadraticCurveTo(100, 100, 200, 20) + this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1475,9 +1475,9 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.moveTo(100, 20); - this.offContext.arcTo(150, 20, 150, 70, 50); - this.offContext.stroke(); + this.offContext.moveTo(100, 20) + this.offContext.arcTo(150, 20, 150, 70, 50) + this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1664,17 +1664,17 @@ struct Fill { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let region = new Path2D(); - region.moveTo(30, 90); - region.lineTo(110, 20); - region.lineTo(240, 130); - region.lineTo(60, 130); - region.lineTo(190, 20); - region.lineTo(270, 90); - region.closePath(); + let region = new Path2D() + region.moveTo(30, 90) + region.lineTo(110, 20) + region.lineTo(240, 130) + region.lineTo(60, 130) + region.lineTo(190, 20) + region.lineTo(270, 90) + region.closePath() // Fill path - this.offContext.fillStyle = 'green'; - this.offContext.fill(region, "evenodd"); + this.offContext.fillStyle = 'green' + this.offContext.fill(region, "evenodd") var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1766,9 +1766,9 @@ struct Clip { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let region = new Path2D(); - region.rect(80,10,20,130); - region.rect(40,50,100,50); + let region = new Path2D() + region.rect(80,10,20,130) + region.rect(40,50,100,50) this.offContext.clip(region,"evenodd") this.offContext.fillStyle = "rgb(255,0,0)" this.offContext.fillRect(0, 0, 600, 600) @@ -2214,8 +2214,8 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData @Entry @Component struct GetImageData { - private settings: RenderingContextSettings = new RenderingContextSettings(true); - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") @@ -2226,9 +2226,9 @@ struct GetImageData { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.drawImage(this.img,0,0,130,130); - var imagedata = this.offContext.getImageData(50,50,130,130); - this.offContext.putImageData(imagedata,150,150); + this.offContext.drawImage(this.img,0,0,130,130) + var imagedata = this.offContext.getImageData(50,50,130,130) + this.offContext.putImageData(imagedata,150,150) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2330,7 +2330,7 @@ struct SetLineDash { .onReady(() =>{ this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) - this.offContext.stroke(); + this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2384,7 +2384,7 @@ struct OffscreenCanvasGetLineDash { .onReady(() => { this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) - this.offContext.stroke(); + this.offContext.stroke() let res = this.offContext.getLineDash() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -2437,7 +2437,7 @@ struct ToDataURL { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var dataURL = this.offContext.toDataURL(); + var dataURL = this.offContext.toDataURL() }) } .width('100%') @@ -2534,11 +2534,11 @@ struct CanvasExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.save(); // save the default state - this.offContext.fillStyle = "green"; - this.offContext.fillRect(20, 20, 100, 100); - this.offContext.restore(); // restore to the default state - this.offContext.fillRect(150, 75, 100, 100); + this.offContext.save() // save the default state + this.offContext.fillStyle = "green" + this.offContext.fillRect(20, 20, 100, 100) + this.offContext.restore() // restore to the default state + this.offContext.fillRect(150, 75, 100, 100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2575,11 +2575,11 @@ struct CanvasExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.save(); // save the default state - this.offContext.fillStyle = "green"; - this.offContext.fillRect(20, 20, 100, 100); - this.offContext.restore(); // restore to the default state - this.offContext.fillRect(150, 75, 100, 100); + this.offContext.save() // save the default state + this.offContext.fillStyle = "green" + this.offContext.fillRect(20, 20, 100, 100) + this.offContext.restore() // restore to the default state + this.offContext.fillRect(150, 75, 100, 100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index c9f4cb0422c71be641d1ebc404597a5ca5fbcdfe..25b640efc283b43e386883a4263e172f1ba98a6c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -2,7 +2,9 @@ 状态管理模块提供了应用程序的数据存储能力、持久化数据管理能力、Ability数据存储能力和应用程序需要的环境状态,其中Ability数据存储从API version9开始支持。 -> 说明:本模块首批接口从API version 7开始支持,后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> **说明:** +> +> 本模块首批接口从API version 7开始支持,后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## AppStorage @@ -45,7 +47,7 @@ SetAndLink\(propName: string, defaultValue: T): SubscribedAbstractProperty\(propName: string, defaultValue: S): SubscribedAbstractProperty\(propName: string, newValue: T): boolean +Set\(propName: string, newValue: T): boolean 对已保存的key值,替换其value值。 @@ -165,7 +167,7 @@ let simple = AppStorage.Set('simpleProp', 121); ### SetOrCreate -SetOrCreate(propName: string, newValue: T): void +SetOrCreate\(propName: string, newValue: T): void 创建或更新setOrCreate内部的值。 @@ -180,7 +182,7 @@ SetOrCreate(propName: string, newValue: T): void | 类型 | 描述 | | ------- | ------------------------------------------------------------ | -| boolean | 如果已存在与给定键名字相同的属性,更新其值且返回true。如果不存在具有给定名称的属性,在LocalStorage中创建具有给定默认值的新属性,默认值必须是T类型。不允许undefined 或 null 返回true。 | +| boolean | 如果已存在与给定键名字相同的属性,更新其值且返回true。如果不存在具有给定名称的属性,在AppStorage中创建具有给定默认值的新属性,默认值必须是T类型。不允许undefined 或 null 返回true。 | ```ts let simple = AppStorage.SetOrCreate('simpleProp', 121) @@ -259,7 +261,7 @@ IsMutable(propName: string): boolean | boolean | 返回此属性是否存在并且是否可以改变。 | ```ts -let simple = AppStorage.IsMutable() +let simple = AppStorage.IsMutable('simpleProp') ``` ### Size @@ -518,7 +520,7 @@ delete(propName: string): boolean | 类型 | 描述 | | ------- | ------------------------------------------------------------ | -| boolean | 删除key指定的键值对,如果存在且删除成功返回true,不存在或删除失败返回false。 | +| boolean | 删除key指定的键值对。存在且删除成功,返回true。不存在、删除失败或有状态变量依旧引用propName,返回false。 | ```ts this.storage = new LocalStorage() @@ -641,12 +643,12 @@ PersistProps(properties: {key: string, defaultValue: any}[]): void; | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | ```ts -PersistentStorage.PersistProps([{'highScore', '0'},{'wightScore','1'}]) +PersistentStorage.PersistProps([{key: 'highScore', defaultValue: '0'},{key: 'wightScore',defaultValue: '1'}]) ``` ### Keys -Keys(): Array +Keys(): Array\ 返回所有持久化属性的标记。 @@ -654,7 +656,7 @@ Keys(): Array | 类型 | 描述 | | ------------- | -------------------------- | -| Array | 返回所有持久化属性的标记。 | +| Array\ | 返回所有持久化属性的标记。 | ```ts let simple = PersistentStorage.Keys() @@ -697,14 +699,14 @@ EnvProp\(key: string, value: S): boolean **内置环境变量说明:** -| key | 类型 | 说明 | -| ------------ | ------------- | ------------------- | -| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | -| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | -| fontScale | number | 字体大小比例。 | -| fontWeightScale | number | 字重比例。 | -| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | -| languageCode | string | 当前系统语言,小写字母,例如zh。 | +| key | 类型 | 说明 | +| ------------ | ------------- | ------------------- | +| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | +| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | +| fontScale | number | 字体大小比例。 | +| fontWeightScale | number | 字重比例。 | +| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | +| languageCode | string | 当前系统语言,小写字母,例如zh。 | ```ts Environment.EnvProp('accessibilityEnabled', 'default') @@ -723,12 +725,12 @@ EnvProps(props: {key: string, defaultValue: any}[]): void | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | 要关联的属性数组。 | ```ts -Environment.EnvProps([{'accessibilityEnabled', 'default'},{'accessibilityUnEnabled','undefault'}]) +Environment.EnvProps([{key: 'accessibilityEnabled', defaultValue: 'default'},{key: 'accessibilityUnEnabled', defaultValue: 'undefault'}]) ``` ### Keys -Keys(): Array +Keys(): Array\ 返回关联的系统项。 @@ -736,7 +738,7 @@ Keys(): Array | 类型 | 描述 | | ------------- | ---------------------- | -| Array | 返回关联的系统项数组。 | +| Array\ | 返回关联的系统项数组。 | ```ts let simple = Environment.Keys() diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md index 1f97c15861aa8fb6b9e0627760346dd2a5262e58..6e397391f91cbc5681d9be59b70b1c91f2b4ae10 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 @@ -21,8 +21,8 @@ | type | [TransitionType](ts-appendix-enums.md#transitiontype) | 否 | 默认包括组件新增和删除。
默认值:TransitionType.All
**说明:**
不指定Type时说明插入删除使用同一种效果。 | | opacity | number | 否 | 设置组件转场时的透明度效果,为插入时起点和删除时终点的值。
默认值:1 | | translate | {
x? : number,
y? : number,
z? : number
} | 否 | 设置组件转场时的平移效果,为插入时起点和删除时终点的值。
-x:横向的平移距离。
-y:纵向的平移距离。
-z:竖向的平移距离。 | -| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number,
centerY? : number
} | 否 | 设置组件转场时的缩放效果,为插入时起点和删除时终点的值。
-x:横向放大倍数(或缩小比例)。
-y:纵向放大倍数(或缩小比例)。
-z:竖向放大倍数(或缩小比例)。
- centerX、centerY缩放中心点。
- 中心点为0时,默认的是组件的左上角。
| -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: Angle,
centerX?: Length,
centerY?: Length
} | 否 | 设置组件转场时的旋转效果,为插入时起点和删除时终点的值。
-x:横向的旋转向量。
-y:纵向的旋转向量。
-z:竖向的旋转向量。
- centerX,centerY指旋转中心点。
- 中心点为(0,0)时,默认的是组件的左上角。 | +| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | 否 | 设置组件转场时的缩放效果,为插入时起点和删除时终点的值。
-x:横向放大倍数(或缩小比例)。
-y:纵向放大倍数(或缩小比例)。
-z:竖向放大倍数(或缩小比例)。
- centerX、centerY指缩放中心点,centerX和centerY默认值是"50%"。
- 中心点为0时,默认的是组件的左上角。
| +| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | 否 | 设置组件转场时的旋转效果,为插入时起点和删除时终点的值。
-x:横向的旋转向量。
-y:纵向的旋转向量。
-z:竖向的旋转向量。
- centerX,centerY指旋转中心点,centerX和centerY默认值是"50%"。
- 中心点为(0,0)时,默认的是组件的左上角。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index 021cc278c448273ae8cf0fbec7af7d77cf919152..82fd60584cbbf0dab54f234136342a5a760a8722 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -12,7 +12,7 @@ | 名称 | 参数 | 参数描述 | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| sharedTransition | id: string,
{
 duration?: number,
 curve?: Curve \| string,
 delay?: number,
 motionPath?:
{
 path: string,
 form?: number,
 to?: number,
 rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
- id:设置组件的id。
- duration:单位为毫秒,默认动画时长为1000毫秒。
- curve:默认曲线为Linear,有效值参见[Curve](ts-animatorproperty.md) 说明。
- delay:单位为毫秒,默认不延时播放。
- motionPath:运动路径信息。
- path:设置路径。
- from:设置起始值。
- to:设置终止值。
- rotatable:是否旋转。
- zIndex:设置Z轴。
- type:动画类型。 | +| sharedTransition | id: string,
{
 duration?: number,
 curve?: Curve \| string,
 delay?: number,
 motionPath?:
{
 path: string,
 form?: number,
 to?: number,
 rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
- id:设置组件的id。
- duration:单位为毫秒,默认动画时长为1000毫秒。
- curve:默认曲线为Linear,有效值参见[Curve](ts-animatorproperty.md)说明。
- delay:单位为毫秒,默认不延时播放。
- motionPath:运动路径信息,详细说明请参考[路径动画](ts-motion-path-animation.md)。
- path:设置路径。
- from:设置起始值。
- to:设置终止值。
- rotatable:是否旋转。
- zIndex:设置Z轴。
- type:动画类型。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md index 8ed865870ff7225f38bf74d900c6d39eee0dfc4b..cb368b39322eff4969717eafe7fd80cb7b1af116 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md @@ -4,7 +4,9 @@ > **说明:** > ->从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 此接口为系统接口。 ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 574b3191a8a64b5d67f2e5bd17408e6b71e7f72c..bc7115c31ae1c215eb12669c0b8ccc875cbdd78e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -41,19 +41,31 @@ @Entry @Component struct Index { + @State outSetValue: number = 40 build() { Row() { Column() { - Text('This is borderImage.').textAlign(TextAlign.Center) + Text('This is borderImage.').textAlign(TextAlign.Center).fontSize(50) .borderImage({ - source: "borderOrigin.png", - slice: {top:"31%", bottom:"31%", left:"31%", right:"31%"}, - width: {top:"20px", bottom:"20px", left:"20px", right:"20px"}, - outset: {top:"5px", bottom:"5px", left:"5px", right:"5px"}, + source: $r('app.media.heart'), + slice: `${this.outSetValue}%`, + width: `${this.outSetValue}px`, + outset: '5px', repeat: RepeatMode.Repeat, fill: false }) + Slider({ + value: this.outSetValue, + min: 0, + max: 100, + style: SliderStyle.OutSet + }) + .margin({ top: 30 }) + .onChange((value: number, mode: SliderChangeMode) => { + this.outSetValue = value + console.info('value:' + value + 'mode:' + mode.toString()) + }) } .width('100%') } @@ -62,7 +74,7 @@ struct Index { } ``` -![zh-cn_image_borderImage](figures/borderImage.png) +![zh-cn_image_borderImage](figures/borderImage.gif) ```ts @@ -73,7 +85,7 @@ struct Index { build() { Row() { Column() { - Text('This is gradient color.').textAlign(TextAlign.Center) + Text('This is gradient color.').textAlign(TextAlign.Center).width(68) .borderImage({ source: { angle: 90, diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index 9f43f0a9139c4489a313bdf3a208dad2d1fee6d2..f1ad36dfd7f9caec182fb07f44812112c588ebe6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -126,19 +126,19 @@ sendMouseEvent(event: MouseEvent): boolean ```ts // xxx.ets class Utils { - static rect_left; - static rect_top; - static rect_right; - static rect_bottom; - static rect_value; + static rect_left + static rect_top + static rect_right + static rect_bottom + static rect_value //获取组件所占矩形区域坐标 static getComponentRect(key) { - let strJson = getInspectorByKey(key); - let obj = JSON.parse(strJson); - console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj)); + let strJson = getInspectorByKey(key) + let obj = JSON.parse(strJson) + console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj)) let rectInfo = JSON.parse('[' + obj.$rect + ']') - console.info("[getInspectorByKey] rectInfo is: " + rectInfo); + console.info("[getInspectorByKey] rectInfo is: " + rectInfo) this.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0] this.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1] this.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0] diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md index f417b1f8d1e02e97998dda9da036f7d9931d966c..e915efdd2c514a9a015f19d6b5060cfb37e30412 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md @@ -63,7 +63,7 @@ struct FocusableExample { .width(165) .height(40) .fontColor(Color.White) - .focusOnTouch(true) //该Button组件点击后可获焦 + .focusOnTouch(true) // 该Button组件点击后可获焦 Row({ space: 5 }) { Button() .width(80) @@ -73,7 +73,7 @@ struct FocusableExample { .width(80) .height(40) .fontColor(Color.White) - .focusOnTouch(true) //该Button组件点击后可获焦 + .focusOnTouch(true) // 该Button组件点击后可获焦 } Row({ space: 5 }) { Button() @@ -86,7 +86,7 @@ struct FocusableExample { .fontColor(Color.White) } }.borderWidth(2).borderColor(Color.Red).borderStyle(BorderStyle.Dashed) - .tabIndex(1) //该Column组件为按TAB键走焦的第一个获焦的组件 + .tabIndex(1) // 该Column组件为按TAB键走焦的第一个获焦的组件 Column({ space: 5 }) { Button('Group2') .width(165) @@ -101,7 +101,7 @@ struct FocusableExample { .width(80) .height(40) .fontColor(Color.White) - .groupDefaultFocus(true) //该Button组件上级Column组件获焦时获焦 + .groupDefaultFocus(true) // 该Button组件上级Column组件获焦时获焦 } Row({ space: 5 }) { Button() @@ -114,14 +114,14 @@ struct FocusableExample { .fontColor(Color.White) } }.borderWidth(2).borderColor(Color.Green).borderStyle(BorderStyle.Dashed) - .tabIndex(2) //该Column组件为按TAB键走焦的第二个获焦的组件 + .tabIndex(2) // 该Column组件为按TAB键走焦的第二个获焦的组件 } Column({ space: 5 }) { TextInput({placeholder: 'input', text: this.inputValue}) .onChange((value: string) => { this.inputValue = value }) - .defaultFocus(true) //该TextInput组件为页面的初始默认焦点 + .defaultFocus(true) // 该TextInput组件为页面的初始默认焦点 Button('Group3') .width(165) .height(40) @@ -165,7 +165,7 @@ struct FocusableExample { .fontColor(Color.White) } }.borderWidth(2).borderColor(Color.Orange).borderStyle(BorderStyle.Dashed) - .tabIndex(3) //该Column组件为按TAB键走焦的第三个获焦的组件 + .tabIndex(3) // 该Column组件为按TAB键走焦的第三个获焦的组件 }.alignItems(VerticalAlign.Top) } } @@ -200,7 +200,7 @@ focusControl.requestFocus示例代码: 使用focusContrl.requestFocus接口使指定组件获取焦点。 ```ts // requestFocus.ets -import prompt from '@system.prompt'; +import prompt from '@ohos.prompt' @Entry @Component @@ -250,7 +250,7 @@ struct RequestFocusExample { Button("RequestFocus") .width(200).height(70).fontColor(Color.White) .onClick(() => { - var res = focusControl.requestFocus(this.selectId) //使选中的this.selectId的组件获焦 + var res = focusControl.requestFocus(this.selectId) // 使选中的this.selectId的组件获焦 if (res) { prompt.showToast({message: 'Request success'}) } else { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index 3fc5257703195527dba8b5c37e8497b69fd9bb54..fbdaabe2a84141eb2de4b1f3a6f7387cea5dc96f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -19,9 +19,9 @@ | saturate | number | 1.0 | 为当前组件添加饱和度效果,饱和度为颜色中的含色成分和消色成分(灰)的比例,入参为1时,显示原图像,大于1时含色成分越大,饱和度越大;小于1时消色成分越大,饱和度越小。(百分比) | | contrast | number | 1.0 | 为当前组件添加对比度效果,入参为对比度的值,值为1时,显示原图;大于1时,值越大对比度越高,图像越清晰醒目;小于1时,值越小对比度越低;当对比度为0时,图像变为全灰。(百分比) | | invert | number | 0 | 反转输入的图像。入参为图像反转的比例。值为1时完全反转。值为0则图像无变化。(百分比) | -| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | 为当前组件添加颜色叠加效果,入参为叠加的颜色。 | | sepia | number | 0 | 将图像转换为深褐色。入参为图像反转的比例。值为1则完全是深褐色的,值为0图像无变化。 (百分比) | | hueRotate | number \| string | '0deg' | 色相旋转效果,输入参数为旋转角度。 | +| colorBlend 8+ | [Color](ts-appendix-enums.md#color) \| string \| [Resource](ts-types.md#resource) | - | 为当前组件添加颜色叠加效果,入参为叠加的颜色。 | ## 示例 @@ -34,7 +34,7 @@ struct BlurEffectsExample { build() { Column({ space: 10 }) { - // 对字体进行模糊 + // 对字体进行模糊 Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%') Flex({ alignItems: ItemAlign.Center }) { Text('original text').margin(10) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index 832938c1704c97a306e54eb44448efc33227b9e8..86660cec308c85cb96f356972f8b34b69a3eb850 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -22,7 +22,7 @@ @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 }) { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md index 92463eb228b273e59b141143d599d52b7bbafed5..e95f066470d5881d87ab5b2e32b56b9b25a158a7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md @@ -25,7 +25,9 @@ ## 示例 -#### 普通菜单 +### 示例1 + +普通菜单 ```ts // xxx.ets @@ -58,58 +60,59 @@ struct MenuExample { ![zh-cn_image_0000001174582862](figures/zh-cn_image_0000001174582862.gif) -#### 自定义内容菜单 +### 示例2 -```ts -// xxx.ets -import router from '@system.router'; +自定义内容菜单 +```ts @Entry @Component struct MenuExample { + @State listData: number[] = [0, 0, 0] + @Builder MenuBuilder() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { - Text('text1') - .fontSize(20) - .width(100) - .height(50) - .textAlign(TextAlign.Center) - - Divider().height(10) - - Text('text2') - .fontSize(20) - .width(100) - .height(50) - .textAlign(TextAlign.Center) - - Divider().height(10) - - Button('Next') - .fontSize(20) - .width(100) - .height(50) - .onClick(() => { - router.push({ uri: 'pages/details' }) - }) - + ForEach(this.listData, (item, index) => { + Column() { + Row() { + Image($r("app.media.icon")).width(20).height(20).margin({ right: 5 }) + Text(`Menu${index + 1}`).fontSize(20) + } + .width('100%') + .height(30) + .justifyContent(FlexAlign.Center) + .align(Alignment.Center) + .onClick(() => { + console.info(`Menu${index + 1} Clicked!`) + }) + + if (index != this.listData.length - 1) { + Divider().height(10).width('80%').color('#ccc') + } + }.padding(5).height(40) + }) }.width(100) } build() { Column() { Text('click for menu') + .fontSize(20) + .margin({ top: 20 }) + .bindMenu(this.MenuBuilder) } + .height('100%') .width('100%') - .margin({ top: 5 }) - .bindMenu(this.MenuBuilder) + .backgroundColor('#f0f0f0') } } ``` ![zh-cn_image_0000001186807708](figures/zh-cn_image_0000001186807708.gif) -#### 菜单(右键触发显示) +### 示例3 + +菜单(右键触发显示) ```ts // xxx.ets diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md index 14fdb7f1a435f40f82029ed7f207d6ba4457de00..153cb7f34463052a855476f22fda8b76ddbb2233 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md @@ -29,7 +29,7 @@ struct OverlayExample { .width(240).height(240) .overlay("Winter is a beautiful season, especially when it snows.", { align: Alignment.Bottom, - offset: { x: 70, y: 100 } + offset: { x: 0, y: -15 } }) }.border({ color: Color.Black, width: 2 }) }.width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index c03775fc9dbeb8e98226a3df3aefd65d7b39d3ae..c909c6988b7711c00f9febca084960e0d3caebe1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -20,11 +20,11 @@ | -------------------------| ------------------------------------------------| -----| ----------------------------------------- | | message | string | 是 | 弹窗信息内容。 | | placementOnTop | boolean | 否 | 是否在组件上方显示,默认值为false。 | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。 | -| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | | primaryButton | {
value: string,
action: () => void
} | 否 | 第一个按钮。
value: 弹窗里主按钮的文本。
action: 点击主按钮的回调函数。 | | secondaryButton | {
value: string,
action: () => void
} | 否 | 第二个按钮。
value: 弹窗里辅助按钮的文本。
action: 点击辅助按钮的回调函数。 | | onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数isVisible为弹窗当前的显示状态。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,默认居左;箭头在气泡左右侧时,默认居上。 | +| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | ## CustomPopupOptions8+类型说明 @@ -32,13 +32,13 @@ | -------------------------| ------------------------- | ---- | ---------------------------------------------------- | | builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。 | | placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。 | -| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | | maskColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡遮障层的颜色。 | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 | | enableArrow | boolean | 否 | 是否显示箭头。
从API Version 9开始,如果箭头所在方位侧的气泡长度不足以显示下箭头,则会默认不显示箭头。比如:placement设置为Left,但气泡高度小于箭头的宽度(32vp),则实际不会显示箭头。
默认值:true | | autoCancel | boolean | 否 | 页面有操作时,是否自动关闭气泡。
默认值:true | | onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,默认居左;箭头在气泡左右侧时,默认居上。 | +| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | ## 示例 @@ -80,7 +80,7 @@ struct PopupExample { secondaryButton: { value: 'cancel', action: () => { - this.handlePopup = !this.handlePopup; + this.handlePopup = !this.handlePopup console.info('cancel Button click') } }, diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md index ffa706268f3bd28b93edaa5944ccca29d365c4ca..aa8a4903a08a0394c911ef53a797789add582904 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-touch-target.md @@ -40,7 +40,7 @@ @Entry @Component struct TouchTargetExample { - @State text: string = ""; + @State text: string = "" build() { Column({ space: 20 }) { @@ -49,7 +49,7 @@ struct TouchTargetExample { Button("button1") .responseRegion({ x: 0, y: 0, width: '50%', height: '100%' }) .onClick(() => { - this.text = 'button1 clicked'; + this.text = 'button1 clicked' }) // 热区宽度为按钮的一半,且右移一个按钮宽度,点击button2右侧左边,点击事件生效 @@ -57,14 +57,14 @@ struct TouchTargetExample { Button("button2") .responseRegion({ x: '100%', y: 0, width: '50%', height: '100%' }) .onClick(() => { - this.text = 'button2 clicked'; + this.text = 'button2 clicked' }) // 热区大小为整个按钮,且下移一个按钮高度,点击button3下方按钮大小区域,点击事件生效 Text("{x:0,y:'100%',width:'100%',height:'100%'}") Button("button3") .responseRegion({ x: 0, y: '100%', width: '100%', height: '100%' }) .onClick(() => { - this.text = 'button3 clicked'; + this.text = 'button3 clicked' }) Text(this.text).margin({ top: 50 }) 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 47ecb3066a940d21d3bab7fab265a8b3e71a4aed..ec171ef02230000c1aad11682469370568732370 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 @@ -63,3 +63,5 @@ struct TransformExample { } } ``` + +![transform](figures/transform.PNG) \ No newline at end of file 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 137610753611d3a732559979a46d274c3d8a2d9a..09c1d74aa7bb7ca2ee484ab339996a88825c94fd 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 @@ -50,12 +50,12 @@ @Entry @Component struct DragExample { - @State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six']; - @State text: string = ''; - @State bool: boolean = false; - @State appleVisible: Visibility = Visibility.Visible; - @State orangeVisible: Visibility = Visibility.Visible; - @State bananaVisible: Visibility = Visibility.Visible; + @State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six'] + @State text: string = '' + @State bool: boolean = false + @State appleVisible: Visibility = Visibility.Visible + @State orangeVisible: Visibility = Visibility.Visible + @State bananaVisible: Visibility = Visibility.Visible // 自定义拖拽过程中显示的内容 @Builder pixelMapBuilder() { @@ -87,10 +87,10 @@ struct DragExample { .backgroundColor(0xAFEEEE) .visibility(this.appleVisible) .onDragStart(() => { - this.bool = true; - this.text = 'apple'; - this.appleVisible = Visibility.None; - return this.pixelMapBuilder; + this.bool = true + this.text = 'apple' + this.appleVisible = Visibility.None + return this.pixelMapBuilder }) Text('orange') .width('25%') @@ -100,10 +100,10 @@ struct DragExample { .backgroundColor(0xAFEEEE) .visibility(this.orangeVisible) .onDragStart(() => { - this.bool = true; - this.text = 'orange'; - this.orangeVisible = Visibility.None; - return this.pixelMapBuilder; + this.bool = true + this.text = 'orange' + this.orangeVisible = Visibility.None + return this.pixelMapBuilder }) Text('banana') .width('25%') @@ -113,11 +113,11 @@ struct DragExample { .backgroundColor(0xAFEEEE) .visibility(this.bananaVisible) .onDragStart((event: DragEvent, extraParams: string) => { - console.log('Text onDragStart, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()); - this.bool = true; - this.text = 'banana'; - this.bananaVisible = Visibility.None; - return this.pixelMapBuilder; + console.log('Text onDragStart, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()) + this.bool = true + this.text = 'banana' + this.bananaVisible = Visibility.None + return this.pixelMapBuilder }) }.padding({ top: 10, bottom: 10 }).margin(10) @@ -147,20 +147,20 @@ struct DragExample { .padding(15) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) .onDragEnter((event: DragEvent, extraParams: string) => { - console.log('List onDragEnter, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()); + console.log('List onDragEnter, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()) }) .onDragMove((event: DragEvent, extraParams: string) => { - console.log('List onDragMove, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()); + console.log('List onDragMove, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()) }) .onDragLeave((event: DragEvent, extraParams: string) => { - console.log('List onDragLeave, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()); + console.log('List onDragLeave, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()) }) .onDrop((event: DragEvent, extraParams: string) => { var jsonString = JSON.parse(extraParams); if (this.bool) { // 通过splice方法插入元素 - this.numbers.splice(jsonString.insertIndex, 0, this.text); - this.bool = false; + this.numbers.splice(jsonString.insertIndex, 0, this.text) + this.bool = false } }) }.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-key.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-key.md index 2caa55742494f1bcbc26afd7a90ac4b6c98b500e..9d5189505861443501e4bb079ae2526f5c3c3624 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-key.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-key.md @@ -36,20 +36,20 @@ @Entry @Component struct KeyEventExample { - @State text: string = ''; - @State eventType: string = ''; + @State text: string = '' + @State eventType: string = '' build() { Column() { Button('KeyEvent') .onKeyEvent((event: KeyEvent) => { if (event.type === KeyType.Down) { - this.eventType = 'Down'; + this.eventType = 'Down' } if (event.type === KeyType.Up) { - this.eventType = 'Up'; + this.eventType = 'Up' } - this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText; + this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText }) Text(this.text).padding(15) }.height(300).width('100%').padding(35) 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 d3ff6dc98d86fb800a524ade36c90514e9540a07..f2a9dc6bf283788e6facda74f53f3f208cce2ebf 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 @@ -19,32 +19,32 @@ ```ts // xxx.ets -import prompt from '@ohos.prompt'; +import prompt from '@ohos.prompt' @Entry @Component struct AppearExample { - @State isShow: boolean = true; - @State changeAppear: string = 'Hide Text'; - private myText: string = 'Text for onAppear'; + @State isShow: boolean = true + @State changeAppear: string = 'Hide Text' + private myText: string = 'Text for onAppear' build() { Column() { Button(this.changeAppear) .onClick(() => { - this.isShow = !this.isShow; + this.isShow = !this.isShow }).margin(15) if (this.isShow) { Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold) .onAppear(() => { - this.changeAppear = 'Hide Text'; + this.changeAppear = 'Hide Text' prompt.showToast({ message: 'The text is shown', duration: 2000 }) }) .onDisAppear(() => { - this.changeAppear = 'Show Text'; + this.changeAppear = 'Show Text' prompt.showToast({ message: 'The text is hidden', duration: 2000 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md index f24bb33026d8b5a126b960bfb387be2a506b8423..5534089ecbe6ea7df5323922809d4e9ab1dca920 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md @@ -45,42 +45,42 @@ @Entry @Component struct TouchExample { - @State text: string = ''; - @State eventType: string = ''; + @State text: string = '' + @State eventType: string = '' build() { Column() { Button('Touch').height(40).width(100) .onTouch((event: TouchEvent) => { if (event.type === TouchType.Down) { - this.eventType = 'Down'; + this.eventType = 'Down' } if (event.type === TouchType.Up) { - this.eventType = 'Up'; + this.eventType = 'Up' } if (event.type === TouchType.Move) { - this.eventType = 'Move'; + this.eventType = 'Move' } this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: ' + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:(' + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:' - + event.target.area.width + '\nheight:' + event.target.area.height; + + event.target.area.width + '\nheight:' + event.target.area.height }) Button('Touch').height(50).width(200).margin(20) .onTouch((event: TouchEvent) => { if (event.type === TouchType.Down) { - this.eventType = 'Down'; + this.eventType = 'Down' } if (event.type === TouchType.Up) { - this.eventType = 'Up'; + this.eventType = 'Up' } if (event.type === TouchType.Move) { - this.eventType = 'Move'; + this.eventType = 'Move' } this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: ' + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:(' + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:' - + event.target.area.width + '\nheight:' + event.target.area.height; + + event.target.area.width + '\nheight:' + event.target.area.height }) Text(this.text) }.width('100%').padding(30) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-focus-event.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-focus-event.md index 3f9aa271b4b137b384542758d11a5815086e1c34..8da2d801d8da08ef4d43be199eca9e23301a665a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-focus-event.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-focus-event.md @@ -24,9 +24,9 @@ @Entry @Component struct FocusEventExample { - @State oneButtonColor: string = '#FFC0CB'; - @State twoButtonColor: string = '#87CEFA'; - @State threeButtonColor: string = '#90EE90'; + @State oneButtonColor: string = '#FFC0CB' + @State twoButtonColor: string = '#87CEFA' + @State threeButtonColor: string = '#90EE90' build() { Column({ space: 20 }) { @@ -38,10 +38,10 @@ struct FocusEventExample { .fontColor(Color.Black) .focusable(true) .onFocus(() => { - this.oneButtonColor = '#FF0000'; + this.oneButtonColor = '#FF0000' }) .onBlur(() => { - this.oneButtonColor = '#FFC0CB'; + this.oneButtonColor = '#FFC0CB' }) Button('Second Button') .backgroundColor(this.twoButtonColor) @@ -50,10 +50,10 @@ struct FocusEventExample { .fontColor(Color.Black) .focusable(true) .onFocus(() => { - this.twoButtonColor = '#FF0000'; + this.twoButtonColor = '#FF0000' }) .onBlur(() => { - this.twoButtonColor = '#87CEFA'; + this.twoButtonColor = '#87CEFA' }) Button('Third Button') .backgroundColor(this.threeButtonColor) @@ -62,10 +62,10 @@ struct FocusEventExample { .fontColor(Color.Black) .focusable(true) .onFocus(() => { - this.threeButtonColor = '#FF0000'; + this.threeButtonColor = '#FF0000' }) .onBlur(() => { - this.threeButtonColor = '#90EE90'; + this.threeButtonColor = '#90EE90' }) }.width('100%').margin({ top: 20 }) } diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-CommonEventService.md b/zh-cn/application-dev/reference/errorcodes/errcode-CommonEventService.md new file mode 100644 index 0000000000000000000000000000000000000000..9c5fe5a338ad282b66cced8a4ebe3ef477580545 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errcode-CommonEventService.md @@ -0,0 +1,127 @@ +# 事件错误码 + +## 1500001 want中Action为空 + +**错误信息** +Want action is null + +**错误描述** +发送事件的want中的Action属性为空时系统会产生此错误码。 + +**可能原因** +发送事件的want中的Action属性为空。 + +**处理步骤** +检查传入want的Action属性是否为空。 + +## 1500002 沙箱引用无法发送公共事件 + +**错误信息** +sandbox application can not send common event + +**错误描述** +沙箱引用无法发送公共事件。 + +**可能原因** +事件发送方应用为沙箱应用,发送事件会被拦截。 + +**处理步骤** +检查事件发送是否为沙箱应用,若是,则无法发送。请不要使用沙箱应用发送事件。 + +## 1500003 事件发送频率过高 + +**错误信息** +common event send frequency too high + +**错误描述** +应用发送事件过于频繁。 + +**可能原因** +短时间内应用发送过多事件。 + +**处理步骤** +检查应用是否过于频繁地发送事件。 + +## 1500004 无法发送系统公共事件 + +**错误信息** +not System services or System app + +**错误描述** +当前应用无法发送系统公共事件。 + +**可能原因** +非系统应用或非系统服务发送系统公共事件。 + +**处理步骤** +检查应用是否为系统应用或者系统服务;若不是,则无法发送。 + +## 1500005 未找到订阅者 + +**错误信息** +subscriber can not found + +**错误描述** +找不到订阅者。 + +**可能原因** +订阅者被删除。 + +**处理步骤** +检查是否有重复取消订阅。 + +## 1500006 无效userId + +**错误信息** +usreId is invalid + +**错误描述** +无效的userId。 + +**可能原因** +和系统userId不一致或不是系统应用或子系统进程。 + +**处理步骤** +检查当前userId是否和系统userId一致;若不一致,检查系统应用或子系统进程。 + +## 1500007 IPC请求发送失败 + +**错误信息** +message send error + +**错误描述** +IPC发送请求失败。 + +**可能原因** +没有成功创建连接对象。 + +**处理步骤** +请勿频繁建立链接,稍后重新尝试。 + +## 1500008 读取数据失败 + +**错误信息** +CEMS error + +**错误描述** +服务端发生错误。 + +**可能原因** +服务端处理数据时发现业务异常。 + +**处理步骤** +稍后重新尝试。 + +## 1500009 system error + +**错误信息** +system error + +**错误描述** +处理业务时系统发生异常,如获取系统当前时间失败。 + +**可能原因** +系统故障,获取系统当前时间发生异常。 + +**处理步骤** +稍后重新尝试。 diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-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/errcode-inputmethod-framework.md b/zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md new file mode 100644 index 0000000000000000000000000000000000000000..1a1ff6b678814c19bcceb1ec491d27488c6e0477 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md @@ -0,0 +1,145 @@ +# 输入法框架错误码 + +## 12800001 包管理服务异常 + +**错误信息** + +Package manager error. + +**错误描述** + +当依赖包管理接口来获取一些信息失败时,系统会报此错误码。 + +**可能原因** + +在调用getInputMethods、listCurrentInputMethodSubtype等接口获取输入法及子类型的时候,由于获取包管理服务异常时会报错。 + +**处理步骤** + +无 + +## 12800002 输入法应用异常 + +**错误信息** + +Input method engine error. + +**错误描述** + +用户调用输入法应用接口失败时,系统会报此错误码。 + +**可能原因** + +在执行显示键盘、隐藏键盘等操作时,由于输入法应用进程死亡导致操作失败时会报错。 + +**处理步骤** + +查看输入法应用进程是否正常。例如再次在普通应用(微信、联系人等第三方应用)中点击对话框看键盘能否被正常拉起。 + +## 12800003 客户端应用异常 + +**错误信息** + +Input method client error. + +**错误描述** + +当三方应用(微信、设置、联系人等)的对话框等编辑控件调用显示键盘、隐藏键盘失败时,系统会报此错误码。 + +**可能原因** + +三方应用客户端服务异常导致输入法应用与三方应用客户端断链。 + +**处理步骤** + +重新将输入法应用与三方应用进行绑定:将三方应用后台进程杀死,重新启动三方应用,通过点击对话框等方式触发输入法键盘的显示,若键盘正常显示,则问题解决。 + +## 12800004 按键事件处理异常 + +**错误信息** + +Key event processing error. + +**错误描述** + +当按键事件异常时,系统会报此错误码。 + +**可能原因** + +按键事件分发、消费、监听异常时会报错。 + +**处理步骤** + +无 + +## 12800005 配置固化失败 + +**错误信息** + +Configuration persisting error. + +**错误描述** + +当保存配置失败时,系统会报此错误码。 + +**可能原因** + +当调用切换输入法接口的时候,会保存输入法的配置参数,系统参数配置模块异常导致参数保存失败时会报错。 + +**处理步骤** + +执行hdc shell param get persist.sys.default_ime查看默认输入法参数,若可查看,则系统参数配置模块正常,可重启设备进行尝试。 + +## 12800006 输入法控制器异常 + +**错误信息** + +Input method controller error. + +**错误描述** + +当获取到输入法控制器失败时,系统会报此错误码。 + +**可能原因** + +在调用getCotroller接口获取输入法控制器InputMethodController时发生异常时会报错。 + +**处理步骤** + +无。 + +## 12800007 输入法设置器异常 + +**错误信息** + +Input method settings extension error. + +**错误描述** + +当获取到输入法设置器发生错误时,系统会报此错误码。 + +**可能原因** + +在调用getSetting接口获取输入法设置器InputMethodSetting时发生异常时会报错。 + +**处理步骤** + +无。 + +## 12800008 输入法管理服务异常 + +**错误信息** + +Input method manager service error. + +**错误描述** + +获取输入法管理服务异常时,系统会报此错误码。 + +**可能原因** + +当调用[输入法框架](../apis/js-apis-inputmethod.md)中的任何接口都有可能由于依赖输入法管理服务,而服务找不到时发生此异常。 + +**处理步骤** + +通过ps -A|grep inputmethod查看是否存在输入法服务的进程号,如果存在,则服务正常。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-ability.md b/zh-cn/application-dev/reference/errorcodes/errorcode-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..d5aa62b58c0c5d3a97e72f9d9e0cc82afb15a30f --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-ability.md @@ -0,0 +1,713 @@ +# 元能力子系统错误码 + +## 16000001 指定的Ability名称不存在 + +**错误信息** + +Input error. The specified ability name does not exist. + +**错误描述** + +当指定的Ability名称不存在时,方法将返回该错误码。 + +**可能原因** + +所查询的Ability不存在。 + +**处理步骤** + +1. 检查包名称是否正确。 +2. 检查包名对应的Ability是否正确。 + +## 16000002 接口调用Ability类型错误 + +**错误信息** + +Ability type error. The specified ability type is wrong. + +**错误描述** + +当接口调用Ability类型错误时,方法将返回该错误码。 + +**可能原因** + +接口调用所在的Ability类型不支持该接口调用。 + +**处理步骤** + +1. 检查包名对应的Ability是否正确。 +2. 根据Ability类型调用不同接口。 + +## 16000003 指定的ID不存在 + +**错误信息** + +Input error. The specified id does not exist. + +**错误描述** + +当指定的ID不存在时,方法将返回该错误码。 + +**可能原因** + +操作的目标ID不存在。 + +**处理步骤** + +确认操作的ID是否存在。 + +## 16000004 可见性校验失败 + +**错误信息** + +Visibility verification failed. + +**错误描述** + +当可见性校验失败时,方法将返回该错误码。 + +**可能原因** + +应用可见性校验失败。 + +**处理步骤** + +请检查应用是否满足被拉起应用可见性限制。 + +## 16000006 不允许跨用户操作 + +**错误信息** + +Can not cross user operations. + +**错误描述** + +当应用跨用户操作时,方法将返回该错误码。 + +**可能原因** + +应用进行了跨用户操作。 + +**处理步骤** + +确认是否进行了跨用户操作。 + +## 16000007 服务繁忙 + +**错误信息** + +Service busyness. There are concurrent tasks, waiting for retry. + +**错误描述** + +当服务繁忙时,方法将返回该错误码。 + +**可能原因** + +服务繁忙。 + +**处理步骤** + +服务繁忙,请稍后重试。 + +## 16000008 众测应用到期 + +**错误信息** + +Crowdtest App Expiration. + +**错误描述** + +当众测应用到期时,方法将返回该错误码。 + +**可能原因** + +众测应用到期,无法打开。 + +**处理步骤** + +请检查应用是否众测到期。 + +## 16000009 wukong模式,不允许启动/停止ability + +**错误信息** + +Can not start ability in wukong mode. + +**错误描述** + +当wukong模式下,启动/停止ability时,方法将返回该错误码。 + +**可能原因** + +wukong模式,不允许启动/停止ability。 + +**处理步骤** + +请勿在wukong模型下启动/停止Ability。 + +## 16000010 不允许带迁移flag + +**错误信息** + +Can not operation with continue flag. + +**错误描述** + +当调用携带迁移flag时,方法将返回该错误码。 + +**可能原因** + +当前调用不允许携带迁移flag。 + +**处理步骤** + +请检查是否携带迁移flag。 + +## 16000011 上下文对象不存在 + +**错误信息** + +Context does not exist. + +**错误描述** + +当上下文对象不存在时,方法将返回该错误码。 + +**可能原因** + +当前上下文对象不存在。 + +**处理步骤** + +请检查上下文对象是否可用。 + +## 16000050 内部错误 + +**错误信息** + +Internal Error. + +**错误描述** + +当内存申请、多线程处理异常等内部处理错误时,方法将返回该错误码。 + +**可能原因** + +内存申请、多线程处理等内核通用错误。 + +**处理步骤** + +确认系统内存是否足够。 + +## 16000051 网络异常 + +**错误信息** + +Network error. The network is abnormal. + +**错误描述** + +当网络异常时,方法将返回该错误码。 + +**可能原因** + +网络不可用。 + +**处理步骤** + +网络异常,请稍后重试,或者重连网络尝试。 + +## 16000052 不支持免安装 + +**错误信息** + +Free install not support. The applicaiotn dose not support free install. + +**错误描述** + +当前应用不支持免安装时,方法将返回该错误码。 + +**可能原因** + +应用包不满足免安装要求,如包大小超过限制等。 + +**处理步骤** + +请检查应用是否支持免安装。 + +## 16000053 非顶层应用 + +**错误信息** + +Not top ability. The application is not top ability. + +**错误描述** + +当前应用未显示在界面顶层时,方法将返回该错误码。 + +**可能原因** + +应用未显示在界面顶层。 + +**处理步骤** + +请检查应用是否显示在界面顶层。 + +## 16000054 免安装服务繁忙 + +**错误信息** + +Free install busyness. There are concurrent tasks, waiting for retry. + +**错误描述** + +当免安装服务繁忙时,方法将返回该错误码。 + +**可能原因** + +已有相同免安装任务在执行。 + +**处理步骤** + +免安装服务繁忙,请稍后重试。 + +## 16000055 免安装超时 + +**错误信息** + +Free install timeout. + +**错误描述** + +当免安装超时时,方法将返回该错误码。 + +**可能原因** + +免安装超时。 + +**处理步骤** + +免安装超时,请稍后重试。 + +## 16000056 不允许免安装其他应用 + +**错误信息** + +Can not free install other ability. + +**错误描述** + +当免安装其他应用时,方法将返回该错误码。 + +**可能原因** + +不允许免安装其他应用。 + +**处理步骤** + +确认免安装的是正确的应用。 + +## 16000057 不支持跨设备免安装 + +**错误信息** + +Not support cross device free install. + +**错误描述** + +当持跨设备免安装时,方法将返回该错误码。 + +**可能原因** + +不支持跨设备免安装。 + +**处理步骤** + +确认为非跨设备免安装应用。 + +## 16000101 执行shell命令失败 + +**错误信息** + +execute shell command failed. + +**错误描述** + +当命令不是有效的shell命令时,方法将返回该错误码。 + +**可能原因** + +命令不是有效的shell命令。 + +**处理步骤** + +检查命令是否为有效的shell命令。 + +## 16000151 无效wantAgent对象 + +**错误信息** + +Invalid wantagent object. + +**错误描述** + +当传入接口的wantAgent对象无效时,方法将返回该错误码。 + +**可能原因** + +传入接口的wantAgent对象无效。 + +**处理步骤** + +检查传入接口的wantAgent对象。 + +## 16000152 未找到wantAgent对象 + +**错误信息** + +wantAgent object not found. + +**错误描述** + +当传入接口的wantAgent对象不存在时,方法将返回该错误码。 + +**可能原因** + +传入接口的wantAgent对象不存在。 + +**处理步骤** + +检查传入接口的wantAgent对象是否合法。 + +## 16000153 wangAgent对象已取消 + +**错误信息** + +wangAgent object canceled. + +**错误描述** + +当传入接口的wangAgent对象已取消时,方法将返回该错误码。 + +**可能原因** + +传入接口的触发的wantAgent已取消。 + +**处理步骤** + +检查触发的wantAgent对象是否已取消。 + +## 16100001 指定Uri的Ability不存在 + +**错误信息** + +Input error. The specified uri does not exist. + +**错误描述** + +当指定Uri的Ability不存在时,方法将返回该错误码。 + +**可能原因** + +所查询的Ability不存在。 + +**处理步骤** + +确认查询的Ability是否存在。 + +## 16100002 接口调用Ability类型错误 + +**错误信息** + +Ability type error. The specified ability type is wrong. + +**错误描述** + +当接口调用Ability类型错误时,方法将返回该错误码。 + +**可能原因** + +接口调用所在的Ability类型不支持该接口调用。 + +**处理步骤** + +1. 检查包名对应的Ability是否正确。 +2. 根据Ability类型调用不同接口。 + +## 16200001 通用组件客户端(Caller)已回收 + +**错误信息** + +Caller released. The caller has been released. + +**错误描述** + +当通用组件客户端(Caller)已回收时,方法将返回该错误码。 + +**可能原因** + +通用组件客户端(Caller)已回收。 + +**处理步骤** + +请重新注册有效通用组件客户端调用接口。 + +## 16200002 通用组件服务端(Callee)无效 + +**错误信息** + +Callee Invalid. The callee does not exist. + +**错误描述** + +当通用组件服务端(Callee)无效时,方法将返回该错误码。 + +**可能原因** + +通用组件服务端(Callee)不存在。 + +**处理步骤** + +请检查通用组件服务端是否存在。 + +## 16200003 回收失败 + +**错误信息** + +Release error. The caller does not call any callee. + +**错误描述** + +当回收失败时,方法将返回该错误码。 + +**可能原因** + +通用组件客户端(Caller)对象未注册通用组件服务端(Callee)。 + +**处理步骤** + +请检查是否已注册通用组件服务端。 + +## 16200004 方法已注册 + +**错误信息** + +Method registered. The method has registered. + +**错误描述** + +当方法已注册时,方法将返回该错误码。 + +**可能原因** + +方法已在通用组件服务端注册过。 + +**处理步骤** + +请检查是否已注册该方法。 + +## 16200005 方法未注册 + +**错误信息** + +Method not registered. The method has not registered. + +**错误描述** + +当方法未注册时,方法将返回该错误码。 + +**可能原因** + +方法未在通用组件服务端注册。 + +**处理步骤** + +请检查是否未注册该方法。 + +## 16300001 指定的任务不存在 + +**错误信息** + +Mission id error. The specified mission id does not exist. + +**错误描述** + +当指定的任务不存在时,方法将返回该错误码。 + +**可能原因** + +操作的目标任务不存在。 + +**处理步骤** + +确认操作的任务是否存在。 + +## 16300002 指定的任务监听器不存在 + +**错误信息** + +Input error. The specified mission listener id does not exist. + +**错误描述** + +当指定的任务监听器不存在时,方法将返回该错误码。 + +**可能原因** + +操作的目标任务监听器不存在。 + +**处理步骤** + +确认操作的任务监听器是否存在。 + +## 18500001 指定的包名无效 + +**错误信息** + +The specified bundleName is invalid. + +**错误描述** + +当指定的包名无效时,方法将返回该错误码。 + +**可能原因** + +待查询的bundle不存在或未安装。 + +**处理步骤** + +确认查询的应用是否已安装。 + +## 18500002 指定的补丁包无效 + +**错误信息** + +The specified hqf is invalid. Hqf may not exist or inaccessible. + +**错误描述** + +当指定的补丁包无效,补丁包不存在或不可访问时,方法将返回该错误码。 + +**可能原因** + +待安装的补丁包文件不存在或不可以访问。 + +**处理步骤** + +1. 请检查传递的补丁包文件路径是否有效。 +2. 请检查是否有权限访问此补丁包文件。 + +## 18500003 补丁包部署失败 + +**错误信息** + +Deploy hqf failed. + +**错误描述** + +当补丁包部署失败时,方法将返回该错误码。 + +**可能原因** + +1. patch.json中type只能为patch或者hotreload,否则部署失败。 +2. 若对应bundleName的hap包未安装,部署失败。 +3. bundleName、versionCode必须和已安装的hap应用相同,如果为patch类型,还需确保versionName相同,否则部署失败。 +4. 如果已经部署过补丁包,新部署的补丁包的versionCode必须大于之前补丁包的versionCode,否则部署失败。 +5. 对于patch类型的补丁会校验签名信息,使用的签名证书需要和应用相同,签名不一致,部署失败。 +6. 在部署patch类型的补丁包时,如果是debug版本,先判断是否有在使用的补丁包,如果在使用的补丁包为hotreload类型,则部署失败。 +7. 在部署hotreload类型的补丁包时,如果是debug版本,先判断是否有在使用的补丁包,如果在使用的补丁包为patch类型,则部署失败;如果是release版本,则部署失败。 + +**处理步骤** + +请检查补丁包是否符合规则。 + +## 18500004 补丁包使能失败 + +**错误信息** + +Switch hqf failed. + +**错误描述** + +当补丁包使能失败时,方法将返回该错误码。 + +**可能原因** + +使能补丁时补丁包状态不正确。 + +**处理步骤** + +请检查补丁包状态。 + +## 18500005 补丁包删除失败 + +**错误信息** + +Delete hqf failed. + +**错误描述** + +当补丁包删除失败时,方法将返回该错误码。 + +**可能原因** + +删除旧补丁时补丁包状态不正确。 + +**处理步骤** + +请检查补丁包状态。 + +## 18500006 加载补丁失败 + +**错误信息** + +Load patch failed. + +**错误描述** + +当加载补丁失败时,方法将返回该错误码。 + +**可能原因** + +方舟引擎加载补丁失败。 + +**处理步骤** + +请检查补丁包是否正确。 + +## 18500007 卸载旧补丁失败 + +**错误信息** + +Unload patch failed. + +**错误描述** + +当方舟引擎卸载旧补丁失败时,方法将返回该错误码。 + +**可能原因** + +方舟引擎加载补丁失败。 + +**处理步骤** + +请检查补丁包是否正确。 + +## 18500008 快速修复内部错误 + +**错误信息** + +Internal error. + +**错误描述** + +当内存申请、多线程处理异常等内部处理错误时,方法将返回该错误码。 + +**可能原因** + +内存申请、多线程处理等内核通用错误。 + +**处理步骤** + +确认系统内存是否足够。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-audio.md b/zh-cn/application-dev/reference/errorcodes/errorcode-audio.md new file mode 100644 index 0000000000000000000000000000000000000000..96e986813706ea59bcb629891e821f561fe2a72a --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-audio.md @@ -0,0 +1,132 @@ +# Audio错误码 + +## 6800101 无效入参 + +**错误信息** + +invalid parameter. + +**错误描述** + +调用接口时,传入的参数无效。 + +**可能原因** + +参数无效,比如值不在边界范围内,没有使用指定的枚举范围等。 + +**处理步骤** + +根据接口文档,传入正确的入参。 + +## 6800102 分配内存失败 + +**错误信息** + +allocate memory failed. + +**错误描述** + +调用接口时,分配内存失败或者出现空指针。 + +**可能原因** + +1. 系统内存压力大,没有足够的内存用来映射。 +2. 对于失效的实例,没有及时销毁释放内存。 + +**处理步骤** + +1. 销毁当前实例。 +2. 重新创建实例,如果重新创建失败,则停止相关操作。 + +## 6800103 状态不支持 + +**错误信息** + +Operation not permit at current state. + +**错误描述** + +当前状态不支持此操作。 + +**可能原因** + +当前状态机不支持操作。比如未启动流就播放数据等。 + +**处理步骤** + +1. 确认当前状态是否支持当前操作。 +2. 把实例切换到正确的状态进行正确的操作。 + +## 6800104 参数选项不支持 + +**错误信息** + +unsupported operation. + +**错误描述** + +参数选项不支持。 + +**可能原因** + +入参选值不在系统支持规格范围内。 + +**处理步骤** + +1. 确认当前api支持的枚举或其他入参。 +2. 改用支持的参数选项。 + +## 6800105 处理超时 + +**错误信息** + +time out. + +**错误描述** + +等待处理超时。 + +**可能原因** + +等待外部处理超时,比如等待应用填写音频数据超时。 + +**处理步骤** + +控制数据填写的时间,例如增加延迟处理。 + +## 6800201 音频流数量达到极限 + +**错误信息** + +stream number limited. + +**错误描述** + +达到系统可支持的最大数量。 + +**可能原因** + +无效的音频流没有及时释放。 + +**处理步骤** + +释放其他不再使用的音频流资源。 + +## 6800301 系统处理异常 + +**错误信息** + +system error. + +**错误描述** + +系统处理异常。 + +**可能原因** + +系统处理异常,比如系统服务重启、跨进程调用异常等。 + +**处理步骤** + +系统内部通用错误,出现的情况不明确,建议尝试重新创建业务。 + 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-geoLocationManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..59e55fbac0939b26f787555c7d46be6bb9158b03 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md @@ -0,0 +1,157 @@ +# 位置服务子系统错误码 + +## 3301000 位置服务不可用 + +**错误信息** + +Location service is unavailable. + +**错误描述** + +位置服务不可用,位置服务相关的接口无法调用. + +**可能原因** + +1.位置服务启动异常,导致应用和位置服务子系统通信失败,导致位置服务不可用. + +2.GNSS芯片初始化失败导致GNSS定位功能失效. + +3.网络定位服务异常,导致网络定位功能失效. + +**处理步骤** + +请停止调用该接口. + +## 3301100 位置功能的开关未开启导致功能失败 + +**错误信息** + +The location switch is off. + +**错误描述** + +位置功能的开关未开启导致功能失败. + +**可能原因** + +位置功能的开关未开启,导致持续定位,单次定位等基本功能不可用. + +**处理步骤** + +请提示用户开启位置功能的开关. + +## 3301200 定位失败,未获取到定位结果 + +**错误信息** + +Failed to obtain the geographical location. + +**错误描述** + +定位失败,未获取到定位结果. + +**可能原因** + +1.GNSS信号弱,导致定位超时. + +2.网络定位异常导致定位超时. + +**处理步骤** + +请重新发起定位请求. + +## 3301300 逆地理编码查询失败 + +**错误信息** + +Reverse geocoding query failed. + +**错误描述** + +逆地理编码查询失败. + +**可能原因** + +数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧. + +**处理步骤** + +请重试逆地理编码查询. + +## 3301400 地理编码查询失败 + +**错误信息** + +Geocoding query failed. + +**错误描述** + +地理编码查询失败. + +**可能原因** + +数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧. + +**处理步骤** + +请重试地理编码查询. + +## 3301500 区域信息(包含国家码)查询失败 + +**错误信息** + +Failed to query the area information. + +**错误描述** + +区域信息(包含国家码)查询失败. + +**可能原因** + +未查询到正确的区域信息. + +**处理步骤** + +请停止调用查询区域码的接口. + +## 3301600 地理围栏操作失败 + +**错误信息** + +Failed to operate the geofence. + +**错误描述** + +地理围栏操作失败,包含添加,删除,暂停和恢复等操作. + +**可能原因** + +1.GNSS芯片不支持地理围栏功能. + +2.底层业务逻辑异常导致操作地理围栏失败. + +**处理步骤** + +请停止调用地理围栏操作接口. + +## 3301700 请求无响应 + +**错误信息** + +No response to the request. + +**错误描述** + +某些异步请求需要用户点击按钮确认,或者需要GNSS芯片和网络服务器响应,这些场景下未收到响应导致业务失败. + +**可能原因** + +1.用户未点击按钮确认. + +2.GNSS芯片未响应. + +3.网络服务器未响应. + +**处理步骤** + +请停止调用相关接口. \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md index 07ef23b7328f886e9eccb2352ee8609c30962e1f..5166f78088c57fdce16ca43bc2d54668bdea696e 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md @@ -253,7 +253,8 @@ Invalid max storage quota value. 传入的最大存储配额值字符串不符合以下规则: -- 最大存储配额值以数字开头,以大小单位(单位字符支持[b|k|kb|m|mb|g|gb|t|tb],不区分大小写)结尾,且不包含其他字符。 +- 配额值字符串只由数字字符和大小单位字符(单位字符支持[b|k|kb|m|mb|g|gb|t|tb],不区分大小写)构成。 +- 配额值字符串必须以数字开头,后面可以选择不传单位字符(默认使用byte作为单位),或者以单位字符结尾。 **处理步骤** diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md b/zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md new file mode 100644 index 0000000000000000000000000000000000000000..d6763eebdda0b57f0090abfd2da966f7d31dc40e --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md @@ -0,0 +1,44 @@ +# NFC错误码 + +## 3100101 + +**错误信息** + +NFC opening or closing state is abnormal in service. + +**错误描述** + +NFC服务内部执行NFC打开或关闭异常。 + +**可能原因** + +和NFC服务建立通信异常。 + +**处理步骤** + +重新执行打开或关闭NFC。 + +## 3100201 + +**错误信息** + +Tag running state is abnormal in service. + +**错误描述** + +NFC服务执行Tag业务逻辑遇到错误。 + +**可能原因** +1. Tag参数值和实际调用函数要求不匹配。 +2. Tag操作时,NFC状态是关闭的。 +3. Tag操作前,已经处在断开状态。 +4. Tag芯片返回错误状态或响应超时。 +5. 和NFC服务没有建立绑定关系,无法调用接口。 + +**处理步骤** +1. 检查NFC参数是否和所调用接口匹配。 +2. 打开设备NFC。 +3. 先调用连接,再执行读写操作。 +4. 重新触碰读取卡片。 +5. 退出应用后,重新读取卡片。 + diff --git a/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md b/zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md similarity index 83% rename from zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md index 559f2ba4a7e76e966212fc53bb96e88270e1c09a..d7038b823654fdaa4601f053f7f808a006113e46 100755 --- a/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md @@ -16,7 +16,8 @@ The input source file is invalid. **处理步骤** -检查源文件是否存在。 +1. 检查源文件是否存在。 +2. 检查待压缩的文件路径是否存在,并且路径是否在正确的沙箱路径下。 ## 900002 传入的目标文件错误 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md b/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md index 57c3e074bd6b50541a4c676d273bff1cb15aa4ff..6810c9398d6dd287ef1351e934b41a7198acb492 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md @@ -5,9 +5,9 @@ - 语法 - [HML语法参考](js-service-widget-syntax-hml.md) - [CSS语法参考](js-service-widget-syntax-css.md) - - [配置数据和事件](js-service-widget-configuration.md) - [多语言支持](js-service-widget-multiple-languages.md) - - [低版本兼容](js-service-widget-version-compatibility.md) + - [版本兼容适配](js-service-widget-version-compatibility.md) + - [设置主题样式](js-service-widget-theme.md) - 组件 - 通用 - [通用属性](js-service-widget-common-attributes.md) @@ -19,6 +19,7 @@ - [无障碍](js-service-widget-common-accessibility.md) - [原子布局](js-service-widget-common-atomic-layout.md) - 容器组件 + - [badge](js-service-widget-container-badge.md) - [div](js-service-widget-container-div.md) - [list](js-service-widget-container-list.md) - [list-item](js-service-widget-container-list-item.md) @@ -35,8 +36,5 @@ - [progress](js-service-widget-basic-progress.md) - [span](js-service-widget-basic-span.md) - [text](js-service-widget-basic-text.md) -- 自定义组件 - - [自定义组件基本用法](js-service-widget-custom-basic-usage.md) - - [自定义事件](js-service-widget-custom-events.md) - - [Props](js-service-widget-custom-props.md) +- [自定义组件使用说明](js-service-widget-custom-basic-usage.md) - [数据类型说明](js-service-widget-appendix-types.md) diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/figures/badgeSample.png b/zh-cn/application-dev/reference/js-service-widget-ui/figures/badgeSample.png new file mode 100644 index 0000000000000000000000000000000000000000..d28449df64e90d5f4bd9ac1243090fc13f9c2903 Binary files /dev/null and b/zh-cn/application-dev/reference/js-service-widget-ui/figures/badgeSample.png differ diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md index 1caa03daece18dc5ad40254438e1618572e58717..2e044292a6c5cf5c7c1b2f137a82dc80d97f24e5 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md @@ -1,7 +1,7 @@ # 媒体查询 -媒体查询(Media Query)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: +媒体查询(MediaQuery)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: 1. 针对设备和应用的属性信息,可以设计出相匹配的布局样式。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md deleted file mode 100644 index f139c9efc848cff2a6cabf5da8acd5a56699b8c3..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md +++ /dev/null @@ -1,36 +0,0 @@ -# 配置数据和事件 - - -卡片使用json文件配置卡片使用的变量和事件,变量的声明在data字段下,事件的声明在actions字段下。 - - -示例: - - - -```json -{ - "data": { - "temperature": "35°C", - "city": "hangzhou" - }, - "actions": { - "routerEventName": { - "action": "router", - "abilityName": "com.example.myapplication.FormAbility", - "params": { - "message": "weather", - "temperature": "{{temperature}}" - } - }, - "messageEventName": { - "action": "message", - "params": { - "message": "weather update" - } - } - } -} -``` - -可参考示例:[input](./js-service-widget-basic-input.md)与[list](js-service-widget-container-list.md)等组件中的用法。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-badge.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-badge.md new file mode 100644 index 0000000000000000000000000000000000000000..67d6e7a49f20c1e0d827f83a71b92b93fb8c9395 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-badge.md @@ -0,0 +1,101 @@ +# badge + + +应用中如果有需用户关注的新事件提醒,可以采用新事件标记来标识。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +仅支持单个子组件。 + + +## 属性 + +除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| placement | string | rightTop | 否 | 事件提醒的数字标记或者圆点标记的位置,可选值为:
- right:位于组件右边框。
- rightTop:位于组件边框右上角。
- left:位于组件左边框。 | +| count | number | 0 | 否 | 设置提醒的消息数,默认为0。当设置相应的提醒消息数大于0时,消息提醒会变成数字标记类型,未设置消息数或者消息数不大于0时,消息提醒将采用圆点标记。
说明:当数字设置为大于maxcount时,将使用maxcount显示。count属性最大支持整数值为2147483647。 | +| visible | boolean | false | 否 | 是否显示消息提醒,当收到新信息提醒时可以设置该属性为true,显示相应的消息提醒,如果需要使用数字标记类型,同时需要设置相应的count属性。 | +| maxcount | number | 99 | 否 | 最大消息数限制,当收到新信息提醒大于该限制时,标识数字会进行省略,仅显示maxcount+。
说明:maxcount属性最大支持整数值为2147483647。 | +| config | BadgeConfig | - | 否 | 设置新事件标记相关配置属性。 | +| label | string | - | 否 | 设置新事件提醒的文本值。
说明:使用该属性时,count和maxcount属性不生效。 | + +### BadgeConfig + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| badgeColor | <color> | #fa2a2d | 否 | 新事件标记背景色。 | +| textColor | <color> | #ffffff | 否 | 数字标记的数字文本颜色。 | +| textSize | <length> | 10px | 否 | 数字标记的数字文本大小。 | +| badgeSize | <length> | 6px | 否 | 圆点标记的大小。 | + + +## 样式 + +支持[通用样式](js-service-widget-common-styles.md)。 + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + + ```html + +
+ + example + + + example + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + width: 100%; + align-items: center; + } + + .badge { + width: 80px; + height: 60px; + margin-top: 30px; + } + + .text1 { + background-color: #f9a01e; + font-size: 19fp; + } + + .text2 { + background-color: #46b1e3; + font-size: 19fp; + } + ``` + + ```json + { + "data":{ + "badgeconfig":{ + "badgeColor":"#0a59f7", + "textColor":"#ffffff", + "textSize":"9px", + "badgeSize": "14px" + } + } + } + ``` + +![badgeSample](figures/badgeSample.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md index b32292dc65c4f008ad088f267dcb9d2b2ecb7f09..8b561ee6ed1b0d454514329d27640ee8a303abf7 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md @@ -1,11 +1,12 @@ -# 自定义组件基本用法 +# 自定义组件使用说明 > **说明:** +> > 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - 自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法: +自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法: ```html @@ -18,10 +19,176 @@ - 事件绑定:自定义组件中绑定子组件事件使用(on|\@)child1语法,子组件中通过{action:"proxy", method: "eventName"}触发事件并进行传值,父组件执行bindParentVmMethod方法并接收子组件传递的参数。 - ## 自定义组件配置文件标签 | 属性 | 类型 | 描述 | | -------- | -------- | -------- | | data | Object | 页面的数据模型,类型是对象。属性名不能以$或_开头,不要使用保留字for, if, show, tid。 | | props | Array/Object | props用于组件之间的通信,可以通过<tag xxxx='value'>方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for, if, show, tid。目前props的数据类型不支持Function。 | + + +## 添加自定义事件 + +自定义组件内支持自定义事件,该事件的标识需要action类型指定为proxy,事件名则通过method指定。使用该自定义组件的卡片页面可以通过该事件名注册相应的事件回调,当自定义组件内该自定义事件触发时,会触发卡片页面上注册的回调事件。 + +> **说明:** +> +> 事件名不支持大写字母。 + +**自定义子组件示例:** + +```html + +
+
+ +
+
+``` + +```css +/* comp.css */ +.container { + flex-direction:column; + background-color: green; + width: 100%; + height: 100%; +} + +.row-3 { + width: 100%; + height: 50px; + background-color: orange; + font-size:15px; +} +``` + +```json +{ + "data": { + }, + "actions": { + "buttonClicked": { + "action": "proxy", + "method":"event_1" + } + } +} +``` +**父组件示例:** + +```html + + + +
+ + +
+``` + +```css +/* xxx.css */ +.container { + background-color: red; + height: 500px; + width: 500px; +} +``` + +```json +{ + "data": { + }, + "actions": { + "click": { + "action": "message", + "params": { + "message": "click event" + } + }, + "buttonClick": { + "action": "message", + "params": { + "message": "click event 2" + } + } + } +} +``` + + +## props + +自定义组件可以通过props声明自定义属性,父组件通过设置属性向子组件传递参数。 + +### 添加默认值 + +子组件可以通过固定值default设置默认值,当父组件没有设置该属性时,将使用其默认值。此情况下props属性必须为对象形式,不能用数组形式,示例如下: + +```html + +
+
+
+ xiaoziti +
+
+ {{text}} +
+
+ {{textdata[0]}} +
+
+
+ +
+
+ +
+
+``` + +```json +{ + "data": { + "progress": { + "default": "80" + } + }, + "props": { + "textdata": { + "default": ["a","b"] + }, + "progress": { + "default": 60 + }, + "text": { + "default": "ha" + } + }, + "actions": { + "buttonClicked": { + "action": "proxy", + "method": "event_1" + } + } +} +``` + +引用子组件comp的父组件示例如下: + +```html + + + +
+ +
+``` + +### 数据单向性 + +父子组件之间数据的传递是单向的,只能从父组件传递给子组件,子组件不能直接修改父组件传递下来的值,可以将props传入的值用data接收后作为默认值,再对data的值进行修改。 + +更多说明请参考[props](../arkui-js/js-components-custom-props.md)文档。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md deleted file mode 100644 index 05287a5e1f56337015048392cdcc11e1cfa617d7..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md +++ /dev/null @@ -1,104 +0,0 @@ -# 自定义事件 - - -自定义组件内支持自定义事件,该事件的标识需要action类型指定为proxy,事件名则通过method指定。使用该自定义组件的卡片页面可以通过该事件名注册相应的事件回调,当自定义组件内该自定义事件触发时,会触发卡片页面上注册的回调事件。 - - -> **说明:** -> -> 事件名不支持大写字母。 - - -## 子组件comp示例: - - -```html - -
-
- -
-
-``` - - - -```css -/* comp.css */ -.container { - flex-direction:column; - background-color: green; - width: 100%; - height: 100%; -} - -.row-3 { - width: 100%; - height: 50px; - background-color: orange; - font-size:15px; -} -``` - - - -```json -{ - "data": { - }, - "actions": { - "buttonClicked": { - "action": "proxy", - "method":"event_1" - } - } -} -``` - - -## 卡片页面示例 - - -```html - - - -
- - -
-``` - - - -```css -/* xxx.css */ -.container { - background-color: red; - height: 500px; - width: 500px; -} -``` - - - -```j'so -{ - "data": { - }, - "actions": { - "click": { - "action": "message", - "params": { - "message": "click event" - } - }, - "buttonClick": { - "action": "message", - "params": { - "message": "click event 2" - } - } - } -} -``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md deleted file mode 100644 index 992ed8445e6caf816393a346c18d43339b61640c..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md +++ /dev/null @@ -1,81 +0,0 @@ -# Props - - -自定义组件可以通过props声明属性,父组件通过设置属性向子组件传递参数。通过父组件向下传递参数的示例如下: - -## 添加默认值 - -子组件可以通过固定值default设置默认值,当父组件没有设置该属性时,将使用其默认值。此情况下props属性必须为对象形式,不能用数组形式,示例如下: - - - -```html - -
-
-
- xiaoziti -
-
- {{text}} -
-
- {{textdata[0]}} -
-
-
- -
-
- -
-
-``` - - - -```json -// comp.json -{ - "data": { - "progress": { - "default": "80" - } - }, - "props": { - "textdata": { - "default": ["a","b"] - }, - "progress": { - "default": 60 - }, - "text": { - "default": "ha" - } - }, - "actions": { - "buttonClicked": { - "action": "proxy", - "method": "event_1" - } - } -} -``` - - - -```html - - - -
- -
-``` - - -## 数据单向性 - -父子组件之间数据的传递是单向的,只能从父组件传递给子组件,子组件不能直接修改父组件传递下来的值,可以将props传入的值用data接收后作为默认值,再对data的值进行修改。 - -更多说明请参考[props](../arkui-js/js-components-custom-props.md)。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md index 9025d3ad8df2f64ca271fd3dd690c14ca575860d..d6102070dff485d382545b8bc5cfcb9fa8895fc9 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md @@ -25,7 +25,7 @@ JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下: - .css结尾的CSS样式文件,这个文件用于描述页面样式。 -- .json结尾的JSON文件,这个文件用于配置卡片中使用的变量action事件。 +- .json结尾的JSON配置文件,这个文件用于配置卡片中使用的变量action事件。 各个文件夹的作用: @@ -41,11 +41,11 @@ JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下: - 引用代码文件,需使用相对路径,比如:../common/style.css。 -- 引用资源文件,推荐使用绝对路径。比如:/common/xxx.png。 +- 引用资源文件,推荐使用绝对路径。比如:/common/test.png。 - 公共代码文件和资源文件推荐放在common下,通过规则1和规则2进行访问。 -- CSS样式文件中通过url()函数创建<url>数据类型,如:url(/common/xxx.png)。 +- CSS样式文件中通过url()函数创建<url>数据类型,如:url(/common/test.png)。 > **说明:** > 当代码文件A需要引用代码文件B时: diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md index 6cd29b1341e3259773fd6212ac188137eec9ea18..e968c2208bd2a9c6b796be6f18223fd48137e50d 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md @@ -24,15 +24,16 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 ```html
- {{content}} - {{key1}} {{key2}} - key1 {{key1}} - {{flag1 && flag2}} - {{flag1 || flag2}} - {{!flag1}} + {{content}} + {{key1}} {{key2}} + key1 {{key1}} + {{flag1 && flag2}} + {{flag1 || flag2}} + {{!flag1}}
``` +卡片hml文件中的变量需要在json文件的data字段下进行声明: ```json { @@ -46,18 +47,17 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 } ``` - > **说明:** > - key值支持对象操作符和数组操作符,如{{key.value}}、{{key[0]}}。 > -> - 从 API Version 6 开始支持字符串拼接、逻辑运算和三元表达式。 +> - 支持字符串拼接、逻辑运算和三元表达式。 > - 字符串拼接: > - 支持变量跟变量:{{key1}}{{key2}}等 > - 支持常量跟变量: "my name is {{name}}, i am from {{city}}." "key1 {{key1}}" > - 逻辑运算: -> - 与:{{flag1 && flag2}}(仅支持两个boolean变量间的与) -> - 或:{{flag1 || flag2}} (仅支持两个boolean变量间的或) -> - 非:{{!flag1}} (仅支持boolean变量的非运行) +> - 与:{{flag1 && flag2}}(仅支持两个boolean变量间的与逻辑运算) +> - 或:{{flag1 || flag2}} (仅支持两个boolean变量间的或逻辑运算) +> - 非:{{!flag1}} (仅支持boolean变量的非逻辑运算) > - 三元表达式 > - {{flag? key1:key2}}(flag为boolean变量,key1和key2可以是变量,也可以是常量) > - 注意事项 @@ -66,7 +66,7 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 ## 事件绑定 -卡片仅支持click通用事件,事件的定义只能是直接命令式,事件定义必须包含action字段,用以说明事件类型。卡片支持两种事件类型:跳转事件(router)和消息事件(message)。跳转事件可以跳转到卡片提供方的OpenHarmony应用,消息事件可以将开发者自定义信息传递给卡片提供方。事件参数支持变量,变量以"{{}}"修饰。跳转事件中若定义了params字段,则在被拉起应用的onStart的intent中,可用"params"作为key将跳转事件定义的params字段的值取到。 +卡片的事件需要在json文件的actions字段下进行声明。卡片仅支持click通用事件,事件的定义只能是直接命令式,事件定义必须包含action字段,用以说明事件类型。卡片支持两种事件类型:跳转事件(router)和消息事件(message)。跳转事件可以跳转到卡片提供方的OpenHarmony应用,消息事件可以将开发者自定义信息传递给卡片提供方。事件参数支持变量,变量以"{{}}"修饰。跳转事件中若定义了params字段,则在被拉起应用的onStart的intent中,可用"params"作为key将跳转事件定义的params字段的值取到。 - 跳转事件格式 @@ -99,20 +99,7 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 | 选择器 | 类型 | 默认值 | 样例描述 | | ------ | ------ | -------- | ---------------------------------------- | | action | string | "router" | 事件类型。
- "router":用于应用跳转。
- "message":自定义点击事件。 | - | want | Object | - | 跳转目标应用的信息,参考want格式表。 | - - **表1** want格式 - - | 选择器 | 类型 | 默认值 | 样例描述 | - | ----------- | -------------------- | ------------ | ---------------------------------------- | - | bundleName | string | - | 表示包描述。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | - | abilityName | string | - | 表示待启动的Ability名称。 | - | action | string | - | 表示action选项描述。 | - | uri | string | - | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | - | type | string | "text/plain" | 表示MIME type类型描述,比如:"text/plain" 、 "image/*"等。 | - | flags | number | - | 表示处理Want的方式。默认传数字,具体参考[flags说明](../apis/js-apis-featureAbility.md#flags说明)。 | - | entities | Array\ | - | 类别,用于指定Intent的操作类别。 | - | parameters | {[key: string]: any} | - | 表示WantParams描述。 | + | want | [Want](../apis/js-apis-application-Want.md) | - | 跳转目标应用的信息,参考want格式表。 | ```json diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-theme.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-theme.md new file mode 100644 index 0000000000000000000000000000000000000000..2373f60ab3dda52851ff3a6336ec8c5d93b4761d --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-theme.md @@ -0,0 +1,19 @@ +# 设置主题样式 + + +卡片目前支持修改的主题样式如下: + +| 名称 | 描述 | +| ------------------ | ----------------------------- | +| app_background | 设置卡片背景颜色。 | + + +修改主题样式需要在widget文件夹下手动创建与pages同级的resources文件夹,在widget/resources/styles/default.json文件中配置主题样式。例如,修改卡片默认的背景色为浅灰色: + +```json +{ + "style": { + "app_background": "#dcdcdc" + } +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md index 07b5eca24b2027f8b1045f9c3c74a4ea71bbe200..62f19723b84a962cbdc163e0e74f9d23fbe30e78 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md @@ -1,62 +1,39 @@ -# 低版本兼容 +# 版本兼容适配 卡片特性不断增加,使用了新特性的卡片,在不支持这些新特性的老系统上可能显示异常。可以在卡片工程中指定最小SDK版本,防止使用新特性的卡片推送安装在老的系统上。也可以参考本章节的内容,在卡片开发阶段做前向兼容适配。 - -> **说明:** -> -> 低版本兼容能力从 API Version 6 开始支持。 - - 开发者可以通过JSON配置文件配置前向兼容能力。该文件提供了apiVersion属性用于兼容版本,该字段和卡片配置文件的数据字段data、事件字段actions同级。在apiVersion标签下定义的内容会基于当前运行版本信息,覆盖原始的data标签内容。 示例如下: - -假设JS服务卡片框架从API Version 6开始,支持引用系统内置资源颜色,从API Version 7开始支持slider组件(仅用于举例,不代表实际情况),则可以按照如下的方式,做前向兼容。 - - +假设JS服务卡片框架从API Version 9开始,支持设置webp格式的图源(仅用于举例,不代表实际情况),则可以按照如下的方式,做前向兼容。 ```html -
- hello world - +
+
``` - -xxx.json配置文件: - - +JSON配置文件: ```json { "data": { - "myBackgroundColor": "#87ceeb", - "canUseSlider": "false" + "imageSrc": "defaultSrc.png" }, "apiVersion": { - "6": { - "myBackgroundColor": "@sys.color.fa_background" - }, - "7": { - "canUseSlider": "true" + "9": { + "imageSrc": "newSrc.webp" } } } ``` - JS服务卡片开发框架会根据应用中的配置及当前系统运行版本,选取最合适的数据。 +假设系统运行版本在8及以下,则实际解析的imageSrc值为defaultSrc.png; -假设系统运行版本在5及以下,则实际解析的myBackgroundColor值为\#87ceeb,canUseSlider值为false; - - -假设系统运行版本为6,则实际解析的myBackgroundColor值为\@sys.color.fa_background,canUseSlider值为false; - - -假设系统运行版本为7及以上,则实际解析的际解析的myBackgroundColor值为\@sys.color.fa_background,canUseSlider值为true。 +假设系统运行版本为9,则实际解析的imageSrc值为newSrc.webp。 diff --git a/zh-cn/application-dev/reference/native-apis/_drawing.md b/zh-cn/application-dev/reference/native-apis/_drawing.md index 9c9772d11d13c346cd19d1d5473f51b3e49d571c..64ce6a9a7ec1cf306fbe9647082038f249ea21b5 100644 --- a/zh-cn/application-dev/reference/native-apis/_drawing.md +++ b/zh-cn/application-dev/reference/native-apis/_drawing.md @@ -2154,7 +2154,7 @@ void OH_Drawing_SetTextStyleFontFamilies (OH_Drawing_TextStyle * , int , const c | -------- | -------- | | OH_Drawing_TextStyle | 指向OH_Drawing_TextStyle对象的指针 | | int | 字体名称数量 | -| char | 指向字体类型的指针 | +| fontFamilies | 指向字体类型的指针数组 | **自从:** diff --git a/zh-cn/application-dev/reference/native-apis/_mind_spore.md b/zh-cn/application-dev/reference/native-apis/_mind_spore.md index 061eece1bfb48ef62a390c389e1031b41aa04093..9812ce51e5efdaff2b432b82bab3386f99f698b8 100644 --- a/zh-cn/application-dev/reference/native-apis/_mind_spore.md +++ b/zh-cn/application-dev/reference/native-apis/_mind_spore.md @@ -84,7 +84,7 @@ | [OH_AI_ContextDestroy](#oh_ai_contextdestroy) (OH_AI_ContextHandle \*context) | 释放上下文对象。 | | [OH_AI_ContextSetThreadNum](#oh_ai_contextsetthreadnum) (OH_AI_ContextHandle context, int32_t thread_num) | 设置运行时的线程数量。 | | [OH_AI_ContextGetThreadNum](#oh_ai_contextgetthreadnum) (const OH_AI_ContextHandle context) | 获取线程数量。 | -| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 | +| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 | | [OH_AI_ContextGetThreadAffinityMode](#oh_ai_contextgetthreadaffinitymode) (const OH_AI_ContextHandle context) | 获取运行时线程绑定CPU核心的策略。 | | [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) (OH_AI_ContextHandle context, const int32_t \*core_list,
size_t core_num) | 设置运行时线程绑定CPU核心的列表。 | | [OH_AI_ContextGetThreadAffinityCoreList](#oh_ai_contextgetthreadaffinitycorelist) (const OH_AI_ContextHandle context, size_t \*core_num) | 获取CPU绑核列表。 | @@ -649,14 +649,14 @@ OH_AI_API void OH_AI_ContextSetThreadAffinityMode (OH_AI_ContextHandle context, **描述:** -设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 +设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 **参数:** | 名称 | 描述 | | -------- | -------- | | context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 | -| mode | 绑核策略。一共有三种策略,0为不绑核, 1为大核优先, 2为小核优先。 | +| mode | 绑核策略。一共有三种策略,0为不绑核, 1为大核优先, 2为中核优先。 | ### OH_AI_ContextSetThreadNum() diff --git a/zh-cn/application-dev/reference/native-apis/context_8h.md b/zh-cn/application-dev/reference/native-apis/context_8h.md index 3e8e1c05f91e5105290f48aa695ee42a60584f61..65a629a526bf12d6d37c7591cbadc2cf114ab8ce 100644 --- a/zh-cn/application-dev/reference/native-apis/context_8h.md +++ b/zh-cn/application-dev/reference/native-apis/context_8h.md @@ -33,7 +33,7 @@ | [OH_AI_ContextDestroy](_mind_spore.md#oh_ai_contextdestroy) (OH_AI_ContextHandle \*context) | 释放上下文对象。 | | [OH_AI_ContextSetThreadNum](_mind_spore.md#oh_ai_contextsetthreadnum) (OH_AI_ContextHandle context, int32_t thread_num) | 设置运行时的线程数量。 | | [OH_AI_ContextGetThreadNum](_mind_spore.md#oh_ai_contextgetthreadnum) (const OH_AI_ContextHandle context) | 获取线程数量。 | -| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 | +| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 | | [OH_AI_ContextGetThreadAffinityMode](_mind_spore.md#oh_ai_contextgetthreadaffinitymode) (const OH_AI_ContextHandle context) | 获取运行时线程绑定CPU核心的策略。 | | [OH_AI_ContextSetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextsetthreadaffinitycorelist) (OH_AI_ContextHandle context, const int32_t \*core_list, size_t core_num) | 设置运行时线程绑定CPU核心的列表。 | | [OH_AI_ContextGetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextgetthreadaffinitycorelist) (const OH_AI_ContextHandle context, size_t \*core_num) | 获取CPU绑核列表。 | diff --git a/zh-cn/application-dev/security/Readme-CN.md b/zh-cn/application-dev/security/Readme-CN.md index 5369b1392693a9a7ea842d1f9f96bd6bc2243788..af608f4bf4e0ca46bad71e67b842062b5027842b 100644 --- a/zh-cn/application-dev/security/Readme-CN.md +++ b/zh-cn/application-dev/security/Readme-CN.md @@ -17,3 +17,4 @@ - Hap包签名工具 - [Hap包签名工具概述](hapsigntool-overview.md) - [Hap包签名工具指导](hapsigntool-guidelines.md) + - [HarmonyAppProvision配置文件](app-provision-structure.md) diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 051aa7c462ad6a5beb732f4d14d4e1f64b673f7f..342754163710cdcd1481f51b796fffd56400bce0 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -113,7 +113,7 @@ 如上述示例所示,权限"ohos.permission.PERMISSION2"的权限等级为system_basic,高于此时应用的APL等级,开发者的最佳做法是使用ACL方式。 -在配置文件声明的基础上,应用还需要在Profile文件中声明不满足申请条件部分的权限。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](../quick-start/app-provision-structure.md)。 +在配置文件声明的基础上,应用还需要在Profile文件中声明不满足申请条件部分的权限。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](app-provision-structure.md)。 该场景中,开发者应该在字段"acls"中做声明如下: @@ -167,6 +167,30 @@ > **说明:** > 动态授权申请接口的使用详见[API参考](../reference/apis/js-apis-ability-context.md)。 +## user_grant权限预授权 +当前正常情况下,user_grant类型的权限默认不授权,需要时应通过拉起弹框由用户确认是否授予。对于一些预置应用,比如截屏应用,不希望出现弹框,则可以通过预授权的方式完成user_grant类型权限的授权。[预置配置文件](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json)在设备上的路径为system/etc/app/install_list_permission.json,设备开机启动时会读取该配置文件,在应用安装会对在文件中配置的user_grant类型权限授权。当前仅支持预置应用配置该文件。 +预授权配置文件字段内容包括bundleName、app_signature、permissions。 +1. 这里的权限仅对user_grant类型的权限生效[查看权限等级和类型](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md)。 +2. userCancellable配置为true,表示支持用户取消授权,为false则表示不支持用户取消授权。 + +```json +[ + { + "bundleName": "com.ohos.myapplication", // 包名 + "app_signature":[], // 指纹信息 + "permissions":[ + { + "name":"xxxx", // 权限名,不可缺省 + "userCancellable":false // 用户不可取消授权,不可缺省 + }, + { + "name":"yyy", // 权限名,不可缺省 + "userCancellable":true // 用户可取消授权,不可缺省 + } + ] + } +] +``` ## 相关实例 针对访问控制,有以下相关实例可供参考: diff --git a/zh-cn/application-dev/security/accesstoken-overview.md b/zh-cn/application-dev/security/accesstoken-overview.md index 9a37da6075ada7be976f6221f0b5c7e67d72ce39..5aae9b27ec59c39aac848a0c3653a27cc393b5fe 100644 --- a/zh-cn/application-dev/security/accesstoken-overview.md +++ b/zh-cn/application-dev/security/accesstoken-overview.md @@ -90,7 +90,7 @@ ATM (AccessTokenManager) 是OpenHarmony上基于AccessToken构建的统一的应 示例如下: -该示例仅涉及修改"apl"字段,其余信息请根据实际情况。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](../quick-start/app-provision-structure.md)。 +该示例仅涉及修改"apl"字段,其余信息请根据实际情况。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](app-provision-structure.md)。 ```json { @@ -218,4 +218,4 @@ ACL方式的工作流程可以参考[ACL方式使用说明](#acl方式使用说 } ``` -Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](../quick-start/app-provision-structure.md)。 \ No newline at end of file +Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](app-provision-structure.md)。 diff --git a/zh-cn/application-dev/quick-start/app-provision-structure.md b/zh-cn/application-dev/security/app-provision-structure.md similarity index 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/permission-list.md b/zh-cn/application-dev/security/permission-list.md index b65ad50d5be3b941402bcd31dbe4aad18f25c873..53e9dd5e8656813eebb9c420e92afb6fc5e1e8d1 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -153,4 +153,12 @@ | ohos.permission.
RECEIVER_STARTUP_COMPLETED | system_basic | system_grant | FALSE | 允许应用订阅开机广播。 | | ohos.permission.
MANAGE_CAMERA_CONFIG | system_basic | system_grant | FALSE | 允许应用进行全局相机开关等操作。 | | ohos.permission.READ_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | 允许应用读取所有的日历信息。 | -| ohos.permission.WRITE_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | 允许应用添加、移除或更改所有的日历活动。 | \ No newline at end of file +| ohos.permission.WRITE_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | 允许应用添加、移除或更改所有的日历活动。 | +| ohos.permission.ENFORCE_USER_IAM | system_core | system_grant | TRUE | 允许SA无token删除IAM子系统用户信息。 | +| ohos.permission.ACCESS_AUTH_RESPOOL | system_core | system_grant | TRUE | 允许SA注册执行器。 | +| ohos.permission.MOUNT_UNMOUNT_MANAGER | system_basic | system_grant | FALSE | 允许应用对外卡进行挂载卸载操作。 | +| ohos.permission.MOUNT_FORMAT_MANAGER | system_basic | system_grant | FALSE | 允许应用对外卡进行格式化操作。 | +| ohos.permission.STORAGE_MANAGER | system_basic | system_grant | TRUE | 允许应用调用storage manager服务中对空间统计以及卷信息的查询接口。 | +| ohos.permission.BACKUP | system_basic | system_grant | TRUE | 允许应用拥有备份恢复能力。 | +| ohos.permission.FILE_ACCESS_MANAGER | system_basic | system_grant | TRUE | 允许文件管理类应用通过FAF框架访问公共数据文件。 | +| ohos.permission.MANAGE_AUDIO_CONFIG | system_basic | system_grant | TRUE | 允许应用进行全局麦克风静音等操作。 | \ No newline at end of file diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif index 2283e46371317539004c0007886500c1a81dd83a..f59b87e0afc79eafbddef8de2a264cf2f41b97c7 100755 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png index 5000709da6dfadee24e10fdbd679b3a28e46578b..d39e5026790f8d85866b0e293f6b53ad455ff1c4 100755 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif index f470f5261becb6c2d7b30f691a0794db2b1feb93..75abb6f81315b55e677acd8c4d943b2f22d76fff 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif index d669cf40b97891ba3853be28574dceae172fe138..0be34d5b9598c7e03132b08e030fd71d977886b5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif differ diff --git a/zh-cn/application-dev/ui/js-framework-syntax-css.md b/zh-cn/application-dev/ui/js-framework-syntax-css.md index a3961ebc73492776031d337f8a6c0be62925a9bb..16d19b5d25d8dd79a44f4398134426c32a6e2fcf 100644 --- a/zh-cn/application-dev/ui/js-framework-syntax-css.md +++ b/zh-cn/application-dev/ui/js-framework-syntax-css.md @@ -100,7 +100,7 @@ div { color: #007dff; } /* 对class="container"的组件下的直接后代text设置样式 */ -.container > text { +.container > text { color: #fa2a2d; } ``` diff --git a/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md b/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md index ed82f95ad103deb99230ef795154d7f268b2bac0..01007ff725f78cf9e78507cf6d1bf2b4b2ddc7c3 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md +++ b/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md @@ -26,8 +26,10 @@ justify-content: center; align-items: center; flex-direction: column; + width: 100%; + height: 100%; } -.fade{ +.fade { width: 30%; height: 200px; left: 35%; @@ -35,13 +37,13 @@ position: absolute; animation: 2s change infinite friction; } -.bigger{ +.bigger { width: 20%; height: 100px; background-color: blue; animation: 2s change1 infinite linear-out-slow-in; } -text{ +text { width: 100%; height: 100%; text-align: center; @@ -61,7 +63,7 @@ text{ } } /* 父组件大小变化 */ -@keyframes change1{ +@keyframes change1 { 0% { width: 20%; height: 100px; @@ -70,11 +72,11 @@ text{ width: 80%; height: 200px; } -} +} /* 子组件文字缩放 */ -@keyframes change2{ - 0%{ - transform: scale(0); +@keyframes change2 { + 0% { + transform: scale(0); } 100% { transform: scale(1.5); diff --git a/zh-cn/application-dev/ui/ui-js-animate-component.md b/zh-cn/application-dev/ui/ui-js-animate-component.md index 859fb01701d252c51c60600f2dd283bd62fbd1b5..4588277ce58dd416ba31db834e2edf841cbdac51 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-component.md +++ b/zh-cn/application-dev/ui/ui-js-animate-component.md @@ -83,6 +83,7 @@ export default { justify-content: center; align-items: center; width: 100%; + height: 100%; } .box{ width: 200px; @@ -103,7 +104,7 @@ export default { onInit() { this.options = { duration: 4000, - }; + } this.keyframes = [ { transform: { @@ -127,11 +128,11 @@ export default { width: 300, height: 300 } - ]; + ] }, Show() { - this.animation = this.$element('content').animate(this.keyframes, this.options); - this.animation.play(); + this.animation = this.$element('content').animate(this.keyframes, this.options) + this.animation.play() } } ``` @@ -225,16 +226,16 @@ animation对象支持动画事件和动画方法。可以通过添加开始和 ```html
-
-
-
- - -
-
- - -
+
+
+
+ + +
+
+ + +
``` @@ -244,6 +245,8 @@ animation对象支持动画事件和动画方法。可以通过添加开始和 flex-direction: column; align-items: center; justify-content: center; + width: 100%; + height: 100%; } button{ width: 200px; @@ -272,75 +275,64 @@ button{ ```js // xxx.js -import prompt from '@system.prompt'; export default { - data: { - animation: '', - }, - onInit() { - }, - onShow() { - var options = { - duration: 1500, - easing:'ease-in', - elay:5, - direction:'normal', - iterations:2 - }; - var frames = [ - { - transform: { - translate: '-150px -0px' - }, - opacity: 0.1, - offset: 0.0, - width: 200, - height: 200, - }, - { - transform: { - translate: '150px 0px' - }, - opacity: 1.0, - offset: 1.0, - width: 300, - height: 300, - } - ]; - this.animation = this.$element('content').animate(frames, options); - this.animation.onstart = function(){ - prompt.showToast({ - message: "start" - }); - }; //添加开始事件 - this.animation.onrepeat = function(){ - prompt.showToast({ - message: " repeated" - }); - };//添加重播事件 - this.animation.oncancel = function(){ - prompt.showToast({ - message: "canceled" - }); - };//添加取消事件 - this.animation.onfinish = function(){ - prompt.showToast({ - message: "finish" - }); - };//添加完成事件 - }, - playAnimation() { - this.animation.play();//调用播放开始的方法 - }, - pauseAnimation() { - this.animation.pause();//调用播放暂停的方法 - }, - reverseAnimation() { - this.animation.reverse();//调用播放倒放的方法 - }, - cancelAnimation() { - this.animation.cancel();//调用播放取消的方法 - } + data: { + animation: '', + }, + onShow() { + var options = { + duration: 1500, + easing:'ease-in', + delay:5, + direction:'normal', + iterations:2 + }; + var frames = [ + { + transform: { + translate: '-150px -0px' + }, + opacity: 0.1, + offset: 0.0, + width: 200, + height: 200, + }, + { + transform: { + translate: '150px 0px' + }, + opacity: 1.0, + offset: 1.0, + width: 300, + height: 300, + } + ]; + this.animation = this.$element('content').animate(frames, options); + this.animation.onstart = function() { + console.info('animation start') + } // 添加开始事件 + this.animation.onrepeat = function() { + console.info('animation repeated') + } // 添加重播事件 + this.animation.oncancel = function() { + console.info('animation canceled') + } // 添加取消事件 + this.animation.onfinish = function() { + console.info('animation finish') + } // 添加完成事件 + }, + playAnimation() { + this.animation.play() // 调用播放开始的方法 + }, + pauseAnimation() { + this.animation.pause() // 调用播放暂停的方法 + }, + reverseAnimation() { + this.animation.reverse() // 调用播放倒放的方法 + }, + cancelAnimation() { + this.animation.cancel() // 调用播放取消的方法 + } } ``` diff --git a/zh-cn/application-dev/ui/ui-js-animate-transform.md b/zh-cn/application-dev/ui/ui-js-animate-transform.md index c189f6380ba1191a159fcbfeccc562c73383e015..c07c524558072b7206186c1e4a961b42b466c98f 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-transform.md +++ b/zh-cn/application-dev/ui/ui-js-animate-transform.md @@ -202,22 +202,24 @@ display: flex; align-items: center; justify-content: center; + width: 100%; + height: 100%; } -.rect{ +.rect { width: 100px; height: 100px; animation: rotate 3s infinite; margin-left: 100px; } -.rect1{ +.rect1 { background-color: #f76160; } -.rect2{ +.rect2 { background-color: #60f76f; /* 改变原点位置*/ transform-origin: 10% 10px; } -.rect3{ +.rect3 { background-color: #6081f7; /* 改变原点位置*/ transform-origin: right bottom; @@ -231,7 +233,7 @@ } } /* 3d示例样式 */ -.rotate3d{ +.rotate3d { margin-top: 150px; flex-direction: column; background-color:#F1F3F5; @@ -242,27 +244,27 @@ border-radius: 300px; border: 1px solid #ec0808; } -.content{ +.content { padding-top: 150px; display: flex; align-items: center; justify-content: center; } /* react4 react5 翻转形成眼睛 */ -.rect4{ +.rect4 { width: 100px; height: 100px; animation: rotate3d1 17ms infinite; background: linear-gradient(#e6c4ec, #be15d9) } -.rect5{ +.rect5 { width: 100px; height: 100px; animation: rotate3d1 17ms infinite; margin-left: 100px; background: linear-gradient(#e6c4ec, #be15d9) } -.mouse{ +.mouse { margin-top: 150px; width: 200px; height: 100px; @@ -271,7 +273,7 @@ animation: rotate3d2 17ms infinite; } /* 眼睛的动效 */ -@keyframes rotate3d1{ +@keyframes rotate3d1 { 0% { transform:rotate3d(0,0,0,0deg) } @@ -283,7 +285,7 @@ } } /* 嘴的动效 */ -@keyframes rotate3d2{ +@keyframes rotate3d2 { 0% { transform:rotate3d(0,0,0,0deg) } @@ -435,6 +437,8 @@ matrix是一个入参为六个值的矩阵,6个值分别代表:scaleX, skewY background-color:#F1F3F5; display: flex; justify-content: center; + width: 100%; + height: 100%; } .rect{ width: 100px; diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-animation.md b/zh-cn/application-dev/ui/ui-js-building-ui-animation.md index 03c99a2899ceea6680d97a434e3e0d527a8b7ef5..ca34f39427ebf3f32af73ad860fcc9df61eead6d 100755 --- a/zh-cn/application-dev/ui/ui-js-building-ui-animation.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-animation.md @@ -27,12 +27,14 @@ ```css /* xxx.css */ .container { + width: 100%; flex-direction: column; align-items: center; } .translate { height: 150px; width: 300px; + margin: 50px; font-size: 50px; background-color: #008000; transform: translate(200px); @@ -40,14 +42,16 @@ .rotate { height: 150px; width: 300px; + margin: 50px; font-size: 50px; background-color: #008000; transform-origin: 200px 100px; - transform: rotateX(45deg); + transform: rotate(45deg); } .scale { height: 150px; width: 300px; + margin: 50px; font-size: 50px; background-color: #008000; transform: scaleX(1.5); @@ -81,28 +85,24 @@ animation样式需要在css文件中先定义keyframe,在keyframe中设置动 ```html
- animation-name -
- color -
-
- opacity -
- +
+ color +
+
+ opacity +
+
``` ```css /* xxx.css */ .item-container { - margin-right: 60px; - margin-left: 60px; + margin: 60px; flex-direction: column; } -.header { - margin-bottom: 20px; -} .item { + width: 80%; background-color: #f76160; } .txt { @@ -112,6 +112,7 @@ animation样式需要在css文件中先定义keyframe,在keyframe中设置动 } .button { width: 200px; + margin: 10px; font-size: 30px; background-color: #09ba07; } @@ -141,7 +142,7 @@ animation样式需要在css文件中先定义keyframe,在keyframe中设置动 } ``` -``` +```js // xxx.js export default { data: { @@ -153,7 +154,7 @@ export default { this.opacityParam = ''; this.colorParam = 'color'; this.opacityParam = 'opacity'; - }, + } } ``` diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-routes.md b/zh-cn/application-dev/ui/ui-js-building-ui-routes.md index c3746e228c5869e14179969fbb4801c3425fa79f..0c1f7da4095e6caaf12416a2aaac76aa03a7fbb8 100644 --- a/zh-cn/application-dev/ui/ui-js-building-ui-routes.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-routes.md @@ -6,7 +6,7 @@ 页面路由router根据页面的uri找到目标页面,从而实现跳转。以最基础的两个页面之间的跳转为例,具体实现步骤如下: -1. 在“Project“窗口,打开entry > src > mainjsdefault,右键点击pages文件夹,选择NewJS Page,创建一个详情页。 +1. 在“Project“窗口,打开src > main >js >MainAbility,右键点击pages文件夹,选择NewJS Page,创建一个详情页。 2. 调用router.push()路由到详情页。 @@ -42,6 +42,8 @@ index和detail这两个页面均包含一个text组件和button组件:text组 /* index.css */ /* detail.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -60,11 +62,11 @@ index和detail这两个页面均包含一个text组件和button组件:text组 ```js // index.js -import router from '@system.router'; +import router from '@ohos.router'; export default { launch() { router.push ({ - uri: 'pages/detail/detail', + url: 'pages/detail/detail', }); }, } @@ -72,7 +74,7 @@ export default { ```js // detail.js -import router from '@system.router'; +import router from '@ohos.router'; export default { launch() { router.back(); diff --git a/zh-cn/application-dev/ui/ui-ts-animation-feature.md b/zh-cn/application-dev/ui/ui-ts-animation-feature.md index 16869cea7b746874566257d31d4e9448d0a3967f..115f4f365f715f07e2817044adb0f772785b6ff1 100644 --- a/zh-cn/application-dev/ui/ui-ts-animation-feature.md +++ b/zh-cn/application-dev/ui/ui-ts-animation-feature.md @@ -305,7 +305,7 @@ .height(184) .width('100%') .onClick(() => { - router.push({ url: 'pages/FoodDetail', params: { foodId: this.foodItem } }) + router.push({ url: 'pages/FoodDetail', params: { foodData: this.foodItem } }) }) } } diff --git a/zh-cn/application-dev/ui/ui-ts-components-intro.md b/zh-cn/application-dev/ui/ui-ts-components-intro.md index 5af40fbdf7ee2567a2d761431cea84c69eb31c98..098791ee5e3a4787d7a85eee43b417a5f88007d5 100644 --- a/zh-cn/application-dev/ui/ui-ts-components-intro.md +++ b/zh-cn/application-dev/ui/ui-ts-components-intro.md @@ -17,8 +17,6 @@ - [`Canvas`:画布组件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) -- [`Xcomponent`:XComponent(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/XComponent) - - [`Clock`:简单时钟(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) - [`PatternLock`:图案密码锁组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/PatternLock) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md index deceb78528aafceed81f93b0352cd0d5f65efb52..565bdddd400c9a2fb32714855fdce94830292ea9 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -83,7 +83,7 @@ GridRow({ } }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") }.backgroundColor(color) }) @@ -264,7 +264,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ForEach(this.bgColors, (color, index) => { GridCol({ span: 2 }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") } .backgroundColor(color) @@ -281,7 +281,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ForEach(this.bgColors, (color, index) => { GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") } .backgroundColor(color) diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md index 77a1755900cdc27ab3ff42aa094d77270c9a1e9e..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.'); }); }); ``` @@ -136,16 +136,13 @@ 当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用`destroy`接口销毁子窗口。 ```js - // 销毁子窗口。当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用destroy接口销毁子窗口,此处以监听窗口区域外的点击事件实现子窗口的销毁。 - windowClass.on('touchOutside', () => { - console.info('touch outside'); - windowClass.destroy((err, data) => { - 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)); - }); + // 销毁子窗口。当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用destroy接口销毁子窗口。 + 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.'); }); ``` @@ -189,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', @@ -222,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.'); }); ``` @@ -237,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 22276bfd2365379cddbb9c32a8e7ef83008f66a2..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.'); }); } }; @@ -127,11 +127,12 @@ class MainAbility extends Ability { ```ts import Ability from '@ohos.application.Ability' + let windowStage_ = null; + let sub_windowClass = null; class MainAbility extends Ability { - onWindowStageCreate(windowStage) { + showSubWindow() { // 1.创建应用子窗口。 - 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; @@ -139,7 +140,7 @@ class MainAbility extends Ability { sub_windowClass = data; console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); // 1.获取已创建的应用子窗口。 - windowStage.getSubWindow((err, data) => { + windowStage_.getSubWindow((err, data) => { if (err.code) { console.error('Failed to obtain the subWindow. Cause:' + JSON.stringify(err)); return; @@ -148,46 +149,60 @@ 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.'); }); }); - // 4.销毁子窗口。当不再需要子窗口时,可根据具体实现逻辑,使用destroy对其进行销毁。 - 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对其进行销毁。 + 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.'); + }); + } + + onWindowStageCreate(windowStage) { + windowStage_ = windowStage; + // 开发者可以在适当的时机,如主窗口上按钮点击事件等,创建子窗口。并不一定需要在onWindowStageCreate调用,这里仅作展示 + this.showSubWindow(); + } + + onWindowStageDestroy() { + // 开发者可以在适当的时机,如子窗口上点击关闭按钮等,销毁子窗口。并不一定需要在onWindowStageDestroy调用,这里仅作展示 + this.destroySubWindow(); + } }; ``` @@ -227,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', @@ -259,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.'); }); } }; @@ -341,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/application-dev/windowmanager/window-overview.md b/zh-cn/application-dev/windowmanager/window-overview.md index 40d122f4bb00a706739c186d14f4cf5e4b8c5160..f98f6d42d9d1130daca4a0c30bed28babc0926e1 100644 --- a/zh-cn/application-dev/windowmanager/window-overview.md +++ b/zh-cn/application-dev/windowmanager/window-overview.md @@ -65,4 +65,8 @@ OpenHarmony的窗口模块将窗口界面分为系统窗口、应用窗口两种 ## 约束与限制 -在FA模型下,不支持系统窗口的相关开发。 +- 在FA模型下,不支持系统窗口的相关开发。 + +- 应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +- 系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 \ No newline at end of file diff --git a/zh-cn/contribute/prebuilts-readme-template.md b/zh-cn/contribute/prebuilts-readme-template.md new file mode 100644 index 0000000000000000000000000000000000000000..0e30f1a9788b6311c774c298bc29bf9f1185a336 --- /dev/null +++ b/zh-cn/contribute/prebuilts-readme-template.md @@ -0,0 +1,28 @@ +OpenHarmony中的Clang/LLVM-based预编译工具 说明 +==================================================== + +1. 获取最新版本的说明文档,请参考如下: +[基于Clang/LLVM-based OpenHarmony工具说明文档](https://gitee.com/openharmony/third_party_llvm-project/blob/master/llvm-build/README.md) + +2. 构建指导 +------------------ + +``` +# 获取代码 +repo init -u https://gitee.com/openharmony/manifest.git -b llvm_toolchain-dev +repo sync -c +repo forall -c 'git lfs pull' +cp -r toolchain/llvm-project/llvm-build toolchain + +# 编译基于Clang/LLVM的 prebuilts工具 +./toolchain/llvm-project/llvm-build/env_prepare.sh +python3 ./toolchain/llvm-build/build.py +``` + +3. 更新预编译工具 +---------------- +在OpenHarmony项目中运行脚本: + +``` +$ ./build/prebuilts_download.sh +``` diff --git "a/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" "b/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" index 32cc3b647502e1862a928f76b02847f8b0a2b620..8092b528d1960f5a83df17416cded1c565b37c32 100755 --- "a/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" +++ "b/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" @@ -40,6 +40,22 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) , 12. 引入新的开源软件存在依赖其他开源软件时,不允许将被动依赖软件嵌套在引入的新的开源软件子目录中,必须剥离所有依赖软件项,并将其分别放置到单独的代码仓,命名统一为third_party_依赖软件名称,原因是嵌套放置依赖软件可能导致多同一款软件多版本、旧版本安全漏洞无法及时修复、开源义务履行合规的风险问题。 - 依赖软件在编译构建部件命名,将新引入的主软件名作为依赖软件部件前缀命名,例如 part_name = "新引入主软件名_依赖软件名" - 新引入软件和依赖软件分别独立构建,通过external_deps来解决部件间依赖。 +13. OpenHarmony对引入三方开源软件的归档目录要求: + - 原则上如果您没有真正充分的理由将其存储在其他地方,且满足OpenHarmony许可证引入要求三方开源软件,统一归属于third_party根目录下; + - 针对开发板引入且无法纳入OpenHarmony系统平台的三方开源软件,可以申请在以下位置存档,要求以上游开源软件名创建目录,并在对应目录下归档README.OpenSource说明文档;采取BUILD.gn方式独立构建,支撑开源义务声明信息的自动收集。 + + ``` + device/soc/$(SOC_COMPANY)/third_party + device/board/$(BOARD_COMPANY)/third_party + vendor/$(PRODUCT_COMPANY)/third_party + ``` + +14. OpenHarmony平台版本或版本构建中用到的预编译二进制或工具链,需提供如下信息: + - 预编译二进制或工具链对应的源码,需要在OpenHarmony社区托管对应的源代码,并提供对应的构建指导,开源义务履行遵从指导; + - 预编译二进制或工具链中引入的开源三方软件,需要遵从原则1~13; + - [预编译二进制或工具链的说明文档](./prebuilts-readme-template.md):包括源码获取地址、构建指导、更新方法,随OpenHarmony版本或工具链归档到对应模块的根目录中; + - 预编译的二进制或工具链对应的根目录需要提供完整开源义务履行声明文档; + - 如果预编译文件来源于上游社区托管平台的二进制(譬如npm包等)。我们需要在归档二进制的地方提供以下信息,首先我们需要提供一个命名为**README**概要性描述文件,内容包括引入的背景描述和其官方托管地址;其次我们需要提供一个命名为**NOTICE**的开源义务履行声明的描述文件,内容包括其中涉及的没一个开源软件名称、版本号、以及对应的开源许可协议。 ### 软件引入流程 @@ -47,7 +63,7 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) , | 检查项 | 说明 | | :----- | :----- | -| 归一化 | 1、检查该软件在OpenHarmony中是否已存在,原则上一款软件只在OpenHarmony中引入一次。 | +| 归一化 | 1、检查该软件在OpenHarmony中是否已存在,原则上一款软件只在OpenHarmony中引入一次。| | 来源可靠 | 1、应该从开源软件官网获取或官网指定的代码托管地址获取。 | | 社区活跃 | 1、软件来自知名社区或组织,社区或组织通过发布公告、修改软件仓库状态、将仓库放到特定目录下等方式告知停止维护的,不建议引入。
2、软件来自个人、小型社区或组织,两年内未发布版本(含正式版本与测试版本),无明确版本计划,社区提交了有效的Bug或PR,但是半年以上未响应的,不建议引入。
3、社区运营状态不明确,通过Issue 或者邮件等方式询问社区是否继续维护,半年以上未响应或者答复停止维护的,不建议引入。| | 安全漏洞 | 1、检索业界已知公开的安全漏洞,如有高危漏洞需要有应对方案。| @@ -61,13 +77,13 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) , 1、自检表 -| 检查项 | 填写指导 | 自检结果示例 | +| 检查项 | 填写指导 | 自检结果示例 | | :----- | :----- | :----- | | 软件名 | 描述该软件官方名称以及引入后的仓名,仓名统一为**third_party**_**加上官方软件名称** | third_party_**softwarename** | -| 软件官网地址 | 描述该软件官方网站链接地址 | https://softwaresite | +| 软件官网地址 | 描述该软件官方网站链接地址 | | | 软件版本号 | 描述该软件要引入的版本号,版本号为其社区正式发布的版本号,不要随意修改;未正式发布的版本不建议引入 | 1.0.0 | | 软件版本发布日期 | 描述该软件要引入的版本的社区发布日期 | 2021.01.01 | -| 软件版本地址 | 描述该版本的官方下载链接地址,注意该地址必须为能定位到该具体版本发布包的下载URL | https://gitee.com/softwarecodesite/v1.0.0.zip | +| 软件版本地址 | 描述该版本的官方下载链接地址,注意该地址必须为能定位到该具体版本发布包的下载URL | | | 软件许可证 | 描述该版本的官方许可证名称及许可证文件的相对路径,如果是多许可证要完整描述,并说明各许可证的关系,如是And还是Or,或者是不同目录对应不同许可证 | Apache-2.0 | | 软件生命周期 | 描述该软件是否有LTS版本,多长时间发布一个版本,最近一年社区代码提交及Issue解决情况,是否有告知停止维护或演进 | 无LTS版本,6个月发布一个版本,近6个月有10次代码提交 | | 软件安全漏洞 | 描述该软件存在的业界公开的安全漏洞列表,包括漏洞号、级别、漏洞链接地址、是否已有补丁或解决方案 | 无业界公开漏洞 | @@ -78,7 +94,7 @@ OpenHarmony遵从 [Open Source Definition](https://opensource.org/docs/osd) , 说明: -- OAT工具的使用方式请参考 https://gitee.com/openharmony-sig/tools_oat ,如对工具有改进建议请直接在社区提交ISSUE,也可Fork下来完善工具并提交PR。 +- OAT工具的使用方式请参考 ,如对工具有改进建议请直接在社区提交ISSUE,也可Fork下来完善工具并提交PR。 - OAT报告原则上应当是清零,格式如下: ``` @@ -100,7 +116,7 @@ third_party_abcde/doc/ LICENSEFILE LICENSE Apache-2.0 2、OAT.xml文件 -请参考 https://gitee.com/openharmony-sig/tools_oat/blob/master/README_zh.md ,完成OAT扫描问题确认及OAT.xml文件配置,申请中附上此文件内容(如果无任何需确认问题则无需配置)。 +请参考 ,完成OAT扫描问题确认及OAT.xml文件配置,申请中附上此文件内容(如果无任何需确认问题则无需配置)。 3、该仓的README.OpenSource文件内容,格式如下: @@ -121,9 +137,9 @@ third_party_abcde/doc/ LICENSEFILE LICENSE Apache-2.0 ] ``` -#### PMC评审 +#### 新增三方开源软件评审 -参考[SIG管理章程](https://gitee.com/openharmony/community/tree/master/sig),PMC会根据收到的PR统一安排SIG申请评审以及建仓。 +参考[SIG-Architecture](https://gitee.com/openharmony/community/blob/master/sig/sig-architecture/sig-architecture_cn.md),SIG-Architecture会统一安排建仓评审。 ### 第三方开源软件许可证要求 @@ -131,66 +147,66 @@ third_party_abcde/doc/ LICENSEFILE LICENSE Apache-2.0 2. 第三方开源软件许可证必须与使用该开源软件的代码仓许可证兼容。 3. 如下类型许可证可以引入到OpenHarmony项目中: -* Apache License 2.0 -* Mulan Permissive Software License, Version 2 -* BSD 2-clause -* BSD 3-clause -* DOM4J License -* PostgreSQL License -* Eclipse Distribution License 1.0 -* MIT -* ISC -* ICU -* University of Illinois/NCSA -* W3C Software License -* zlib/libpng -* Academic Free License 3.0 -* Python Software Foundation License -* Python Imaging Library Software License -* Boost Software License Version 1.0 -* WTF Public License -* UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE -* Zope Public License 2.0 +- Apache License 2.0 +- Mulan Permissive Software License, Version 2 +- BSD 2-clause +- BSD 3-clause +- DOM4J License +- PostgreSQL License +- Eclipse Distribution License 1.0 +- MIT +- ISC +- ICU +- University of Illinois/NCSA +- W3C Software License +- zlib/libpng +- Academic Free License 3.0 +- Python Software Foundation License +- Python Imaging Library Software License +- Boost Software License Version 1.0 +- WTF Public License +- UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE +- Zope Public License 2.0 4. 如下类型许可证不建议引入到OpenHarmony项目中: -* GNU GPL 1, 2, 3 -* GNU Affero GPL 3 -* GNU LGPL 2, 2.1, 3 -* QPL -* Sleepycat License -* Server Side Public License (SSPL) version 1 -* Code Project Open License (CPOL) -* BSD-4-Clause/BSD-4-Clause (University of California-Specific) -* Facebook BSD+Patents license -* NPL 1.0/NPL 1.1 -* The Solipsistic Eclipse Public License -* The "Don't Be A Dick" Public License -* JSON License -* Binary Code License (BCL) -* Intel Simplified Software License -* JSR-275 License -* Microsoft Limited Public License -* Amazon Software License (ASL) -* Java SDK for Satori RTM license -* Redis Source Available License (RSAL) -* Booz Allen Public License -* Creative Commons Non-Commercial -* Sun Community Source License 3.0 -* Common Development and Distribution Licenses: CDDL 1.0 and CDDL 1.1 -* Common Public License: CPL 1.0 -* Eclipse Public License: EPL 1.0 -* IBM Public License: IPL 1.0 -* Mozilla Public Licenses: MPL 1.0, MPL 1.1, and MPL 2.0 -* Sun Public License: SPL 1.0 -* Open Software License 3.0 -* Erlang Public License -* UnRAR License -* SIL Open Font License -* Ubuntu Font License Version 1.0 -* IPA Font License Agreement v1.0 -* Ruby License -* Eclipse Public License 2.0: EPL 2.0 +- GNU GPL 1, 2, 3 +- GNU Affero GPL 3 +- GNU LGPL 2, 2.1, 3 +- QPL +- Sleepycat License +- Server Side Public License (SSPL) version 1 +- Code Project Open License (CPOL) +- BSD-4-Clause/BSD-4-Clause (University of California-Specific) +- Facebook BSD+Patents license +- NPL 1.0/NPL 1.1 +- The Solipsistic Eclipse Public License +- The "Don't Be A Dick" Public License +- JSON License +- Binary Code License (BCL) +- Intel Simplified Software License +- JSR-275 License +- Microsoft Limited Public License +- Amazon Software License (ASL) +- Java SDK for Satori RTM license +- Redis Source Available License (RSAL) +- Booz Allen Public License +- Creative Commons Non-Commercial +- Sun Community Source License 3.0 +- Common Development and Distribution Licenses: CDDL 1.0 and CDDL 1.1 +- Common Public License: CPL 1.0 +- Eclipse Public License: EPL 1.0 +- IBM Public License: IPL 1.0 +- Mozilla Public Licenses: MPL 1.0, MPL 1.1, and MPL 2.0 +- Sun Public License: SPL 1.0 +- Open Software License 3.0 +- Erlang Public License +- UnRAR License +- SIL Open Font License +- Ubuntu Font License Version 1.0 +- IPA Font License Agreement v1.0 +- Ruby License +- Eclipse Public License 2.0: EPL 2.0 如要引入其它类型License或上述(4)所列License,请联系邮箱:oh-legal@openatom.io。 @@ -219,4 +235,4 @@ third_party_abcde/doc/ LICENSEFILE LICENSE Apache-2.0 如果软件符合以上任何一条退出条件,PMC与相应SIG首先分析该软件在当前OpenHarmony社区中被依赖、被使用的情况。 1. 如果OpenHarmony中存在依赖关系,且短时间内不能解除,我们建议SIG新建分支代码仓,并主动进行社区维护动作。 -2. 如果OpenHarmony中不存在依赖关系,或者短时间内可以解除,则责任SIG将软件从OpenHarmony正式发行中移出,并在相应的Release Notes中说明移除的原因及影响。 \ No newline at end of file +2. 如果OpenHarmony中不存在依赖关系,或者短时间内可以解除,则责任SIG将软件从OpenHarmony正式发行中移出,并在相应的Release Notes中说明移除的原因及影响。 diff --git a/zh-cn/design/API-Review-Template.md b/zh-cn/design/API-Review-Template.md index 0c7dacf02ef71c1ff7a2ab77afdddcb0d355bb74..ed26f538818e2a0da6131c63a6a7f1bd460480ab 100644 --- a/zh-cn/design/API-Review-Template.md +++ b/zh-cn/design/API-Review-Template.md @@ -2,7 +2,7 @@ ## 背景 -* API类型:[Public API | Test API| HDI] +* API类型:[Public API | System API |Test API| HDI] * API需求来源: * API使用场景: * API所属子系统: diff --git a/zh-cn/design/OpenHarmony-API-governance.md b/zh-cn/design/OpenHarmony-API-governance.md index a99e605980ecca03cb9e2f8a10e6d21f0136ca50..b56d09d461dd22683fcd66a0b4085fd865fa082d 100755 --- a/zh-cn/design/OpenHarmony-API-governance.md +++ b/zh-cn/design/OpenHarmony-API-governance.md @@ -28,7 +28,7 @@ OpenHarmony软件栈中包含了多个角色,因此API也分作多种类型。 各类型API说明如下: * Public API:OpenHarmony对所有应用开发者公开的API。 -* Test API:测试专用的API,供开发者使用。 +* Test API:测试专用的API,仅在测试阶段使用。 * System API:提供给系统特权应用使用的API,普通应用无法使用。 * HDI:描述硬件能力的接口。 * Driver API:提供给驱动开发者使用的接口。 @@ -41,6 +41,7 @@ OpenHarmony的目标是构建面向万物互联时代的新一代操作系统, * C/C++ * JavaScript * TypeScript +* ArkTS 本章程所描述的内容与编程语言无关。即:在不违反编程语言要求的情况下,API不分编程语言都要遵守章程的要求。 @@ -66,7 +67,7 @@ API评审流程如下: 1. API评审申请、代码提交(Owner:Contributor),所有涉及API新增或变更需同步提交相应的API评审文档,详细说明API的需求来源、场景与使用方法、权限设计、隐私保护澄清等,详见后面的API评审申请要素。为避免后续的返工,Contributor可以在正式的API评审申请、代码提交之前,先通过邮件方式将API设计文档提交Committer、领域SIG、API SIG等相关人员预审。 1. 代码评审(Owner:Committer),代码评审和API预审,涉及API提交Code Review通过后,还需要进一步领域SIG评审。如果单次提交同时涉及多个领域的API新增或变更,相应的API评审申请和代码需要同时提交给相关领域的Committer评审,只有所有对应领域的Committer都完成CodeReview后才能进入下一评审环节。 1. API评审(Owner:领域SIG),新增API相关的代码提交评审,领域SIG评审通过即可代码合入;变更API相关的代码提交,领域SIG评审通过后,还需要进一步提交API SIG。如果单次提交同时涉及多个领域的API新增,相应的API评审申请和代码需要同时提交给相关领域的SIG评审,只需一个领域SIG评审通过即可代码合入。如果单次提交同时涉及多个领域的API变更,相应的API评审申请和代码需要同时提交给相关领域的SIG评审,只有所有对应领域的SIG都要评审通过才能进入下一评审环节。 -1. API变更评审(Owner:API SIG),变更API相关的代码提交评审,评审通过即可代码。 +1. API变更评审(Owner:API SIG),变更API相关的代码提交评审,评审通过即可编码。 1. 评审完成。 ### API评审申请要素 @@ -74,88 +75,24 @@ API评审流程如下: 如果涉及API新增或变更需同步提交相应的API评审文档。API评审文档使用[《OpenHarmony API 评审模板》](API-Review-Template.md)描述。 针对新增API,需要包含如下要素: -1. 需求来源与使用场景(必须)。 -1. API现状与差距分析,说明API新增或变更的必要性(必须)。 -1. API原型设计与使用方法说明(必须);必要时,可以进一步包含相应的使用样例(可选)。 -1. API权限设计(必须)。 -1. API隐私保护方案与要求满足情况澄清(必须); -1. 提交代码的同时提交相应的API参考(必须);必要时,可同步提交相应的开发者指南文档(可选)。 -1. 兼容性/性能/功耗/可靠性/测试等相关情况说明(可选,如不满足本章程 “API设计要求”,则必须包含相关说明)。 +1. (必选)需求来源与使用场景。 +1. (必选)API现状与差距分析,说明API新增或变更的必要性。 +1. (可选)API原型设计与使用方法说明(必须);必要时,可以进一步包含相应的使用样例。 +1. (必选)API权限设计。 +1. (必选)API隐私保护方案与要求满足情况澄清; +1. (可选)提交代码的同时提交相应的API参考(必须);必要时,可同步提交相应的开发者指南文档。 +1. (可选)兼容性/性能/功耗/可靠性/测试等相关情况说明(如不满足本章程 “API设计要求”,则必须包含相关说明)。 针对变更API,需要额外包含如下要素: 1. 针对老接口的处理方式(废弃、隐藏或彻底删除)以及对使用老SDK开发应用的兼容措施(必须); 2. 变更影响、替代接口和相应的应用适配方案(必须)。 3. 刷新ChangeLog(必须) 和 API-diff文档(涉及JS/Native API变更,必须)。 -## API设计要求 - - -### 一致性要求 -1. 概念一致性:基于场景的业务模型抽象,形成OpenHarmony的连贯、一致、自恰的用户程序模型和业务概念。 -1. 术语一致性:相应的业务术语必须采用统一名词,不允许使用多个语意接近的名词表示同一个业务对象;同样地,为了避免产生混淆,也不允许针对不同的业务对象使用相同的名词或语言接近的名词。 -1. 操作一致性:相同的操作动作必须采用同一动词。 -1. 参数顺序一致性:相同参数/参数序列在多个API中的位置和顺序保持一致。 -1. 机制及算法一致性:通信机制、调用模式、认证机制、加密算法等保持一致。 -1. 帮助、Demo、模板风格一致性:排版、用法等保持一致。 - -### 易用性要求 -以“能力使用者”视角,而不是“能力提供者”视角设计API: -1. 可理解:API命名和功能特性必须容易理解。 -1. 易使用:提供简单易用的API,减少API之间不必要的耦合,避免多个无之间关联关系API之间调用顺序的依赖,尽可能使调用者优雅,尽量避免使用单一功能时必须同时组合调用多个包/模块或类中的多方法才能实现。 -1. 避免误导:提供使用者期望的能力,避免误导,减少误用。 -1. 提供必要的API文档。 - -### 命名要求 -1. 能清晰的表达意图:使用完整的描述性的单词。 -1. 避免造成误导:有误导的名字比表达不清的名字还要有危害性。 -1. 词义清晰明了,避免使用info,data,object等一般意义的词。 -1. 作用域越大,命名应越精确。 -1. 不用或少用缩写,业界通用术语遵从行业习惯允许使用缩写。 -1. 包名/模块名/命名空间前缀约定: - 1. JS API 统一模块名:@ohos.\*。 - 2. Native API 统一命名空间:namespace OHOS.\*。 - 3. 引用外部开源代码的,可以保留原包名/模块名/命名空间,也可以按照上述规则对包名统一进行替换。 -1. 包名/模块名/命名空间最短不少于2段,最长不超过4段;每一段建议使用一个单词,最长不超过2个单词。 -1. 类名、方法名/函数名、成员变量、变量名最多不超过4个单词。 - -### 权限控制要求 -1. 完备性原则:一切穿透应用沙箱的行为都需考虑使用权限来管控。 -1. 最优粒度原则:一个权限只保护一类对象;一个接口仅需申请一个权限即可访问。 -1. 清晰完整原则:权限定义中必须清晰说明保护对象、开放范围、敏感级别。 -1. 最小开放原则:一个权限仅对确有正当业务需求的应用开放,开放控制可通过权限来实现。 - -### 隐私保护要求 -1. API调用的返回仅包含必要的内容, 避免携带额外信息。 -1. API调用不允许获取、手机用户个人数据, 除非通过用户权限管控、由用户授权同意。 -1. API涉及跨应用调用时,如涉及个人数据向被调用者的披露,由调用方在隐私声明中说明披露的数据类型、数据接收者和数据使用目的。 -1. API涉及到用户敏感数据(如电话、通讯录、媒体等)访问时,需要使用system picker的机制,禁止API通过申请敏感权限方式访问。 -1. API开放禁止捆绑与所开放能力不相关的功能。 - -### 文档化要求 -1. API参考采用英文方式交付。 -1. 模块/包模块的API参考必须包括简要描述和详细描述。 -1. 类、方法、“Interface”、枚举或成员变量的API参考必须包括简要描述。 -1. 类、方法、“Interface”、枚举或成员变量的API参考可选包括详细描述。 -1. 方法、“Interface”的API参考必须包括所有入参的参数描述。 -1. 如果方法或“Interface”有返回值,则API参考必须包含返回值描述。 -1. 如果执行过程中可能抛出异常,则API参数必须包含相关的异常描述。 -1. 必须包含API的起始版本号(使用@since注释标记)。 -1. 可选包括本模块或类自己的版本号(使用@version注释标记)。 -1. 涉及API变更(不兼容),必须同步交付API-Diff和ChangeLog文档。 - -### 兼容性要求 -1. 按严格程度从高到低,API兼容要求包括:契约兼容 > 二进制兼容 > 源码兼容。 - 1. 源码兼容:指版本演进后,开发者已有的源代码可正常编译通过。 - 1. 二进制兼容:指版本演进后,开发者已有程序不用重新编译可正常链接、运行。 - 1. 契约兼容:也称语义兼容,指版本演进后,开发者原有程序行为不发生变化。 -1. OpenHarmony API后向兼容必须满足二进制兼容要求,例外情况需要通过API SIG评审并经过PMC批准。常见破坏二进制兼容的API变更包括: - 1. 任何API元素删除; - 1. 降低方法的可见性,例如protected修改为了private,或者public修改为protected。 - 1. 类类型发生变化,例如抽象类变更为非抽象类,或者接口类(“Interface”)变更为非接口类。 - 1. 方法原型发生变化,例如返回值类型修改,或入参顺序或入参类型发生变化。 - 1. 成员final/static等属性发生变化,例如非final成员变成final,或者非static的成员变成static。 -1. 禁止“原型相同、功能不兼容”的API修改,可受限使用“废弃old-api、新增new-api”的方式进行修改。 -1. 根据发布类型不同,API的生命周期和兼容性要求: +## API的生命周期和兼容性要求 + +OpenHarmony API会以API version的形式逐步演进。每个版本会经历如下图的发布周期。 + +不同周期的API其兼容性要求如下所述: ![](figures/API-Lifecycle.png) @@ -173,33 +110,6 @@ API评审流程如下: 1. 提供可替代接口。 1. 废弃API至少保留5个API Version版本(对废弃5个API Version的API可以彻底删除,不再支持)。 -### 性能要求 -1. 应及时响应,避免调用者等待;如果API调用执行时间过长应设计为异步方式。 -2. 应关注API调用时机、调用频次对RAM占用的影响。 -3. 应关注API调用时机、调用频次对功耗的影响。 -4. 对使用资源的API调用需要能及时释放资源,异常场景具备容错机制,保障资源及时释放。 - -### 功耗要求 - -1. 针对API调用时机、调用频次对功耗的影响做评估,有影响进行相关设计。 -2. 版本演进过程中,功耗不劣化。 - -### 可靠性要求 - -1. API不能因为外部输入(输入参数、系统状态、外部数据等)或者内部状态、数据异常而崩溃,应该返回确定的错误码或者抛出预定义的异常。 -2. API应明确调用是同步还是异步调用,若是同步调用,应明确超时上限或者允许调用者设置超时时间,避免调用卡死导致业务无响应。 -3. API务必支持多线程重入。 -4. 满足幂等性要求,相同业务含义的请求API调用一次或多次重试总能获得相同的效果(API调用依赖外部资源的变化除外)。针对可重入的API调用实现内部应尽量避免引入时变因素,如系统tick、静态变量、没有互斥保护的全局变量等;针对同一客户端的多次重复调用,可以使用contextID、clientToken、sequenceNo等作为调用入参。 -5. API内部创建对象的生命周期要闭合,避免对象资源泄漏。 -6. API要明确客户端调用失败后,能够发起重试的最大次数。 - -### 测试要求 -1. 新增API必须同步交付API自动化测试用例,用例100%覆盖API接口。 -2. 用例场景单一,单条用例覆盖接口单个功能场景,简化单条用例代码逻辑。 -3. 用例执行高效,每条用例执行时间控制在毫秒级。 -4. 用例执行全自动化:接口用例需要达成100%自动化。 -5. 用例有效性:用户要求必须存在断言,且不能仅是检查是否抛出异常,需要有功能逻辑的断言。 - -### 编程语言要求 +### API 设计规范 -API根据其编程语言类型,需要遵守相应的OpenHarmony编程语言规范。 +关于这部分内容,请参见[《OpenHarmony API设计规范》](OpenHarmony-API-quality.md)。 diff --git a/zh-cn/design/OpenHarmony-API-quality.md b/zh-cn/design/OpenHarmony-API-quality.md new file mode 100644 index 0000000000000000000000000000000000000000..21d0ca4e81dd6e15ebd7247439bd1953e5e09aef --- /dev/null +++ b/zh-cn/design/OpenHarmony-API-quality.md @@ -0,0 +1,858 @@ +# OpenHarmony API 设计规范 + +* 修订记录 + +| 版本 | 作者 | 时间 | 更新内容 | +| -------------- | ------------------- | ---------- | ---------- | +| v0.1,试运行版 | OpenHarmony API SIG | 2022年11月 | 初版发布 | + +## 目的 + +API是软件实现者提供给使用者在编程界面上的定义,API在很大程度上体现了软件实体的能力范围。 + +同时,API定义的好坏极大影响了使用者的体验。 + +为了保障OpenHarmony生态健康发展,保证开发者使用体验,现制定OpenHarmony API设计规范。 + +## 范围 + +OpenHarmony API主要包含了对应用开放的外部API,以及系统实现部分的内部API。 + +本设计规范主要用以约束以下API(不区分编程语言): + +* OpenHarmony Public API +* OpenHarmony System API + +关于OpenHarmony API的分类,请参见[《 OpenHarmony API治理章程》](https://gitee.com/openharmony/docs/blob/master/zh-cn/design/OpenHarmony-API-governance.md)。 + +## 接口设计目标 + +好的接口设计应该满足以下四点: + +* **可使用** (Operational):这一点是毋庸置疑的,接口必须要能完成它提供的能力。可使用是最基本的要求。 +* **富于表现力** (Expressive):与可使用同样重要的是,借助接口,使用者能够清晰表达他们想要做的事情。 +* **简单** (Simple):接口的设计要保证学习和使用简单,避免难于理解或者使用出错的情况发生。 +* **可预测** (Predictable):API应当始终一致的按照接口的定义完成使命。如果接口定义中不包含出错和异常的情况,那么这个API被调用任意多遍,都不应该发生任何异常。当然,如果实际情况是有可能出错或者失败的,那就要在接口定义中说明清楚什么情况下会出什么错,并准确的在相应的时机下返回对应的错误。 + +除此之外,API的设计还应该注意以下几点: + +* **API的稳定性和一致性是最重要的,API并非越多越好。** +* **API命名应当容易理解,API命名并非越短越好。** +* **API应当做好封装和抽象,并非暴露的信息或者能力越多越好。** + +从开发者使用API的阶段上来看,API应当做到: + +* **在学习阶段** + * 容易理解 + * 容易上手 +* **在开发阶段** + * 富于表现力 + * 简单 + * 可预测 +* **在维护阶段** + * 行为稳定 + * 容易维护 + +## API设计概述 + +为了使得规则尽可能通用,本规范不会涉及具体编程语言的差异,也不会涉及编码规约。这部分内容只要遵守相应的本地要求即可。 + +从整体上来看,本规范将API规范分成**发布前评审规范**和**发布后评价**两个部分。 + +* **发布前评审规范** :是对于API的最基本要求,所有API必须满足这些要求才能通过评审。 +* **发布后评价** :尽管在发布前已经做了很多的规则要求。但是仍然不能保证API是完美的。因此,API发布后仍然要保持对API的关注。发布后的审视将影响对API提供者的评价。 + +以下是所有的API设计规则的罗列,以供快速索引,详细的说明在后文中展开。 + +每一个OpenHarmony API提供者都应该熟悉以下规则。 + +### 发布前评审规范 + +* 易用性 + * 规则1:符合编码规则 + * 规则2:准确使用英语语法 + * 规则3:合理使用缩写 + * 规则4:准确使用对仗词 + * 规则5:准确使用设计/架构模式 + * 规则6:避免有争议的命名 + * 规则7:参数类型合理 + * 规则8:参数数量合理 + * 规则9:参数顺序合理 + * 规则10:返回值定义完备 + * 规则11:异常定义合理 + * 规则12:从正面表达 + * 规则13:降低出错的可能性 + * 规则14:避免顺序耦合 + * 规则15:准确表达所有逻辑 + * 规则16:注意封装 + * 规则17:单一职责 +* 可用性 + * 规则18:保证可靠性 + * 规则19:功能完备 + * 规则20:考虑权限与隐私保护 + * 规则21:考虑并发环境 + * 规则22:注意资源管理闭合 + * 规则23:考虑重试逻辑 + * 规则24:满足幂等要求 + * 规则25:考虑设备通用性 +* 一致性 + * 规则26:保证术语、概念一致性 + * 规则27:保证设备间行为一致性 + * 规则28:注意版本演进一致性 + * 规则29:命名风格保持一致 + * 规则30:参数顺序保持一致 + * 规则31:同步/异步风格一致 +* 兼容性 + * 规则32:注意新旧系统版本的兼容性 + * 规则33:二进制向后兼容性 +* API资料 + * 规则34:模块、命名空间、类需要包含基础说明 + * 规则35:使用场景说明清晰 + * 规则36:接口说明准确 + * 规则37:参数说明准确 + * 规则38:返回值/异常描述准确 + * 规则39:元信息完备 + * 规则40:风格一致 +* 组织方式 + * 规则41:分层合理 + * 规则42:模块划分合理 + * 规则43:应用描述文件也是接口的一部分 +* 质量属性 + * 规则44:性能满足要求 + * 规则45:功耗设计合理 + * 规则46:需要保证可测试性 + * 规则47:考虑环境适应性 + +### 发布后评价 + +* 稳定性 + * 规则48:接口废弃率/变更率越低越好 +* 安全性 + * 规则49:避免接口被滥用 + * 规则50:避免接口被利用 +* 可维护性 + * 规则51:能承载业务演进 + * 规则52:功能扩展后不影响原先行为 + * 规则53:文档和资料配套更新 +* 不可替代性 + * 规则54:保证API之间正交 +* 开发者反馈 + * 规则55:关注开发者反馈 + +## 发布前评审规范说明 + +### 易用性 + +任何设计都应该考虑易用性。对于OpenHarmony API来说,易用性需要考虑以下几个方面: + +#### 命名 + +* **规则1:符合编码规约** + +API的定义首先应当满足所属项目的编码规约,例如:大小写的定义、下划线、连字符规则、前缀规则等。 + +对于OpenHarmony生态而言,可参考如下编码规约: + +* [《OpenHarmony JavaScript语言通用编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-JavaScript-coding-style-guide.md) +* [《OpenHarmony C语言编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-c-coding-style-guide.md) +* [《OpenHarmony C++语言编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-cpp-coding-style-guide.md) +* [《OpenHarmony C&C++ 安全编程指南》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-c-cpp-secure-coding-guide.md) +* [《OpenHarmony HDF驱动编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md) +* **规则2:准确使用英语语法** + +API命名只允许使用英语。通常,类的名称是名词,例如:`XXXManager`,`XXXService`,`XXXAnimation`等。函数通常是动词或动宾结构,例如:`start()`,`createUser()`,`startBoot()`等。 + +对于一个名称叫做`Start`的类,或者一个叫做`ball()`的函数,通常是错误的做法。 + +另外,还请注意及物动词和不及物动词,避免语法错误。对于动词,根据场景需要注意时态。例如:如果时机上就存在“开始传输”和“渲染完成”这些事件,就应该用上`transferStarted()`以及`renderDone()`这类的表达。 + +* **规则3:合理使用缩写** + +应当尽可能避免使用缩写。缩写不仅仅是难于理解,还有一个问题是:一个缩写可能会有多个解释,在上下文信息不全的情况下,使用者会很难分辨。 + +如果是大家都熟知的缩写是允许的,除此之外,应该尽量避免。尤其是,只有自己能明白的缩写,这是禁止的。 + +* **规则4:准确使用对仗词** + +在语言表达中,同一个含义可能有很多个类似的词可以表达,例如: + +| 词语 | 近义词 | +| ----- | -------------------------------------------------- | +| send | deliver, dispatch, announce, distribute, route | +| find | search, extract, locate, recover | +| start | launch, create, begin, open | +| make | create, set up, build, generate, compose, add, new | + +但在API命名中,应当注意对仗词的使用。 + +例如,如果你使用了`add`就应该使用`remove`,而不是`destroy`。使用了`increase`就应该使用`decrease`,而不是`reduce`。 + +下面是一些常见的对仗词: + +| 词语 | 对仗 | +| -------- | -------- | +| add | remove | +| increase | decrease | +| open | close | +| begin | end | +| insert | delete | +| show | hide | +| create | destroy | +| lock | unlock | +| source | target | +| first | last | +| min | max | +| start | stop | +| get | set | +| next | previous | +| up | down | +| new | old | + +* **规则5:准确使用模式** + +设计模式或者架构模式其实是软件行业的“行话”。既然是行话,就要正确的使用,否则别人就可能误解你的意思。 + +因此,当你的接口中包含了`Strategy`,`Builder`,`Factory`,`Singleton`这类的词语时,请确保你准确理解了这些设计模式,并且正确使用了它们。 + +另外,如果你确定的是在使用某个模式,那就准确的在名称上使用标准术语,不要随便修改词性或者打乱名称的词语顺序,这样使用者会更容易理解。 + +* **规则6:避免有争议命名** + +命名要遵守的底线,是应该避免有争议的名称。这其中,包括但不限于任何违反法律、产生宗教争议、或导致种族歧视的词语。 + +当然,使用脏话也是绝对禁止的。考虑到OpenHarmony会使能千行百业,对于避免有争议命名,需要思考得更多。 + +#### 参数 + +* **规则7:参数类型合理** + +通常,使用类类型参数比使用简单类型要更好。 + +例如:对于下面的一组接口看似没什么问题: + +* `addPerson(string id, string name, int age)` +* `removePerson(string id, string name, int age)` +* `modifyPerson(string id, string name, int age)` + +但是这个定义不便于扩展,因为后期可能要新增参数。但是如果一开始就通过一个类类型`Person`来定义参数,则添加一个字段就很容易,并且,对于接口本身不用做任何改变。 + +使用类类型而不是简单类型,还有一个好处是:参数数量会少,更容易记忆。 + +* **规则8:参数数量合理** + +参数数量应当控制在7个以内。在更多的情况下,参数控制在3~5会更容易使用。 + +在任何情况,参数的数量都不应当超过10个,这种接口通常很难记忆和使用。如果遇到这种情况,通常是对类型没有做很好的封装,或者是接口的实现逻辑包含太多的内容。请考虑拆解。 + +* **规则9:参数顺序合理** + +在一些编程语言中,常常会以先输入参数、后输出参数的顺序来组织参数列表。 + +但其实,如果能再根据参数的大小逻辑关系、参数的重要性来进行排序,那对于使用者来说,会更容易记忆和使用。 + +比如,可选参数应该放到必选参数的后面,回调函数作为参数应该放到最后等。以`fs.readFile` 方法为例,路径参数是必填的,`encoding` 和 `flag` 是有默认值的。 + +```js +fs.readFile(path[, options], callback) +``` + +```js +fs.readFile('/etc/passwd', (err, data) => { + if (err) throw err; + console.log(data); +}); + +fs.readFile('/etc/passwd', { + encoding: 'utf-8', + flag: 'r+' +}, (err, data) => { + if (err) throw err; + console.log(data); +}); +``` + +#### 返回值 + +* **规则10:返回值定义完备** + +返回值定义完备需要做到:不能只考虑正常情况,对于接口的定义,也要考虑异常和无效的情况。要让开发者能合理处理。 + +例如: + +* 对于数字类型的返回值,要定义清楚返回的范围,什么情况下会出现极值。 +* 对于布尔类型的返回值,要定义清楚什么时候返回`true`,什么时候返回`false`。 +* 对于数组或者集合类型的返回值,要定义清楚什么时候返回`null`,什么时候返回包含空元素的集合。 +* 对于枚举类型的返回值,要确保每种情况都准确定义了。 +* **规则11:异常定义合理** + +异常是特殊情况的返回,这通常意味着输入参数无效或者函数根本无法正常处理。 + +对于同一个模块,或者同样的业务,在何种情况下返回错误值,在何种情况下直接返回异常,应该有统一的定义。 + +另外,针对同样的异常情况下,应当返回同样的异常类型。 + +保持一致可以很大程度上降低开发者的使用难度,并且避免使用出错。 + +#### 其他 + +对于易用性而言,除了上面提到的内容,还有一些推荐的做法,可以降低开发者的使用难度。 + +* **规则12:从正面表达** + +从正面表达可以降低开发者的思考成本。 + +通俗来说就是:接口的命名尽量使用肯定的词语,而不是否定方式的表达。因为否定表达很难理解。 + +下面是一个反例: + +```js +if (!isNotAccessible() || !isNotWritable() || !isNotPrintable()) +``` + +如何接口都是正面表达,就更容易理解了,下面是推荐的做法: + +```js +if (isAccessible() && isWritable() && isPrintable()) +``` + +* **规则13:降低出错的可能性** + +调用者使用错误很大程度在于参数传递上。 + +例如下面这个函数。第二个和第三个参数都是布尔值,这样使用者很容易记错顺序,或者搞不清楚该传入`true`还是`false`。 + +```js +declare function findString(text: string, isForward: boolean, isCaseSensitive: boolean): string; +``` + +通过枚举在定义上就避免这种错误存在的可能: + +```js +enum SearchDirection { + FORWARD, + BACKWARD +}; + +enum CaseSensitivity { + SENSITIVE, + INSENSITIVE +}; + +declare function findString(text: string, direction: SearchDirection, sensitivity: CaseSensitivity): string; +``` + +很多时候,通过枚举代替布尔值以及整数表达的类型,可以减少使用者出错的可能性。 + +再者,通过将多个参数组成一个类型的形式,也可以降低参数传递出错的可能性。 + +* **规则14:避免顺序耦合** + +软件设计要尽可能保证高内聚,低耦合。这一点对于大型项目尤其重要。 + +耦合表达了软件模块之间的依赖程度,耦合过深常常意味着架构设计没有做好。 + +从一个软件静态结构或者分层架构图上可以看得出:如果模块之间的依赖关系比较少,上下层之间有明显的调用方向,则是比较好的设计。相反的,如果模块之间依赖关系非常复杂,或者上下层之间存在相反方向的调用链,则不是一个好的结构。 + +耦合有很多种,对于接口来说,顺序耦合就是要注意的。顺序耦合是指:类中方法需要按照某个特定的顺序调用才能工作。 + +类似下面这组命名的接口,很可能就是顺序耦合: + +```js +doSomethingFirst() +doSomethingSecond() +doSomethingThird() +``` + +这种设计的问题在于:对于使用者的要求太高了,很容易用错。 + +对于这类问题,通常可以使用`模板方法`设计模式来解决。 + +* **规则15:准确表达所有逻辑** + +有些接口是用来查询信息的,例如`getUserAccount()`。有些是进行操作的,会修改数据,例如`createUserAccount()`。 + +**永远不要在一个看起来是查询操作的接口里面去做修改数据的动作** ,因为这样使用者会非常的迷惑。 + +更通用的来讲, **接口的名称应当表达它所做的所有事情** ,不要有所隐瞒。只有这样,在阅读代码的时候,才能更容易理解代码到底做了什么。 + +如果接口包含了内容太多,很难通过几个单词描述清楚所做的所有事情该怎么办?对于这种情况,通常意味着需要将这个接口拆分成多个,因为这个接口不够“内聚”。 + +还有一些情况下,大家在做某件事的时候,会本能的以为别人也有同样的背景认识。但事实往往并不是这样。在编程时也是一样。 + +例如,对于一个描述编程语言的字段,可能会将其命名为`language`。这是因为大家默认认为已经在讨论编程语言了,但是`language`到底是编程语言还是国际化语言?是不是叫做`programmingLanuage`更好一些呢? + +当然,对于这一条还是要举一个反例,不要走到另外一个极端:如果类名或者namespace名称中已经明确带了一个前缀,在函数中就没必要再重复一遍了。毫无信息量的冗余是没有必要的。 + +* **规则16:注意封装:不暴露实现细节** + +对于面向对象编程来说,大家都知道“封装”的重要性。 + +这意味着,系统能力应当尽可能封装好实现细节,提供简洁的接口供调用者使用。 + +这就好像冰山,埋在水里的部分不管多庞大,露在水面上的部分要足够的小,足够的简洁。这才是友好的界面(Interface)。 + +封装的重要性,不仅仅是让开发者容易使用。其实也是使得开发者不容易出错。举一个生活中的例子:电子工程师将房间的电路线接好之后,只留一个开关按钮给到用户,这就是一个很好的封装。既避免了让用户理解复杂的电路结构(方便使用),也不会产生触电(出错)的风险。 + +* **规则17:单一职责** + +一个 API 应当尽量只做一件事情,尽可能保持单一核心的职责。例如: + +```js +// 不推荐 +view.fetchDataAndRender(url, templete); + +// 推荐 +let data = view.dataManager.fetchData(url); +view.render(data, templete); +``` + +这么做的目的是因为:开发者可以根据需要,按最小单位来使用接口。也可以根据多个单一职责的组合,来进一步封装自己需要的业务逻辑。 + +单一职责与注重封装性在一些情况下可能是矛盾的:如果提供了多个单一能力的接口,势必需要使用者关心多次的调用细节。 + +在这种情况下,需要从封装的“层次”来考虑决定,接口提供给开发者的,到底是哪个层级的能力?面向高层次使用者的一件事,对于低一个层次来说,可能就是多件事情。 + +### 可用性 + +* **规则18:保证可靠性** + +操作系统所提供的接口,必须是完全可靠的。 + +当然,可靠性不意味每次调用都是成功的。例如:在资源已经耗尽的情况下,应当给调用者合理的返回值或者异常。 + +每个接口必须针对所有的情况进行准确的定义,并在相应的情况下按照定义的行为完成工作。 + +没有按照预定行为返回结果,或者无故导致应用程序异常都属于不可靠行为。 + +* **规则19:功能完备** + +每个特性或者能力在规划时,需考虑到功能的完备性。不应当出现:在支持的范围内,某个流程中断,或者某个选项缺失的情况发生。API设计者应当做好足够的验证和推演。 + +即便操作系统的特性常常会伴随系统版本几年内才能完全迭代完备。但是,对于每一个特定版本,在其包含的范围内应当是闭合的,自洽的。这要求模块的设计者划分好版本迭代的边界。 + +* **规则20:注意权限和隐私保护** + +任何涉及到用户数据、用户隐私的接口都必须做好权限限制和数据保护。 + +对于权限控制,应当遵循以下几个原则: + +1. 完备性原则:一切穿透应用沙箱的行为都需考虑使用权限来管控。 +2. 最优粒度原则:一个权限只保护一类对象;一个接口只需申请最小粒度的权限。 +3. 清晰完整原则:权限定义中必须清晰说明保护对象、开放范围、敏感级别。 +4. 最小开放原则:一个权限仅对确有正当业务需求的应用开放,开放控制可通过权限来实现。 + +对于隐私包含,应当遵守以下几个原则: + +1. API调用的返回仅包含必要的内容, 避免携带额外信息。 +2. API调用不允许获取、手机用户个人数据, 除非通过用户权限管控、由用户授权同意。 +3. API涉及跨应用调用时,如涉及个人数据向被调用者的披露,由调用方在隐私声明中说明披露的数据类型、数据接收者和数据使用目的。 +4. API涉及到用户敏感数据(如电话、通讯录、媒体等)访问时,需要使用system picker的机制,禁止API通过申请敏感权限方式访问。 +5. API开放禁止捆绑与所开放能力不相关的功能。 + +* **规则21:考虑并发环境** + +保证所有的接口线程安全需要付出很大的代价(程序复杂度、性能影响),因此OpenHarmony API不必要求所有接口线程安全。只需根据需要选择即可。 + +但是,对于设计上就是为了并发环境使用的接口,必须做好相应的设计和说明。 + +当然,对于接口的内部实现中,应当尽可能避免出现线程不安全的问题发生。 + +* **规则22:注意资源管理闭合** + +在一些情况下,有些接口包含了动态资源的申请。此种情况下,这些接口也需要考虑到资源的释放。 + +如果申请的资源是直接返回开发者的,则需要提供相应的接口来释放资源。 + +如果资源没有直接返回给开发者,则接口自身要考虑到资源的生命周期,以及释放的时机。 + +对于有资源使用上限的情况,应当给开发者说明清楚。并且提供接口查询是否已经到达上限。 + +对于独占资源更加应当注意资源的释放时机。 + +* **规则23:考虑重试逻辑** + +对于可能失败的接口,应当考虑好给开发者相应的机制来重试。例如:对于相机这类独占的资源,一旦有某个进程使用了,其他进程就无法获取到。这种情况下,应当提供接口给开发者查询是否可用的接口。 + +在一些情况下,为了避免开发者反复尝试,还需要提供给开发者状态监听的机制。 + +并且,API要明确客户端调用失败后,能够发起重试的最大次数。 + +* **规则24:满足幂等要求** + +在数学中,幂等用函数表达式就是:`f(x) = f(f(x))`。例如求绝对值的函数,就是幂等的,``abs(x) = abs(abs(x))``。 + +计算机科学中,幂等表示一次和多次请求某一个资源应该具有同样的效果,或者说,多次请求所产生的影响与一次请求执行的影响效果相同。 + +具体到实际场景:文件打开,或者的硬件资源使用,打开一次和打开多次其效果应当是一样的,不应该有其他副作用。当然,关闭,也是类似。 + +* **规则25:考虑设备通用性** + +OpenHarmony是为多种不同类型设备设计的统一操作系统。 + +考虑到设备的复杂性,接口的设计应当要能面对多种设备的适用性。例如: + +* 对于用户界面的控件,要考虑到不同屏幕尺寸的大小。 +* 对于数据的存储,要考虑到不同大小的存储空间。 +* 对于用户输入事件,要考虑不同的用户交互方式:触摸、语音、按键等。 + +当然,有一些API只在某些特定设备上才有,例如: + +* 健康类传感器只在穿戴设备上有 +* 车控类接口只在车机设备上有 + +这种情况,请参考[《 SysCap使用指南》](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/syscap.md),来标定API的适用范围。 + +### 一致性 + +* **规则26:保证术语、概念的一致性** + +为了容易理解,接口在命名和说明上应当注意术语和概念的一致性,不应该出现“方言”。基于场景的业务模型抽象,形成OpenHarmony的连贯、一致、自恰的业务概念。 + + + +在这方面,应当遵循以下原则: + +1. 每个概念只应该有 **唯一** 的一个术语,同一个对象不应该有两个名称。 +2. 术语命名应该是 **贴切的** , **可解释** , **易理解** 。 +4. 术语的定义应当 **精准、无二义**。 +5. 对于业界通用术语, **不应该重新定义** ,应当遵循业内做法。 + +总体来说,要避免随意添加术语概念,尽可能以[《OpenHarmony 技术术语集》](https://gitee.com/openharmony/docs/blob/master/zh-cn/glossary.md)为准。如果需要,可以在术语集中新增词条。 + +* **规则27:保证设备间行为一致性** + +在默认情况下,同一个接口在不同的设备上应当保证行为是一致的。 + +对于因为设备形态而导致的行为不一致,应当给予开发者充分的说明,并且提供相应的检查机制。 + +* **规则28:注意版本演进一致性** + +在默认情况下,所有接口应当保证在系统版本演进的情况下,其行为是一致的。如果在新版本上出现了行为不兼容的变更,最低要求是需要对应用的目标版本做区分处理。 + +简单而言:接口的行为变更不能影响已经开发完的应用。 + +* **规则29:命名风格保持一致** + +在一些 API 设计的场景中,即使命名已经做到准确,但在有些情况下仍然可能碰到不一致的场景。比如,API 中经常会看到 picture 和 image、path 和 url 混用的情况,这两组词的意思非常接近,容易出现混乱。在指代同一内容时,应该使用相同的命名。 + +例如,下面这些接口都是为了获取媒体资源,但是命名风格不一致。 + +```js +declare function getMediaAsserts(): Array; +declare function getAudios(): Array; +declare function getVideos(): Array; +declare function getImages(): Array; +``` + +应该修改为: + +```js +function getMediaAsserts(): Array; +function getAudioAsserts(): Array; +function getVideoAsserts(): Array; +function getImageAsserts(): Array; +``` + +* **规则30:参数顺序保持一致** + +为了开发者便于理解,对于同一个命名空间或者是同一个模块来说,其成套的接口的参数顺序应当是一致的。 + +例如:`deviceId`和`missionId`在单个接口中的顺序没有强制要求,但是在同一模块接口中必须保持顺序一致。 + +```js +function getMissionInfo(deviceId: string, missionId: number): Promise; +function getMissionSnapShot(deviceId: string, missionId: number): Promise; + +// 正确 +function getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise; + +// 错误 +function getLowResolutionMissionSnapShot(missionId: number, deviceId: string): Promise; +``` + +* **规则31:同步/异步风格一致** + +异步接口应该可以通过入参和返回值判断出来,风格上要保持统一。例如: + +```javascript +// Callback形式 +function getDefaultDisplay(callback: AsyncCallback): void; +// Promise形式 +function getDefaultDisplay(): Promise; +``` + +如果同时提供了同步和异步接口,可以在同步函数名后加上后缀`Sync`加以区别,例如: + +```js +function getDefaultDisplaySync(): Display; +``` + +如果只提供了同步接口,且返回值不是`void`,可以不用加后缀,例如: + +```js +function registerMissionListener(listener: MissionListener): number; +``` + +### 兼容性 + +* **规则32:注意新旧系统版本的兼容性** + +API 变更的成本非常高,在设计之初就应该做尽可能完备的考虑。但是API变更始终是系统发展过程中不可避免的。 + +API 变更要保证向后兼容原则,API 变更后,废弃的 API 要在源码和文档中显著标识 `deprecated`,并引导开发者使用变更后 API 。 + +废弃的 API 要保证其功能仍然可用,至少保留5个版本。5个版本后,在充分告知开发者,并给与充分的时间供开发者修改后,可予以删除。 + +* **规则33:二进制向后兼容性** + +二进制兼容,指版本演进后,开发者已有程序不用重新编译可正常链接、运行。这也意味着,二进制兼容是保证在版本升级的情况下,对象实例的内存布局不会发生变化。 + +以C++接口为例,常见破坏二进制兼容的API变更包括: + +1. 任何API元素删除 +2. 添加新的虚函数 +3. 改变类的继承 +4. 改变虚函数声明时的顺序 +5. 添加新的非静态成员变量 +6. 改变非静态成员变量的声明顺序 + +由于C接口相比C++接口在二进制兼容性上有天然的优势,所以OpenHarmony的Native API推荐使用C接口定义。 + +### API资料 + +API的很多信息需要通过文档和资料进行说明,因此,配套的这些内容也应当做好质量管理。 + +* **规则34:模块、命名空间、类、函数需要包含基础说明** + +每个模块、命名空间、类和函数都需要包含基本的说明。 + +对于关键模块、复杂模块需要有详细的说明。 + +说明采用英文的形式。 + +* **规则35:使用场景说明清晰** + +所有接口应当提供示例代码,覆盖常见使用场景。 + +复杂接口需要详细说明使用场景。可以在接口的说明上增加详细教程的链接。 + +* **规则36:接口说明准确** + +接口说明的文字不应该出现拼写错误或者错别字。 + +所有代码示例应当保证能够正常运行。如果接口在不同版本上存在行为不一致,则需要针对每种情况做详细说明。 + +对于废弃接口,需做明确标记,并做好替代接口说明。 + +* **规则37:参数说明准确** + +对于API的每一个参数,都应该说明清楚。例如: + +* 如果是非简单类型,则需说明清楚是否允许参数为空 +* 如果是枚举类型,则需针对每个枚举值说明清楚使用场景 +* 如果是可选参数,则需说明清楚什么时候该传参,什么时候可省略 + +**规则38:返回值/异常定义准确** + +如果接口有返回值/异常,需要在接口说明中描述完整。例如: + +```js +/** + * Sync function of rename. + * @param {string} path - path. + * @returns {void} rmdir success. + * @throws {BusinessError} 401 - if type of path is not string. + * @throws {BusinessError} 201 - if permission denied. + * @syscap SystemCapability.FileManagement.File.FileIO + * @since 7 + */ +declare function rmdirSync(path: string): void; +``` + +* **规则39:元信息完备** + +接口的方法说明上应当包含基本的元信息,例如:`@syscap`、`@since`等。 + +元信息描述了API自身的基本信息。工具和SDK会利用这个信息进行相应的处理,例如:针对已经废弃的接口会给出警告提示。 + +* **规则40:风格一致** + +API的说明资料,在风格和样式上应当保持一致。例如,文字的加粗,资料图片的配色等。 + +### 组织方式 + +* **规则41:分层合理** + +操作系统通常是以分层的模型来进行架构的。这意味着每一层要解决不同层次上的问题。 + +因此,接口的设计也要注意相应的层次。 + +可以使用建筑行业来进行类比:所有的建筑都会包含墙体和房间的门。墙体是有砖块构成的,门是有木料构成的。在这种情况下,抽象可能会分为下面几层: + +* 第一层是基本都原材料,包括水泥、沙子、木材等 +* 第二层是用原材料构建出来的建筑元素,例如:门、窗户、墙体等 +* 第三层是房间的种类,例如:卧室、卫生间、客厅等 +* 最后,最上面一层是各种不同用途的建筑。例如:酒店、公寓等 + +这里每一层所要考虑的概念和要处理的问题都是不一样的,请仔细思考你提供的API是在哪一个层次上。 + +* **规则42:模块划分合理** + +大家不仅要关注水平层面的分层,也应该关注垂直层面的划分。因此,模块的组织也同样重要。OpenHarmony的接口是以命名空间的形式组织的。一个命名空间通常对应了一个模块。 + +从子系统的角度,一个较小的子系统应该尽可能将接口放在同一个命名空间中。较大的子系统,可以提供多个命名空间。 + +* **规则43:应用描述文件也是接口的一部分** + +接口的英文是Interface,这个词还有界面的意思。操作系统提供给开发者的接口并不仅仅是编程接口。任何公开给开发者的机制,都是API的一部分。 + +这其中,最明显的就是应用描述文件,这些文件也需要按照接口规范一样的规则来管理。 + +### 质量属性 + +* **规则44:性能满足要求** + +操作系统所提供的接口所有上层应用都可能会使用到,因此,其实现的性能应当是能够满足实际要求的。 + +下面是一些举例: + +1. 应及时响应,避免调用者等待;如果API调用执行时间过长应设计为异步方式。 +2. 接口存在大量数据传输时,应考虑使用共享内存、消息队列等。 +3. 尽可能减少新增进程实体。 +4. 对使用资源的API调用需要能及时释放资源,异常场景具备容错机制,保障资源及时释放。 + +* **规则45:功耗设计合理** + +OpenHarmony 操作系统在设计之初就需要面向多种不同类型的设备,这些设备中绝大多数是无源设备。因此,功耗的考虑是毋庸置疑的。 + +每个功能/机制在实现上应当把功耗的合理性作为最基本的要求。除此之外,对于高功耗的接口应当在说明中给开发者充足的解释,并且对于使用方式给与足够的指导。 + +同时,在使用上要避免开发者错误的使用。例如,在设备锁屏之后,或者应用切换到后台之后,就应当停止高功耗的行为。 + +另外,还应当注意在版本演进过程中,功耗不出现劣化。 + +* **规则46:需要保证可测试性** + +完备的自动化测试用例,可以带来很多好处: + +1. 开发过程中,提前快速发现问题,提高接口质量。 +2. 版本迭代时,保证代码修改不影响功能,提高代码修改的信心。 +3. 确保接口向后兼容性。 + +所以,对于一个OpenHarmony API,都要求做到以下几点: + +1. 新增API必须同步交付API自动化测试用例,用例100%覆盖API接口。 +2. 用例场景单一,单条用例覆盖接口单个功能场景,简化单条用例代码逻辑。 +3. 用例执行高效,每条用例执行时间控制在毫秒级。 +4. 用例执行全自动化:接口用例需要达成100%自动化。 +5. 用例有效性:用户要求必须存在断言,且不能仅是检查是否抛出异常,需要有功能逻辑的断言。 + + + +* **规则47:考虑环境适应性** + +考虑到用户的个性化,操作系统通常会提供一些环境自定义的能力,例如:语言国际化、浅色/深色主题、字体大小等。 + +对于这方面相关的接口,在开发者没有传递指定参数的情况下,应当能够更加当前所属的环境,自适应的返回相应环境下的结果。 + +## 发布后评价说明 + +尽管在API发布前已经做了多方面规则约束,但总可能还有一些问题在开发者使用之后才能发现。 + +即便是这样,但并不意味着在设计API之初不需要考虑这些问题。 + +相反的,大家应当时刻避免发布后问题的发生。 + +如果在接口发布后,发现了下面几条规则问题的发生,则该模块的接口质量是比较差的。 + +### 稳定性 + +* **规则48:接口废弃率/变更率越低越好** + +对于接口来说,稳定是其最重要的属性。 + +这是因为接口的废弃和行为变更将极大的影响开发者的维护效率。考虑上多种设备类型、多个系统版本,这个问题会变得更加复杂。 + +设计出能保证长期稳定,持续兼容的接口是每个API设计者应当追求的目标。 + +接口的废弃率/变更率与接口的质量在一定程度上成反比。 + +### 安全性 + +* **规则49:避免接口被滥用** + +所有接口在设计上,应当考虑到不能被过度滥用。滥用既可能是数量上的滥用,也可能是范围上的滥用。 + +例如:对于用户公共数据(相册、联系人等)的访问,对于长时间后台运行的能力,都可能被滥用。 + +对于数量滥用的防止,可以考虑“仅一次授权”这样的机制。 + +在实现上,可以根据调用者的身份进行相应的限制。 + +当然,无论是哪种限制,都应该在接口说明中说明清楚。并且在检测到过度滥用的情况下,有相应的返回值告知调用者。 + +* **规则50:避免接口被利用** + +被滥用是指接口的使用超出了原先预期的限制。而被利用是指:接口可以被用来造成负面影响,例如攻击系统。 + +无论开发者以何种方式使用OpenHarmony提供的接口,如果某个接口,或某些接口组合调用导致系统出现了问题,那么就一定接口本身存在问题。 + +特别的,如果某些接口(无论在何种情况下)一旦调用就可以使用系统崩溃,或者进入不能工作的场景,或者能够窃取用户数据,这是绝对不允许的。这就要求API的设计者从API被调用的所有可能都场景上进行考虑,避免一些极端情况的发生。 + +### 可维护性 + +* **规则51:能承载业务能力演进** + +考虑到操作系统的一些较大特性,需要经过数年才能打磨完成。因此接口在设计上应当考虑今后的可扩展性。 + +随着能力的演进,如果出现了在新版本上新起了一组新的接口,而废弃了原先旧的接口,那么就是接口的设计上存在问题。这是应当避免的。 + +* **规则52:功能扩展后不影响原先行为** + +随着OpenHarmony 操作系统版本的演进,一些接口新增了参数,或者一些参数新增了新的选项是很常见的一种行为。 + +但是,在这种情况下,一定要考虑清楚对于过往已存在行为的一致性。不应当因为新的场景的引入,而破坏了原先存在的行为。 + +这里需要遵循的原则是:如果在新版本上行为要发生变化,只允许针对目标版本是新版本的应用生效。对于目标版本是旧版本的应用应当继续保持原先的行为。 + +* **规则53:文档和资料应当配套更新** + +当大家在更新接口实现的时候,一定要记得更新接口的说明。从兼容性的角度来看,不能修改原先存在的行为。通常应当提供新的接口来完成新的功能。 + +但在下面的情况下,可以考虑修改既有接口的行为: + +1. 缺陷的修复。 +2. 性能/功耗的改进。 +3. 为接口拓展新的特性或场景,但不影响原有特性或场景逻辑。 + +第1、2种情况,通常在Release Note里面说明;第3种情况就需要在接口说明上表述清楚。 + +### 不可替代性 + +* **规则54:保证API之间正交** + +正交(Orthogonality),意味着多个接口之间不应该出现重合的功能。 + +例如:一个接口提供了创建用户账号的能力。另外一个接口包含了创建用户并登录的功能。如果是这样,就应该把第二个接口拆开,只保留单独登录的功能。 + +如果将接口的能力画成一个个图形,那么这些图形之间不应该出现重叠交错的想象。对于同一个层级的接口,不应该出现某个接口提供了1、2、3功能,另外一个接口又提供了2、3、4功能这种情况发生。 + +当然,为了便于调用,允许将一些接口组合成一个更高阶的接口。这通常是抽象层次的不一样,并非是同一个层次的重叠。 + +### 开发者反馈 + +* **规则55:关注开发者反馈** + +尽管API在正式发布之前,会经过试用阶段,但考虑到试用时间和试用范围是有限的,实际上无法保证能避免所有问题。 + +因此,在接口正式发布之后,也应该继续关注开发者的反馈。 + +开发者反馈可能分为以下几种情况: + +* 希望提供更多API来满足目前不能实现的功能,这种情况可以将需求导入到下个版本的规划中。 +* 反馈API的行为与文档描述不一致,这通常是缺陷,应当尽快修复。如果是文档的问题,也应当尽快修改。 +* 反馈接口设计不合理,可能是命名或者参数设置存在问题,这种情况就需要考虑API废弃同时用新API代替。 + +在一些情况下,可能要变更已经发布的API行为。这种情况下,应当要注意:行为变化只能发生在新开发的应用上,对于已经发布的应用,不能产生行为变化。API提供者可以根据应用的目标API版本来进行判断。 + +在最坏的情况下,需要将既存API废弃,提供新的API代替。 diff --git a/zh-cn/device-dev/Readme-CN.md b/zh-cn/device-dev/Readme-CN.md index 4d91198caa68f0429f228338a0943d074ae4b1b3..146d5484f274750a806173175d7d628cb7c68cb6 100644 --- a/zh-cn/device-dev/Readme-CN.md +++ b/zh-cn/device-dev/Readme-CN.md @@ -25,7 +25,8 @@ - 小型系统芯片移植案例 - [小型设备STM32MP1芯片移植案例](porting/porting-stm32mp15xx-on-smallsystem.md) - 标准系统芯片移植案例 - - [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md) + - [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md) + - [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md) - 子系统开发 - 内核 - [轻量系统内核](kernel/kernel-mini-overview.md) diff --git a/zh-cn/device-dev/device-dev-guide.md b/zh-cn/device-dev/device-dev-guide.md index 29273529556c779558fa807f53c64d14704ced30..597e90485906b086f9b319758a50eebf7bf71edf 100644 --- a/zh-cn/device-dev/device-dev-guide.md +++ b/zh-cn/device-dev/device-dev-guide.md @@ -51,6 +51,6 @@ OpenHarmony也提供了一系列可选的系统组件,方便设备开发者按 | 快速入门 | 快速熟悉OpenHarmony环境搭建、编译、烧录、调测、运行 | - [快速入门](quick-start/Readme-CN.md)| | 基础能力使用 | 使用OpenHarmony提供的基础能力 | - [内核开发指南](kernel/kernel-standard-overview.md)
- [驱动开发指南](driver/driver-hdf-overview.md)
- [子系统开发指南](subsystems/subsys-build-all.md)
- [安全指南](security/security-guidelines-overall.md)
- [隐私保护](security/security-privacy-protection.md) | | 进阶开发 | 结合系统能力开发智能设备 | - [时钟应用开发指导](guide/device-clock-guide.md)
- [平台驱动开发示例](guide/device-driver-demo.md)
- [外设驱动开发示例](guide/device-outerdriver-demo.md) | -| 移植适配 | - 针对特定芯片做移植适配
- 快速移植OpenHarmony Linux内核的方法| - [标准系统芯片移植指导](porting/standard-system-porting-guide.md)
- [一种快速移植OpenHarmony Linux内核的方法](porting/porting-linux-kernel.md)
- [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md)| +| 移植适配 | - 针对特定芯片做移植适配
- 快速移植OpenHarmony Linux内核的方法| - [标准系统芯片移植指导](porting/standard-system-porting-guide.md)
- [一种快速移植OpenHarmony Linux内核的方法](porting/porting-linux-kernel.md)
- [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md)
- [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md)| | 贡献组件 | 为OpenHarmony贡献功能组件 | - [HPM Part 介绍](hpm-part/hpm-part-about.md)
- [HPM Part 开发指导](hpm-part/hpm-part-development.md)
- [HPM Part 参考](hpm-part/hpm-part-reference.md) | | 参考 | 为开发者提供常见的问题解答和HDI接口参考 | - [常见问题](faqs/faqs-overview.md)
- [HDI接口参考](reference/hdi-apis/Readme-CN.md) | diff --git a/zh-cn/device-dev/device-test/Readme-CN.md b/zh-cn/device-dev/device-test/Readme-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..cb28b27227a24f2fec3d7fe7422ed3b2f354e8af --- /dev/null +++ b/zh-cn/device-dev/device-test/Readme-CN.md @@ -0,0 +1,5 @@ +# 设备测试 + +- [developer_test开发者自测试执行框架使用指导](developer_test.md) +- [xdevice测试调度框架使用指导](xdevice.md) +- [XTS用例开发指导](xts.md) diff --git a/zh-cn/device-dev/device-test/developer_test.md b/zh-cn/device-dev/device-test/developer_test.md index 05f860d7e9dc7420a75d0f9daa8fb378979fe9ee..e7bbd639df1de2da2b155e6ac147ce3e55d0125f 100644 --- a/zh-cn/device-dev/device-test/developer_test.md +++ b/zh-cn/device-dev/device-test/developer_test.md @@ -20,10 +20,104 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ## 环境准备 -开发自测试框架依赖于python运行环境,python版本为3.8.X,在使用测试框架之前可参阅以下方式进行配置。 +开发自测试框架依赖于python运行环境,python版本为3.7.5及以上版本,在使用测试框架之前可参阅以下方式进行配置。 - - [环境配置](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-testguide-test.md#%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE) - - [源码获取](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md) +源码获取可[参考](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md)。 + +### 自测试框架基础环境依赖 + +| 环境依赖 | 版本型号 | 详细说明 | +| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 操作系统 | Ubuntu18.04及以上 | 代码编译环境 | +| Linux系统扩展组件 | libreadline-dev | 命令行读取插件 | +| python | 3.7.5版本及以上 | 测试框架语言 | +| python插件 | pyserial 3.3及以上、paramiko2.7.1及以上、setuptools40.8.0及以上、rsa4.0及以上 | pserial:支持python的串口通信;paramiko:支持python使用SSH协议;setuptools:支持python方便创建和分发python包;rsa:支持python rsa加密 | +| NFS Server | haneWIN NFS Server 1.2.50及以上或者 NFS v4及以上 | 支持设备通过串口连接,使用轻量、小型设备 | +| HDC | 1.1.0 | 支持设备通过HDC连接 | + + + +1. 安装Linux扩展组件readline,安装命令如下: + + ```bash + sudo apt-get install libreadline-dev + ``` + 安装成功提示如下: + ``` + Reading package lists... Done + Building dependency tree + Reading state information... Done + libreadline-dev is already the newest version (7.0-3). + 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. + ``` + +2. 安装setuptools插件,安装命令如下: + ```bash + pip3 install setuptools + ``` + 安装成功提示如下: + ``` + Requirement already satisfied: setuptools in d:\programs\python37\lib\site-packages (41.2.0) + ``` + +3. 安装paramiko插件,安装命令如下: + ```bash + pip3 install paramiko + ``` + 安装成功提示如下: + ``` + Installing collected packages: pycparser, cffi, pynacl, bcrypt, cryptography, paramiko + Successfully installed bcrypt-3.2.0 cffi-1.14.4 cryptography-3.3.1 paramiko-2.7.2 pycparser-2.20 pynacl-1.4.0 + ``` + +4. 安装python的rsa插件,安装命令如下: + ```bash + pip3 install rsa + ``` + 安装成功提示如下: + ``` + Installing collected packages: pyasn1, rsa + Successfully installed pyasn1-0.4.8 rsa-4.7 + ``` + +5. 安装串口插件pyserial,安装命令如下: + ```bash + pip3 install pyserial + ``` + 安装成功提示如下: + ``` + Requirement already satisfied: pyserial in d:\programs\python37\lib\site-packages\pyserial-3.4-py3.7.egg (3.4) + ``` + +6. 如果设备仅支持串口输出测试结果,则需要安装NFS Server + + > 针对小型或轻量设备 + + - Windows环境下安装,安装haneWIN NFS Server1.2.50软件包。 + - Linux环境下安装,安装命令如下: + ```bash + sudo apt install nfs-kernel-server + ``` + 安装成功提示如下: + ``` + Reading package lists... Done + Building dependency tree + Reading state information... Done + nfs-kernel-server is already the newest version (1:1.3.4-2.1ubuntu5.3). + 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. + ``` + +7. 如果设备支持HDC连接,则需要安装HDC工具,安装流程请参考[HDC-OpenHarmony设备连接器](https://gitee.com/openharmony/developtools_hdc_standard/blob/master/README_zh.md)。 + + +### 环境依赖检查 + +| 检查项 | 操作 | 满足环境 | +| -------------------------------------------------- | --------------------------------------------------- | ------------------------- | +| 检查python安装成功 | 命令行窗口执行命令:python --version | 版本不小于3.7.5即可 | +| 检查python扩展插件安装成功 | 打开test/developertest目录,执行start.bat或start.sh | 可进入提示符“>>>”界面即可 | +| 检查NFS Server启动状态(被测设备仅支持串口时检测) | 通过串口登录开发板,执行mount命令挂载NFS | 可正常挂载文件目录即可 | +| 检查HDC安装成功 | 命令行窗口执行命令:hdc_std -v | 版本不小于1.1.0即可 | ## 编写测试用例 @@ -41,7 +135,7 @@ calculator_sub_test.cpp ``` 用例示例 -``` +```c++ /* * Copyright (c) 2021 XXXX Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -128,7 +222,7 @@ HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) 2.引用测试框架头文件和命名空间 -``` +```c++ #include using namespace testing::ext; @@ -136,13 +230,13 @@ using namespace testing::ext; 3.添加被测试类的头文件 -``` +```c++ #include "calculator.h" ``` 4.定义测试套(测试类) -``` +```c++ class CalculatorSubTest : public testing::Test { public: static void SetUpTestCase(void); @@ -169,13 +263,13 @@ void CalculatorSubTest::SetUp(void) void CalculatorSubTest::TearDown(void) { // input testcase teardown step,teardown invoked after each testcases -} +}== ``` > **注意:** 在定义测试套时,测试套名称应与编译目标保持一致,采用大驼峰风格。 5.测试用例实现,包含用例注释和逻辑实现 -``` +```c++ /** * @tc.name: integer_sub_001 * @tc.desc: Verify the sub function. @@ -242,7 +336,7 @@ AppInfoTest.js - 用例示例 -``` +```js /* * Copyright (C) 2021 XXXX Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -316,13 +410,13 @@ describe("AppInfoTest", function () { */ ``` 2. 导入被测api和jsunit测试库 - ``` + ```js import app from '@system.app' import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' ``` 3. 定义测试套(测试类) - ``` + ```js describe("AppInfoTest", function () { beforeAll(function() { // input testsuit setup step,setup invoked before all testcases @@ -345,7 +439,7 @@ describe("AppInfoTest", function () { }) ``` 4. 测试用例实现 - ``` + ```JS /* * @tc.name:appInfoTest001 * @tc.desc:verify app info is not null @@ -360,7 +454,7 @@ describe("AppInfoTest", function () { expect(info != null).assertEqual(true) }) ``` - > **注意:** @tc.require: 格式必须以AR/SR或issue开头: 如:issueI56WJ7 + > **注意:** @tc.require: 格式必须以issue开头: 如:issueI56WJ7 **Fuzz测试** @@ -546,7 +640,7 @@ ohos_js_unittest("GetAppInfoJsTest") { ``` config.json为hap编译所需配置文件,需要开发者根据被测sdk版本配置“target”项,其余项可默认,具体如下所示: -``` +```json { "app": { "bundleName": "com.example.myapplication", @@ -659,7 +753,7 @@ group("unittest") { 2.在resource目录下对应的模块目录中创建一个ohos_test.xml文件,文件内容格式如下: -``` +```xml @@ -689,7 +783,7 @@ ohos_unittest("CalculatorSubTest") { 在执行测试用例之前,针对用例使用设备的不同,需要对相应配置进行修改,修改完成即可执行测试用例。 #### user_config.xml配置 -``` +```xml @@ -788,7 +882,7 @@ ohos_unittest("CalculatorSubTest") { >**说明:** 将测试框架及测试用例从Linux环境移植到Windows环境,以便后续执行。 3. 修改user_config.xml - ``` + ```xml false diff --git a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001154351160.jpg b/zh-cn/device-dev/device-test/figures/zh-cn_image_0000001154351160.jpg similarity index 100% rename from zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001154351160.jpg rename to zh-cn/device-dev/device-test/figures/zh-cn_image_0000001154351160.jpg diff --git a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001200230833.gif b/zh-cn/device-dev/device-test/figures/zh-cn_image_0000001200230833.gif similarity index 100% rename from zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001200230833.gif rename to zh-cn/device-dev/device-test/figures/zh-cn_image_0000001200230833.gif diff --git a/zh-cn/device-dev/subsystems/subsys-xts-guide.md b/zh-cn/device-dev/device-test/xts.md similarity index 99% rename from zh-cn/device-dev/subsystems/subsys-xts-guide.md rename to zh-cn/device-dev/device-test/xts.md index 36f1f7ab87265f684f24487de5b107332ef05c15..dbe852a1830d6def4f1630d31d12f6689a568b79 100644 --- a/zh-cn/device-dev/subsystems/subsys-xts-guide.md +++ b/zh-cn/device-dev/device-test/xts.md @@ -28,7 +28,7 @@ XTS子系统当前包括acts与tools软件包: ## 目录 - + ``` /test/xts ├── acts # 测试代码存放目录 @@ -102,7 +102,7 @@ XTS子系统当前包括acts与tools软件包: 当前使用的测试框架是hctest,hctest测试框架支持使用C语言编写测试用例,是在开源测试框架unity的基础上进行增强和适配。 1. 用例目录规范:测试用例存储到test/xts/acts仓中。 - + ``` ├── acts │ └──subsystem_lite @@ -116,14 +116,14 @@ XTS子系统当前包括acts与tools软件包: 2. src目录下用例编写样例。 1.引用测试框架 - + ``` #include "hctest.h" ``` 2. 使用宏定义LITE_TEST_SUIT定义子系统、模块、测试套件名称 - + ``` /** * @brief register a test suite named "IntTestSuite" @@ -159,7 +159,7 @@ XTS子系统当前包括acts与tools软件包: 3. 测试模块的配置文件(BUILD.gn)样例: 在每个测试模块目录下新建BUILD.gn编译文件,用于指定编译后静态库的名称、依赖的头文件、依赖的库等;具体写法如下: - + ``` import("//test/xts/tools/lite/build/suite_lite.gni") hctest_suite("ActsDemoTest") { @@ -175,7 +175,7 @@ XTS子系统当前包括acts与tools软件包: 4. acts下BUILD.gn增加编译选项。 需要将测试模块加入到acts目录下的编译脚本中,编译脚本路径:test/xts/acts/build_lite/BUILD.gn。 - + ``` lite_component("acts") { ... @@ -220,7 +220,7 @@ XTS子系统当前包括acts与tools软件包: 当前使用的测试框架是hcpptest,hcpptest测试框架是在开源的googletest测试框架的基础上进行的增强和适配。 1. 规范用例目录:测试用例存储到test/xts/acts仓中。 - + ``` ├── acts │ └──subsystem_lite @@ -236,14 +236,14 @@ XTS子系统当前包括acts与tools软件包: 需要引用gtest.h 如:\#include "gtest/gtest.h" - + ``` #include "gtest/gtest.h" ``` 2. 定义Setup与TearDown - + ``` using namespace std; using namespace testing::ext; @@ -271,10 +271,10 @@ XTS子系统当前包括acts与tools软件包: 普通测试用例的定义:HWTEST(测试套名称, 测试用例名称, 用例标注)。 包含SetUp和TearDown的测试用例的定义 :HWTEST_F(测试套名称, 测试用例名称,用例标注)。 - + 宏定义包括三个参数:测试套件名称,测试用例名称,用例属性(测试类型、用例粒度、用例级别)。 - + ``` HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) { // do something @@ -285,7 +285,7 @@ XTS子系统当前包括acts与tools软件包: 每个测试模块目录下新建BUILD.gn编译文件,用于指定编译后可执行文件的名称、依赖的头文件、依赖的库等;具体写法如下。每个测试模块将独立编译成.bin可执行文件, 该文件可直接push到单板上进行测试。 举例: - + ``` import("//test/xts/tools/lite/build/suite_lite.gni") hcpptest_suite("ActsDemoTest") { @@ -309,7 +309,7 @@ XTS子系统当前包括acts与tools软件包: 4. acts目录下增加编译选项(BUILD.gn)样例: 将测试模块加入到acts目录下的编译脚本中,编译脚本为:test/xts/acts/build_lite/BUILD.gn。 - + ``` lite_component("acts") { ... @@ -346,7 +346,7 @@ XTS子系统当前包括acts与tools软件包: 格式:mount [nfs服务器IP]:[/nfs共享目录] [/开发板目录] nfs 举例: - + ``` mount 192.168.1.10:/nfs /nfs nfs ``` @@ -377,7 +377,7 @@ XTS子系统当前包括acts与tools软件包: 用例编写语法采用 jasmine 的标准语法,格式支持ES6格式。 1. 规范用例目录:测试用例存储到entry/src/main/js/test目录。 - + ``` ├── BUILD.gn │ └──entry @@ -394,7 +394,7 @@ XTS子系统当前包括acts与tools软件包: ``` 2. index.js示例 - + ``` // 拉起js测试框架,加载测试用例 import {Core, ExpectExtend} from 'deccjsunit/index' @@ -425,7 +425,7 @@ XTS子系统当前包括acts与tools软件包: ``` 3. 单元测试用例示例 - + ``` // Example1: 使用HJSUnit进行单元测试 describe('appInfoTest', function () { @@ -447,7 +447,7 @@ hap包编译请参考[标准系统js应用开发指导](https://developer.harmon 1. 全量编译 **命令**: - + ``` ./build.sh suite=acts system_size=standard ``` @@ -464,7 +464,7 @@ hap包编译请参考[标准系统js应用开发指导](https://developer.harmon Windows工作台下安装python3.7及以上版本,确保工作台和测试设备正常连接。 **测试执行目录**(对应编译生成的out/release/suites/acts目录) - + ``` ├── testcase # 测试套文件存放目录 │ └──xxx.hap # 测试套可执行hap文件 @@ -480,7 +480,7 @@ Windows工作台下安装python3.7及以上版本,确保工作台和测试设 2. 界面启动后,输入用例执行指令。 - 全量执行 - + ``` run acts ``` @@ -490,7 +490,7 @@ Windows工作台下安装python3.7及以上版本,确保工作台和测试设 ![zh-cn_image_0000001200230833](figures/zh-cn_image_0000001200230833.gif) - 模块执行(具体模块可以查看\acts\testcases\) - + ``` run –l ActsSamgrTest ``` diff --git a/zh-cn/device-dev/driver/driver-peripherals-camera-des.md b/zh-cn/device-dev/driver/driver-peripherals-camera-des.md index 94704359fc2492e9ddc456669e3827b4ca0f3d19..8fddafeda91cdbea167912c57ad3a991b1d6b980 100755 --- a/zh-cn/device-dev/driver/driver-peripherals-camera-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-camera-des.md @@ -18,9 +18,9 @@ Camera模块主要包含服务、设备的初始化,数据通路的搭建,         ![](figures/Camera模块驱动模型.png) -1. 系统启动时创建camera_host进程。进程创建后,首先枚举底层设备,创建(也可以通过配置表创建)管理设备树的DeviceManager类及其内部各个底层设备的对象,创建对应的CameraHost类实例并且将其注册到UHDF服务中,方便相机服务层通过UHDF服务获取底层CameraDeviceHost的服务,从而操作硬件设备。 +1. 系统启动时创建camera_host进程。进程创建后,首先枚举底层设备,创建(也可以通过配置表创建)管理设备树的DeviceManager类及其内部各个底层设备的对象,创建对应的CameraHost类实例并且将其注册到UHDF(用户态HDF驱动框架)服务中,方便相机服务层通过UHDF服务获取底层CameraDeviceHost的服务,从而操作硬件设备。 -2. Service通过CameraDeviceHost服务获取CameraHost实例,CameraHost可以获取底层的Camera能力,打开手电筒、调用Open接口打开Camera创建连接、创建DeviceManager(负责底层硬件模块上电)、创建CameraDevice(向上提供设备控制接口)。创建CameraDevice时会实例化PipelineCore的各个子模块,其中StreamPipelineCore负责创建Pipeline,MetaQueueManager负责上报metaData。 +2. Service通过CameraDeviceHost服务获取CameraHost实例,CameraHost可以获取底层的Camera能力,开启闪光灯、调用Open接口打开Camera创建连接、创建DeviceManager(负责底层硬件模块上电)、创建CameraDevice(向上提供设备控制接口)。创建CameraDevice时会实例化PipelineCore的各个子模块,其中StreamPipelineCore负责创建Pipeline,MetaQueueManager负责上报metaData。 3. Service通过CameraDevice模块配置流、创建Stream类。StreamPipelineStrategy模块通过上层下发的模式和查询配置表创建对应流的Node连接方式,StreamPipelineBuilder模块创建Node实例并且连接返回该Pipeline给StreamPipelineDispatcher。StreamPipelineDispatcher提供统一的Pipeline调用管理。 @@ -43,86 +43,88 @@ Camera模块主要包含服务、设备的初始化,数据通路的搭建, ### 场景介绍
-Camera模块主要用以相机预览、拍照、视频流等场景下对相机操作封装,使开发者更易操作相机硬件,提高开发效率。 +Camera模块主要针对相机预览、拍照、视频流等场景,对这些场景下的相机操作进行封装,使开发者更易操作相机硬件,提高开发效率。 ### 接口说明 +注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/camera/v1_0/)。 - icamera_device.h | 功能描述 | 接口名称 | | ---------------------------- | ------------------------------------------------------------ | - | 获取流控制器 | CamRetCode GetStreamOperator(
const OHOS::sptr &callback,
OHOS::sptr &streamOperator) | - | 更新设备控制参数 | CamRetCode UpdateSettings(const std::shared_ptr &settings) | - | 设置Result回调模式和回调函数 | CamRetCode SetResultMode(const ResultCallbackMode &mode) | - | 获取使能的ResultMeta | CamRetCode GetEnabledResults(std::vector &results) | - | 使能具体的ResultMeta | CamRetCode EnableResult(const std::vector &results) | - | 禁止具体的ResultMeta | CamRetCode DisableResult(const std::vector &results) | - | 关闭Camera设备 | void Close() | + | 获取流控制器 | int32_t GetStreamOperator(const sptr& callbackObj,
sptr& streamOperator) | + | 更新设备控制参数 | int32_t UpdateSettings(const std::vector& settings) | + | 设置Result回调模式和回调函数 | int32_t SetResultMode(ResultCallbackMode mode) | + | 获取使能的ResultMeta | int32_t GetEnabledResults(std::vector& results) | + | 使能具体的ResultMeta | int32_t EnableResult(const std::vector& results) | + | 禁止具体的ResultMeta | int32_t DisableResult(const std::vector& results) | + | 关闭Camera设备 | int32_t Close() | - icamera_device_callback.h | 功能描述 | 接口名称 | | ---------------------------------------------------------- | ------------------------------------------------------------ | - | 设备发生错误时调用,由调用者实现,用于返回错误信息给调用者 | void OnError(ErrorType type, int32_t errorCode) | - | 上报camera设备相关的metadata的回调 | void OnResult(uint64_t timestamp, const std::shared_ptr &result) | + | 设备发生错误时调用,由调用者实现,用于返回错误信息给调用者 | int32_t OnError(ErrorType type, int32_t errorCode) | + | 上报camera设备相关的metadata的回调 | int32_t OnResult(uint64_t timestamp, const std::vector& result) | - icamera_host.h | 功能描述 | 接口名称 | | ------------------------------ | ------------------------------------------------------------ | - | 设置ICameraHost回调接口 | CamRetCode SetCallback(const OHOS::sptr &callback) | - | 获取当前可用的Camera设备ID列表 | CamRetCode GetCameraIds(std::vector\ &cameraIds) | - | 获取Camera设备能力集合 | CamRetCode GetCameraAbility(const std::string &cameraId, std::shared_ptr &ability) | - | 打开Camera设备 | CamRetCode OpenCamera(const std::string &cameraId,
const OHOS::sptr &callback,
OHOS::sptr &device) | - | 打开或关闭闪光灯 | CamRetCode SetFlashlight(const std::string &cameraId, bool &isEnable) | + | 设置ICameraHost回调接口 | int32_t SetCallback(const sptr& callbackObj) | + | 获取当前可用的Camera设备ID列表 | int32_t GetCameraIds(std::vector& cameraIds) | + | 获取Camera设备能力集合 | int32_t GetCameraAbility(const std::string& cameraId, std::vector& cameraAbility) | + | 打开Camera设备 | int32_t OpenCamera(const std::string& cameraId, const sptr& callbackObj,
sptr& device) | + | 打开或关闭闪光灯 | int32_t SetFlashlight(const std::string& cameraId, bool isEnable) | - icamera_host_callback.h | 功能描述 | 接口名称 | | ---------------------- | ------------------------------------------------------------ | - | Camera设备状态变化上报 | void OnCameraStatus(const std::string &cameraId, CameraStatus status) | - | 闪光灯状态变化回调 | void OnFlashlightStatus(const std::string &cameraId, FlashlightStatus status) | + | Camera设备状态变化上报 | int32_t OnCameraStatus(const std::string& cameraId, CameraStatus status) | + | 闪光灯状态变化回调 | int32_t OnFlashlightStatus(const std::string& cameraId, FlashlightStatus status) | + | Camera事件回调 | int32_t OnCameraEvent(const std::string& cameraId, CameraEvent event) | - ioffline_stream_operator.h | 功能描述 | 接口名称 | | -------------- | ------------------------------------------------------------ | - | 取消捕获请求 | CamRetCode CancelCapture(int captureId) | - | 释放流 | CamRetCode ReleaseStreams(const std::vector &streamIds) | - | 释放所有离线流 | CamRetCode Release() | + | 取消捕获请求 | int32_t CancelCapture(int32_t captureId) | + | 释放流 | int32_t ReleaseStreams(const std::vector& streamIds) | + | 释放所有离线流 | int32_t Release() | - istream_operator.h | 功能描述 | 接口名称 | | -------------------------------- | ------------------------------------------------------------ | - | 查询是否支持添加参数对应的流 | CamRetCode IsStreamsSupported(
OperationMode mode,
const std::shared_ptr\ &modeSetting,
const std::vector<std::shared_ptr<StreamInfo>> &info,
StreamSupportType &type) | - | 创建流 | CamRetCode CreateStreams(const std::vector> &streamInfos) | - | 释放流 | CamRetCode ReleaseStreams(const std::vector &streamIds) | - | 配置流 | CamRetCode CommitStreams(OperationMode mode, const std::shared_ptr &modeSetting) | - | 获取流的属性 | CamRetCode GetStreamAttributes(std::vector> &attributes) | - | 绑定生产者句柄和指定流 | CamRetCode AttachBufferQueue(int streamId, const OHOS::sptr\ &producer) | - | 解除生产者句柄和指定流的绑定关系 | CamRetCode DetachBufferQueue(int streamId) | - | 捕获图像 | CamRetCode Capture(int captureId, const std::shared_ptr &info, bool isStreaming) | - | 取消捕获 | CamRetCode CancelCapture(int captureId) | - | 将指定流转换成离线流 | CamRetCode ChangeToOfflineStream(const std::vector &streamIds,
OHOS::sptr &callback,
OHOS::sptr &offlineOperator) | + | 查询是否支持添加参数对应的流 | int32_t IsStreamsSupported(
OperationMode mode,
const std::vector& modeSetting,
const std::vector& infos,
StreamSupportType& type) | + | 创建流 | int32_t CreateStreams(const std::vector& streamInfos) | + | 释放流 | int32_t ReleaseStreams(const std::vector& streamIds) | + | 配置流 | int32_t CommitStreams(OperationMode mode, const std::vector& modeSetting) | + | 获取流的属性 | int32_t GetStreamAttributes(std::vector& attributes) | + | 绑定生产者句柄和指定流 | int32_t AttachBufferQueue(int32_t streamId, const sptr& bufferProducer) | + | 解除生产者句柄和指定流的绑定关系 | int32_t DetachBufferQueue(int32_t streamId) | + | 捕获图像 | int32_t Capture(int32_t captureId, const CaptureInfo& info, bool isStreaming) | + | 取消捕获 | int32_t CancelCapture(int32_t captureId) | + | 将指定流转换成离线流 | int32_t ChangeToOfflineStream(const std::vector& streamIds,
const sptr& callbackObj,
sptr& offlineOperator) | - istream_operator_callback.h | 功能描述 | 接口名称 | | ---------------------------------------- | ------------------------------------------------------------ | - | 捕获开始回调,在捕获开始时调用 | void OnCaptureStarted(int32_t captureId, const std::vector &streamIds) | - | 捕获结束回调,在捕获结束时调用 | void OnCaptureEnded(int32_t captureId, const std::vector> &infos) | - | 捕获错误回调,在捕获过程中发生错误时调用 | void OnCaptureError(int32_t captureId, const std::vector> &infos) | - | 帧捕获回调 | void OnFrameShutter(int32_t captureId,
const std::vector &streamIds, uint64_t timestamp) | + | 捕获开始回调,在捕获开始时调用 | int32_t OnCaptureStarted(int32_t captureId, const std::vector& streamIds) | + | 捕获结束回调,在捕获结束时调用 | int32_t OnCaptureEnded(int32_t captureId, const std::vector& infos) | + | 捕获错误回调,在捕获过程中发生错误时调用 | int32_t OnCaptureError(int32_t captureId, const std::vector& infos) | + | 帧捕获回调 | int32_t OnFrameShutter(int32_t captureId, const std::vector& streamIds, uint64_t timestamp) | ### 开发步骤 Camera驱动的开发过程主要包含以下步骤: 1. 注册CameraHost - 定义Camera的HdfDriverEntry结构体,该结构体中定义了CameraHost初始化的方法。 - ``` + 定义Camera的HdfDriverEntry结构体,该结构体中定义了CameraHost初始化的方法(代码目录drivers/peripheral/camera/interfaces/hdi_ipc/camera_host_driver.cpp)。 + ```c++ struct HdfDriverEntry g_cameraHostDriverEntry = { .moduleVersion = 1, .moduleName = "camera_service", @@ -135,33 +137,46 @@ Camera驱动的开发过程主要包含以下步骤: 2. 初始化Host服务 - 步骤1中提到的HdfCameraHostDriverBind接口提供了CameraServiceDispatch和CameraHostStubInstance的注册。这两个接口一个是远端调用CameraHost的方法,如OpenCamera(),SetFlashlight()等,另外一个是Camera设备的初始化,在开机时被调用。 + 步骤1中提到的HdfCameraHostDriverBind接口提供了CameraServiceDispatch和CameraHostStubInstance的注册。CameraServiceDispatch接口是远端调用CameraHost的方法,如OpenCamera(),SetFlashlight()等,CameraHostStubInstance接口是Camera设备的初始化,在开机时被调用。 - ``` - int HdfCameraHostDriverBind(HdfDeviceObject *deviceObject) + ```c++ + static int HdfCameraHostDriverBind(struct HdfDeviceObject *deviceObject) { - HDF_LOGI("HdfCameraHostDriverBind enter!"); - if (deviceObject == nullptr) { - HDF_LOGE("HdfCameraHostDriverBind: HdfDeviceObject is NULL!"); + HDF_LOGI("HdfCameraHostDriverBind enter"); + + auto *hdfCameraHostHost = new (std::nothrow) HdfCameraHostHost; + if (hdfCameraHostHost == nullptr) { + HDF_LOGE("%{public}s: failed to create HdfCameraHostHost object", __func__); return HDF_FAILURE; } - HdfCameraService *hdfCameraService = reinterpret_cast(OsalMemAlloc(sizeof(HdfCameraService))); - if (hdfCameraService == nullptr) { - HDF_LOGE("HdfCameraHostDriverBind OsalMemAlloc HdfCameraService failed!"); + + hdfCameraHostHost->ioService.Dispatch = CameraHostDriverDispatch; // 提供远端CameraHost调用方法 + hdfCameraHostHost->ioService.Open = NULL; + hdfCameraHostHost->ioService.Release = NULL; + + auto serviceImpl = ICameraHost::Get(true); + if (serviceImpl == nullptr) { + HDF_LOGE("%{public}s: failed to get of implement service", __func__); + delete hdfCameraHostHost; + return HDF_FAILURE; + } + + hdfCameraHostHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, + ICameraHost::GetDescriptor()); // 初始化Camera设备 + if (hdfCameraHostHost->stub == nullptr) { + HDF_LOGE("%{public}s: failed to get stub object", __func__); + delete hdfCameraHostHost; return HDF_FAILURE; } - hdfCameraService->ioservice.Dispatch = CameraServiceDispatch; // 提供远端CameraHost调用方法 - hdfCameraService->ioservice.Open = nullptr; - hdfCameraService->ioservice.Release = nullptr; - hdfCameraService->instance = CameraHostStubInstance(); // 初始化Camera设备 - deviceObject->service = &hdfCameraService->ioservice; + + deviceObject->service = &hdfCameraHostHost->ioService; return HDF_SUCCESS; } ``` 下面的函数是远端CameraHost调用的方法: - ``` + ```c++ int32_t CameraHostStub::CameraHostServiceStubOnRemoteRequest(int cmdId, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -196,7 +211,7 @@ Camera驱动的开发过程主要包含以下步骤: 调用Get()接口从远端CameraService中获取CameraHost对象。get()方法如下: - ``` + ```c++ sptr ICameraHost::Get(const char *serviceName) { do { @@ -223,46 +238,74 @@ Camera驱动的开发过程主要包含以下步骤: CameraHostProxy对象中有五个方法,分别是SetCallback、GetCameraIds、GetCameraAbility、OpenCamera和SetFlashlight。下面着重描述OpenCamera接口。 CameraHostProxy的OpenCamera()接口通过CMD_CAMERA_HOST_OPEN_CAMERA调用远端CameraHostStubOpenCamera()接口并获取ICameraDevice对象。 - ``` - CamRetCode CameraHostProxy::OpenCamera(const std::string &cameraId, const OHOS::sptr &callback, OHOS::sptr &pDevice) + ```c++ + int32_t CameraHostProxy::OpenCamera(const std::string& cameraId, const sptr& callbackObj, + sptr& device) { - int32_t ret = Remote()->SendRequest(CMD_CAMERA_HOST_REMOTE_OPEN_CAMERA, data, reply, option); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: SendRequest failed, error code is %{public}d", __func__, ret); - return INVALID_ARGUMENT; + MessageParcel cameraHostData; + MessageParcel cameraHostReply; + MessageOption cameraHostOption(MessageOption::TF_SYNC); + + if (!cameraHostData.WriteInterfaceToken(ICameraHost::GetDescriptor())) { + HDF_LOGE("%{public}s: failed to write interface descriptor!", __func__); + return HDF_ERR_INVALID_PARAM; } - CamRetCode retCode = static_cast(reply.ReadInt32()); - bool flag = reply.ReadBool(); - if (flag) { - sptr remoteCameraDevice = reply.ReadRemoteObject(); - if (remoteCameraDevice == nullptr) { - HDF_LOGE("%{public}s: CameraHostProxy remoteCameraDevice is null", __func__); - } - pDevice = OHOS::iface_cast(remoteCameraDevice); + + if (!cameraHostData.WriteCString(cameraId.c_str())) { + HDF_LOGE("%{public}s: write cameraId failed!", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!cameraHostData.WriteRemoteObject(OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(callbackObj, + ICameraDeviceCallback::GetDescriptor()))) { + HDF_LOGE("%{public}s: write callbackObj failed!", __func__); + return HDF_ERR_INVALID_PARAM; + } + + int32_t cameraHostRet = Remote()->SendRequest(CMD_CAMERA_HOST_OPEN_CAMERA, cameraHostData, cameraHostReply, cameraHostOption); + if (cameraHostRet != HDF_SUCCESS) { + HDF_LOGE("%{public}s failed, error code is %{public}d", __func__, cameraHostRet); + return cameraHostRet; } - return retCode; + + device = hdi_facecast(cameraHostReply.ReadRemoteObject()); + + return cameraHostRet; } ``` Remote()->SendRequest调用上文提到的CameraHostServiceStubOnRemoteRequest(),根据cmdId进入CameraHostStubOpenCamera()接口,最终调用CameraHostImpl::OpenCamera(),该接口获取了CameraDevice并对硬件进行上电等操作。 - ``` - CamRetCode CameraHostImpl::OpenCamera(const std::string &cameraId, const OHOS::sptr &callback, OHOS::sptr &device) + ```c++ + int32_t CameraHostImpl::OpenCamera(const std::string& cameraId, const sptr& callbackObj, + sptr& device) { - std::shared_ptr cameraDevice = std::static_pointer_cast(itr->second); + CAMERA_LOGD("OpenCamera entry"); + DFX_LOCAL_HITRACE_BEGIN; + if (CameraIdInvalid(cameraId) != RC_OK || callbackObj == nullptr) { + CAMERA_LOGW("open camera id is empty or callback is null."); + return INVALID_ARGUMENT; + } + + auto itr = cameraDeviceMap_.find(cameraId); + if (itr == cameraDeviceMap_.end()) { + CAMERA_LOGE("camera device not found."); + return INSUFFICIENT_RESOURCES; + } + CAMERA_LOGD("OpenCamera cameraId find success."); + + std::shared_ptr cameraDevice = itr->second; if (cameraDevice == nullptr) { CAMERA_LOGE("camera device is null."); return INSUFFICIENT_RESOURCES; } - CamRetCode ret = cameraDevice->SetCallback(callback); - if (ret != NO_ERROR) { - CAMERA_LOGW("set camera device callback failed."); - return ret; - } + + CamRetCode ret = cameraDevice->SetCallback(callbackObj); + CHECK_IF_NOT_EQUAL_RETURN_VALUE(ret, HDI::Camera::V1_0::NO_ERROR, ret); + CameraHostConfig *config = CameraHostConfig::GetInstance(); - if (config == nullptr) { - return INVALID_ARGUMENT; - } + CHECK_IF_PTR_NULL_RETURN_VALUE(config, INVALID_ARGUMENT); + std::vector phyCameraIds; RetCode rc = config->GetPhysicCameraIds(cameraId, phyCameraIds); if (rc != RC_OK) { @@ -274,14 +317,20 @@ Camera驱动的开发过程主要包含以下步骤: CameraPowerDown(phyCameraIds); return DEVICE_ERROR; } - + auto sptrDevice = deviceBackup_.find(cameraId); if (sptrDevice == deviceBackup_.end()) { + #ifdef CAMERA_BUILT_ON_OHOS_LITE + deviceBackup_[cameraId] = cameraDevice; + #else deviceBackup_[cameraId] = cameraDevice.get(); + #endif } device = deviceBackup_[cameraId]; cameraDevice->SetStatus(true); - return NO_ERROR; + CAMERA_LOGD("open camera success."); + DFX_LOCAL_HITRACE_END; + return HDI::Camera::V1_0::NO_ERROR; } ``` @@ -289,29 +338,42 @@ Camera驱动的开发过程主要包含以下步骤: CameraDeviceImpl定义了GetStreamOperator、UpdateSettings、SetResultMode和GetEnabledResult等方法,获取流操作方法如下: - ``` - CamRetCode CameraDeviceImpl::GetStreamOperator(const OHOS::sptr &callback, - OHOS::sptr &streamOperator) + ```c++ + int32_t CameraDeviceImpl::GetStreamOperator(const sptr& callbackObj, + sptr& streamOperator) { - if (callback == nullptr) { + HDI_DEVICE_PLACE_A_WATCHDOG; + DFX_LOCAL_HITRACE_BEGIN; + if (callbackObj == nullptr) { CAMERA_LOGW("input callback is null."); return INVALID_ARGUMENT; } - spCameraDeviceCallback_ = callback; + + spCameraDeciceCallback_ = callbackObj; if (spStreamOperator_ == nullptr) { - // 这里新建一个spStreamOperator对象传递给调用者,以便对stream进行各种操作。 - spStreamOperator_ = new(std::nothrow) StreamOperatorImpl(spCameraDeviceCallback_, shared_from_this()); + #ifdef CAMERA_BUILT_ON_OHOS_LITE + // 这里创建一个spStreamOperator_ 对象传递给调用者,以便对stream进行各种操作 + spStreamOperator_ = std::make_shared(spCameraDeciceCallback_, shared_from_this()); + #else + spStreamOperator_ = new(std::nothrow) StreamOperator(spCameraDeciceCallback_, shared_from_this()); + #endif if (spStreamOperator_ == nullptr) { CAMERA_LOGW("create stream operator failed."); return DEVICE_ERROR; } + spStreamOperator_->Init(); ismOperator_ = spStreamOperator_; } streamOperator = ismOperator_; - - spStreamOperator_->SetRequestCallback([this](){ - spCameraDeviceCallback_->OnError(REQUEST_TIMEOUT, 0); + #ifndef CAMERA_BUILT_ON_OHOS_LITE + CAMERA_LOGI("CameraDeviceImpl %{public}s: line: %{public}d", __FUNCTION__, __LINE__); + pipelineCore_->GetStreamPipelineCore()->SetCallback( + [this](const std::shared_ptr &metadata) { + OnMetadataChanged(metadata); }); + #endif + DFX_LOCAL_HITRACE_END; + return HDI::Camera::V1_0::NO_ERROR; } ``` @@ -319,7 +381,7 @@ Camera驱动的开发过程主要包含以下步骤: 调用CreateStreams创建流前需要填充StreamInfo结构体,具体内容如下: - ``` + ```c++ using StreamInfo = struct _StreamInfo { int streamId_; int width_; // 数据流宽 @@ -328,141 +390,239 @@ Camera驱动的开发过程主要包含以下步骤: int dataSpace_; StreamIntent intent_; // StreamIntent 如PREVIEW bool tunneledMode_; - OHOS::sptr bufferQueue_; // 数据流bufferQueue可用streamCustomer->CreateProducer()接口创建 + BufferProducerSequenceable bufferQueue_; // 数据流bufferQueue可用streamCustomer->CreateProducer()接口创建 int minFrameDuration_; EncodeType encodeType_; }; ``` - CreateStreams()接口是StreamOperatorImpl类中的方法,该接口的主要作用是创建一个StreamBase对象,通过StreamBase的Init方法初始化CreateBufferPool等操作。 + CreateStreams()接口是StreamOperator(StreamOperatorImpl类是StreamOperator的基类)类中的方法,该接口的主要作用是创建一个StreamBase对象,通过StreamBase的Init方法初始化CreateBufferPool等操作。 - ``` - RetCode StreamOperatorImpl::CreateStream(const std::shared_ptr& streamInfo) + ```c++ + int32_t StreamOperator::CreateStreams(const std::vector& streamInfos) { - static std::map typeMap = { - {PREVIEW, "PREVIEW"}, - {VIDEO, "VIDEO"}, - {STILL_CAPTURE, "STILL_CAPTURE"}, - {POST_VIEW, "POST_VIEW"}, {ANALYZE, "ANALYZE"}, - {CUSTOM, "CUSTOM"} - }; - - auto itr = typeMap.find(streamInfo->intent_); - if (itr == typeMap.end()) { - CAMERA_LOGE("do not support stream type. [type = %{public}d]", streamInfo->intent_); - return RC_ERROR; + PLACE_A_NOKILL_WATCHDOG(requestTimeoutCB_); + DFX_LOCAL_HITRACE_BEGIN; + for (const auto& it : streamInfos) { + CHECK_IF_NOT_EQUAL_RETURN_VALUE(CheckStreamInfo(it), true, INVALID_ARGUMENT); + CAMERA_LOGI("streamId:%{public}d and format:%{public}d and width:%{public}d and height:%{public}d", + it.streamId_, it.format_, it.width_, it.height_); + if (streamMap_.count(it.streamId_) > 0) { + CAMERA_LOGE("stream [id = %{public}d] has already been created.", it.streamId_); + return INVALID_ARGUMENT; + } + std::shared_ptr stream = StreamFactory::Instance().CreateShared( // 创建Stream实例 + IStream::g_availableStreamType[it.intent_], it.streamId_, it.intent_, pipelineCore_, messenger_); + if (stream == nullptr) { + CAMERA_LOGE("create stream [id = %{public}d] failed.", it.streamId_); + return INSUFFICIENT_RESOURCES; + } + StreamConfiguration scg; + StreamInfoToStreamConfiguration(scg, it); + RetCode rc = stream->ConfigStream(scg); + if (rc != RC_OK) { + CAMERA_LOGE("configure stream %{public}d failed", it.streamId_); + return INVALID_ARGUMENT; + } + if (!scg.tunnelMode && (it.bufferQueue_)->producer_ != nullptr) { + CAMERA_LOGE("stream [id:%{public}d] is not tunnel mode, can't bind a buffer producer", it.streamId_); + return INVALID_ARGUMENT; + } + if ((it.bufferQueue_)->producer_ != nullptr) { + auto tunnel = std::make_shared(); + CHECK_IF_PTR_NULL_RETURN_VALUE(tunnel, INSUFFICIENT_RESOURCES); + rc = tunnel->AttachBufferQueue((it.bufferQueue_)->producer_); + CHECK_IF_NOT_EQUAL_RETURN_VALUE(rc, RC_OK, INVALID_ARGUMENT); + if (stream->AttachStreamTunnel(tunnel) != RC_OK) { + CAMERA_LOGE("attach buffer queue to stream [id = %{public}d] failed", it.streamId_); + return INVALID_ARGUMENT; + } + } + { + std::lock_guard l(streamLock_); + streamMap_[stream->GetStreamId()] = stream; + } + CAMERA_LOGI("create stream success [id:%{public}d] [type:%{public}s]", stream->GetStreamId(), + IStream::g_availableStreamType[it.intent_].c_str()); } - std::shared_ptr stream = StreamFactory::Instance().CreateShared(itr->second); // 创建StreamBase实例 - RetCode rc = stream->Init(streamInfo); - return RC_OK; - } + DFX_LOCAL_HITRACE_END; + return HDI::Camera::V1_0::NO_ERROR; + } ``` -7. **配置流** +7. 配置流 CommitStreams()是配置流的接口,必须在创建流之后调用,其主要作用是初始化Pipeline和创建Pipeline。 - ``` - CamRetCode StreamOperatorImpl::CommitStreams(OperationMode mode, const std::shared_ptr& modeSetting) + ```c++ + int32_t StreamOperator::CommitStreams(OperationMode mode, const std::vector& modeSetting) { - auto cameraDevice = cameraDevice_.lock(); - if (cameraDevice == nullptr) { - CAMERA_LOGE("camera device closed."); - return CAMERA_CLOSED; - } - std::shared_ptr PipelineCore = - std::static_pointer_cast(cameraDevice)->GetPipelineCore(); - if (PipelineCore == nullptr) { - CAMERA_LOGE("get pipeline core failed."); - return CAMERA_CLOSED; + CAMERA_LOGV("enter"); + CHECK_IF_PTR_NULL_RETURN_VALUE(streamPipeline_, DEVICE_ERROR); + PLACE_A_NOKILL_WATCHDOG(requestTimeoutCB_); + if (modeSetting.empty()) { + CAMERA_LOGE("input vector is empty"); + return INVALID_ARGUMENT; } + DFX_LOCAL_HITRACE_BEGIN; - streamPipeCore_ = PipelineCore->GetStreamPipelineCore(); - if (streamPipeCore_ == nullptr) { - CAMERA_LOGE("get stream pipeline core failed."); - return DEVICE_ERROR; + std::vector configs = {}; + { + std::lock_guard l(streamLock_); + std::transform(streamMap_.begin(), streamMap_.end(), std::back_inserter(configs), + [](auto &iter) { return iter.second->GetStreamAttribute(); }); } - - RetCode rc = streamPipeCore_->Init(); // 对pipelinecore的初始化 + + std::shared_ptr setting; + MetadataUtils::ConvertVecToMetadata(modeSetting, setting); + DynamicStreamSwitchMode method = streamPipeline_->CheckStreamsSupported(mode, setting, configs); + if (method == DYNAMIC_STREAM_SWITCH_NOT_SUPPORT) { + return INVALID_ARGUMENT; + } + if (method == DYNAMIC_STREAM_SWITCH_NEED_INNER_RESTART) { + std::lock_guard l(streamLock_); + for (auto it : streamMap_) { + it.second->StopStream(); + } + } + { + std::lock_guard l(streamLock_); + for (auto it : streamMap_) { + if (it.second->CommitStream() != RC_OK) { + CAMERA_LOGE("commit stream [id = %{public}d] failed.", it.first); + return DEVICE_ERROR; + } + } + } + RetCode rc = streamPipeline_->PreConfig(setting); // 设备流配置 if (rc != RC_OK) { - CAMERA_LOGE("stream pipeline core init failed."); + CAMERA_LOGE("prepare mode settings failed"); return DEVICE_ERROR; } - rc = streamPipeCore_->CreatePipeline(mode); // 创建一个pipeline + rc = streamPipeline_->CreatePipeline(mode); // 创建一个pipeline if (rc != RC_OK) { CAMERA_LOGE("create pipeline failed."); return INVALID_ARGUMENT; } - return NO_ERROR; + + DFX_LOCAL_HITRACE_END; + return HDI::Camera::V1_0::NO_ERROR; } ``` -8. **捕获图像** +8. 捕获图像 在调用Capture()接口前需要先填充CaptureInfo结构体,具体内容如下: - ``` + ```c++ using CaptureInfo = struct _CaptureInfo { - std::vector streamIds_; //需要Capture的streamIds - std::shared_ptr captureSetting_; // 这里填充camera ability 可通过CameraHost 的GetCameraAbility()接口获取 - bool enableShutterCallback_; + int[] streamIds_; // 需要Capture的streamIds + unsigned char[] captureSetting_; // 这里填充camera ability 可通过CameraHost 的GetCameraAbility()接口获取 + bool enableShutterCallback_; }; ``` - StreamOperatorImpl中的Capture方法主要调用CreateCapture()接口去捕获数据流: + StreamOperator中的Capture方法主要是捕获数据流: - ``` - CamRetCode StreamOperatorImpl::Capture(int captureId, const std::shared_ptr& captureInfo, bool isStreaming) + ```c++ + int32_t StreamOperator::Capture(int32_t captureId, const CaptureInfo& info, bool isStreaming) { - if (!ValidCaptureInfo(captureId, captureInfo)) { - CAMERA_LOGE("capture streamIds is empty. [captureId = %d]", captureId); - return INVALID_ARGUMENT; - } - std::shared_ptr cameraCapture = nullptr; - RetCode rc = CreateCapture(captureId, captureInfo, isStreaming, cameraCapture); - if (rc != RC_OK) { - CAMERA_LOGE("create capture is failed."); - return DEVICE_ERROR; + CHECK_IF_EQUAL_RETURN_VALUE(captureId < 0, true, INVALID_ARGUMENT); + PLACE_A_NOKILL_WATCHDOG(requestTimeoutCB_); + DFX_LOCAL_HITRACE_BEGIN; + + for (auto id : info.streamIds_) { + std::lock_guard l(streamLock_); + auto it = streamMap_.find(id); + if (it == streamMap_.end()) { + return INVALID_ARGUMENT; + } } - + { - std::unique_lock lock(captureMutex_); - camerCaptureMap_.insert(std::make_pair(captureId, cameraCapture)); + std::lock_guard l(requestLock_); + auto itr = requestMap_.find(captureId); + if (itr != requestMap_.end()) { + return INVALID_ARGUMENT; + } } - - rc = StartThread(); - if (rc != RC_OK) { - CAMERA_LOGE("preview start failed."); - return DEVICE_ERROR; + + std::shared_ptr captureSetting; + MetadataUtils::ConvertVecToMetadata(info.captureSetting_, captureSetting); + CaptureSetting setting = captureSetting; + auto request = + std::make_shared(captureId, info.streamIds_.size(), setting, + info.enableShutterCallback_, isStreaming); + for (auto id : info.streamIds_) { + RetCode rc = streamMap_[id]->AddRequest(request); + if (rc != RC_OK) { + return DEVICE_ERROR; + } + } + + { + std::lock_guard l(requestLock_); + requestMap_[captureId] = request; } - return NO_ERROR; + return HDI::Camera::V1_0::NO_ERROR; } ``` 9. 取消捕获和释放离线流 - StreamOperatorImpl类中的CancelCapture()接口的主要作用是根据captureId取消数据流的捕获。 + StreamOperator类中的CancelCapture()接口的主要作用是根据captureId取消数据流的捕获。 - ``` - CamRetCode StreamOperatorImpl::CancelCapture(int captureId) + ```c++ + int32_t StreamOperator::CancelCapture(int32_t captureId) { - auto itr = camerCaptureMap_.find(captureId); // 根据captureId 在Map中查找对应的CameraCapture对象 - RetCode rc = itr->second->Cancel(); // 调用CameraCapture中Cancel方法结束数据捕获 - std::unique_lock lock(captureMutex_); - camerCaptureMap_.erase(itr); // 擦除该CameraCapture对象 - return NO_ERROR; + CHECK_IF_EQUAL_RETURN_VALUE(captureId < 0, true, INVALID_ARGUMENT); + PLACE_A_NOKILL_WATCHDOG(requestTimeoutCB_); + DFX_LOCAL_HITRACE_BEGIN; + + std::lock_guard l(requestLock_); + auto itr = requestMap_.find(captureId); // 根据captureId 在Map中查找对应的CameraCapture对象 + if (itr == requestMap_.end()) { + CAMERA_LOGE("can't cancel capture [id = %{public}d], this capture doesn't exist", captureId); + return INVALID_ARGUMENT; + } + + RetCode rc = itr->second->Cancel(); // 调用CameraCapture中Cancel方法结束数据捕获 + if (rc != RC_OK) { + return DEVICE_ERROR; + } + requestMap_.erase(itr); // 擦除该CameraCapture对象 + + DFX_LOCAL_HITRACE_END; + return HDI::Camera::V1_0::NO_ERROR; } ``` - StreamOperatorImpl类中的ReleaseStreams接口的主要作用是释放之前通过CreateStream()和CommitStreams()接口创建的流,并销毁Pipeline。 + StreamOperator类中的ReleaseStreams接口的主要作用是释放之前通过CreateStream()和CommitStreams()接口创建的流,并销毁Pipeline。 - ``` - CamRetCode StreamOperatorImpl::ReleaseStreams(const std::vector& streamIds) + ```c++ + int32_t StreamOperator::ReleaseStreams(const std::vector& streamIds) { - RetCode rc = DestroyStreamPipeline(streamIds); // 销毁该streamIds 的pipeline - rc = DestroyHostStreamMgr(streamIds); - rc = DestroyStreams(streamIds); // 销毁该streamIds 的 Stream - return NO_ERROR; + PLACE_A_NOKILL_WATCHDOG(requestTimeoutCB_); + DFX_LOCAL_HITRACE_BEGIN; + for (auto id : streamIds) { + std::lock_guard l(streamLock_); + auto it = streamMap_.find(id); + if (it == streamMap_.end()) { + continue; + } + if (it->second->IsRunning()) { + it->second->StopStream(); + } + it->second->DumpStatsInfo(); + streamMap_.erase(it); + } + + for (auto id : streamIds) { + CHECK_IF_EQUAL_RETURN_VALUE(id < 0, true, INVALID_ARGUMENT); + } + + DFX_LOCAL_HITRACE_END; + return HDI::Camera::V1_0::NO_ERROR; } ``` @@ -472,11 +632,11 @@ Camera驱动的开发过程主要包含以下步骤: ### 开发实例 -在/drivers/peripheral/camera/hal/init目录下有一个关于Camera的demo,开机后会在/vendor/bin下生成可执行文件ohos_camera_demo,该demo可以完成Camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例,可参考[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/init)。 +在/drivers/peripheral/camera/hal/init目录下有一个关于Camera的demo,开机后会在/vendor/bin下生成可执行文件ohos_camera_demo,该demo可以完成Camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例,可参考[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/init)。 1. 在main函数中构造一个CameraDemo 对象,该对象中有对Camera初始化、启停流、释放等控制的方法。下面mainDemo->InitSensors()函数为初始化CameraHost,mainDemo->InitCameraDevice()函数为初始化CameraDevice。 - ``` + ```c++ int main(int argc, char** argv) { RetCode rc = RC_OK; @@ -507,157 +667,271 @@ Camera驱动的开发过程主要包含以下步骤: 初始化CameraHost函数实现如下,这里调用了HDI接口ICameraHost::Get()去获取demoCameraHost,并对其设置回调函数。 - ``` - RetCode CameraDemo::InitSensors() + ```c++ + RetCode OhosCameraDemo::InitSensors() { - demoCameraHost_ = ICameraHost::Get(DEMO_SERVICE_NAME); + int rc = 0; + + CAMERA_LOGD("demo test: InitSensors enter"); + + if (demoCameraHost_ != nullptr) { + return RC_OK; + } + #ifdef CAMERA_BUILT_ON_OHOS_LITE + demoCameraHost_ = OHOS::Camera::CameraHost::CreateCameraHost(); + #else + constexpr const char *DEMO_SERVICE_NAME = "camera_service"; + demoCameraHost_ = ICameraHost::Get(DEMO_SERVICE_NAME, false); + #endif if (demoCameraHost_ == nullptr) { CAMERA_LOGE("demo test: ICameraHost::Get error"); return RC_ERROR; } - - hostCallback_ = new CameraHostCallback(); + + #ifdef CAMERA_BUILT_ON_OHOS_LITE + hostCallback_ = std::make_shared(); + #else + hostCallback_ = new DemoCameraHostCallback(); + #endif rc = demoCameraHost_->SetCallback(hostCallback_); + if (rc != HDI::Camera::V1_0::NO_ERROR) { + CAMERA_LOGE("demo test: demoCameraHost_->SetCallback(hostCallback_) error"); + return RC_ERROR; + } + + CAMERA_LOGD("demo test: InitSensors exit"); + return RC_OK; } ``` 初始化CameraDevice函数实现如下,这里调用了GetCameraIds(cameraIds_),GetCameraAbility(cameraId, ability_),OpenCamera(cameraIds_.front(), callback, demoCameraDevice_)等接口实现了demoCameraHost的获取。 - ``` - RetCode CameraDemo::InitCameraDevice() + ```c++ + RetCode OhosCameraDemo::InitCameraDevice() { + int rc = 0; + + CAMERA_LOGD("demo test: InitCameraDevice enter"); + + if (demoCameraHost_ == nullptr) { + CAMERA_LOGE("demo test: InitCameraDevice demoCameraHost_ == nullptr"); + return RC_ERROR; + } + (void)demoCameraHost_->GetCameraIds(cameraIds_); + if (cameraIds_.empty()) { + return RC_ERROR; + } const std::string cameraId = cameraIds_.front(); - demoCameraHost_->GetCameraAbility(cameraId, ability_); - - sptr callback = new CameraDeviceCallback(); + demoCameraHost_->GetCameraAbility(cameraId, cameraAbility_); + + MetadataUtils::ConvertVecToMetadata(cameraAbility_, ability_); + + GetFaceDetectMode(ability_); + GetFocalLength(ability_); + GetAvailableFocusModes(ability_); + GetAvailableExposureModes(ability_); + GetExposureCompensationRange(ability_); + GetExposureCompensationSteps(ability_); + GetAvailableMeterModes(ability_); + GetAvailableFlashModes(ability_); + GetMirrorSupported(ability_); + GetStreamBasicConfigurations(ability_); + GetFpsRange(ability_); + GetCameraPosition(ability_); + GetCameraType(ability_); + GetCameraConnectionType(ability_); + GetFaceDetectMaxNum(ability_); + + #ifdef CAMERA_BUILT_ON_OHOS_LITE + std::shared_ptr callback = std::make_shared(); + #else + sptr callback = new DemoCameraDeviceCallback(); + #endif rc = demoCameraHost_->OpenCamera(cameraIds_.front(), callback, demoCameraDevice_); + if (rc != HDI::Camera::V1_0::NO_ERROR || demoCameraDevice_ == nullptr) { + CAMERA_LOGE("demo test: InitCameraDevice OpenCamera failed"); + return RC_ERROR; + } + + CAMERA_LOGD("demo test: InitCameraDevice exit"); + return RC_OK; } ``` 2. PreviewOn()接口包含配置流、开启预览流和启动Capture动作。该接口执行完成后Camera预览通路已经开始运转并开启了两路流,一路流是preview,另外一路流是capture或者video,两路流中仅对preview流进行capture动作。 - ``` - static RetCode PreviewOn(int mode, const std::shared_ptr& mainDemo) + ```c++ + static RetCode PreviewOn(int mode, const std::shared_ptr& mainDemo) { - rc = mainDemo->StartPreviewStream(); // 配置preview流 - if (mode == 0) { + RetCode rc = RC_OK; + CAMERA_LOGD("main test: PreviewOn enter"); + + rc = mainDemo->StartPreviewStream(); // 配置preview流 + if (rc != RC_OK) { + CAMERA_LOGE("main test: PreviewOn StartPreviewStream error"); + return RC_ERROR; + } + + if (mode == 0) { rc = mainDemo->StartCaptureStream(); // 配置capture流 - } else { + if (rc != RC_OK) { + CAMERA_LOGE("main test: PreviewOn StartCaptureStream error"); + return RC_ERROR; + } + } else { rc = mainDemo->StartVideoStream(); // 配置video流 - } - - rc = mainDemo->CaptureON(STREAM_ID_PREVIEW, CAPTURE_ID_PREVIEW, CAPTURE_PREVIEW); // 将preview流capture + if (rc != RC_OK) { + CAMERA_LOGE("main test: PreviewOn StartVideoStream error"); + return RC_ERROR; + } + } + + rc = mainDemo->CaptureON(STREAM_ID_PREVIEW, CAPTURE_ID_PREVIEW, CAPTURE_PREVIEW); + if (rc != RC_OK) { + CAMERA_LOGE("main test: PreviewOn mainDemo->CaptureON() preview error"); + return RC_ERROR; + } + + CAMERA_LOGD("main test: PreviewOn exit"); return RC_OK; } ``` StartCaptureStream()、StartVideoStream()和StartPreviewStream()接口都会调用CreateStream()接口,只是传入的参数不同。 - ``` - RetCode CameraDemo::StartVideoStream() - { - RetCode rc = RC_OK; - if (isVideoOn_ == 0) { - isVideoOn_ = 1; - rc = CreateStream(STREAM_ID_VIDEO, streamCustomerVideo_, VIDEO); // 如需启preview或者capture流更改该接口参数即可。 - } - return RC_OK; - } - ``` - CreateStream()方法调用HDI接口去配置和创建流,首先调用HDI接口去获取StreamOperation对象,然后创建一个StreamInfo。调用CreateStreams()和CommitStreams()实际创建流并配置流。 - ``` - RetCode CameraDemo::CreateStreams(const int streamIdSecond, StreamIntent intent) + ```c++ + RetCode OhosCameraDemo::CreateStream(const int streamId, std::shared_ptr &streamCustomer, + StreamIntent intent) { - std::vector> streamInfos; - std::vector>().swap(streamInfos); + int rc = 0; + CAMERA_LOGD("demo test: CreateStream enter"); + GetStreamOpt(); // 获取StreamOperator对象 - std::shared_ptr previewStreamInfo = std::make_shared(); - SetStreamInfo(previewStreamInfo, streamCustomerPreview_, STREAM_ID_PREVIEW, PREVIEW); // 填充StreamInfo - if (previewStreamInfo->bufferQueue_ == nullptr) { - CAMERA_LOGE("demo test: CreateStream CreateProducer(); is nullptr\n"); + if (streamOperator_ == nullptr) { + CAMERA_LOGE("demo test: CreateStream GetStreamOpt() is nullptr\n"); return RC_ERROR; } - streamInfos.push_back(previewStreamInfo); - - std::shared_ptr secondStreamInfo = std::make_shared(); - if (streamIdSecond == STREAM_ID_CAPTURE) { - SetStreamInfo(secondStreamInfo, streamCustomerCapture_, STREAM_ID_CAPTURE, intent); - } else { - SetStreamInfo(secondStreamInfo, streamCustomerVideo_, STREAM_ID_VIDEO, intent); - } - - if (secondStreamInfo->bufferQueue_ == nullptr) { - CAMERA_LOGE("demo test: CreateStreams CreateProducer() secondStreamInfo is nullptr\n"); + + StreamInfo streamInfo = {0}; + + SetStreamInfo(streamInfo, streamCustomer, streamId, intent); // 填充StreamInfo流 + if (streamInfo.bufferQueue_->producer_ == nullptr) { + CAMERA_LOGE("demo test: CreateStream CreateProducer(); is nullptr\n"); return RC_ERROR; } - streamInfos.push_back(secondStreamInfo); - + + std::vector streamInfos; + streamInfos.push_back(streamInfo); + rc = streamOperator_->CreateStreams(streamInfos); // 创建流 - if (rc != Camera::NO_ERROR) { + if (rc != HDI::Camera::V1_0::NO_ERROR) { CAMERA_LOGE("demo test: CreateStream CreateStreams error\n"); return RC_ERROR; } - - rc = streamOperator_->CommitStreams(Camera::NORMAL, ability_); - if (rc != Camera::NO_ERROR) { + + rc = streamOperator_->CommitStreams(NORMAL, cameraAbility_); + if (rc != HDI::Camera::V1_0::NO_ERROR) { CAMERA_LOGE("demo test: CreateStream CommitStreams error\n"); - std::vector streamIds = {STREAM_ID_PREVIEW, streamIdSecond}; + std::vector streamIds; + streamIds.push_back(streamId); streamOperator_->ReleaseStreams(streamIds); return RC_ERROR; } + + CAMERA_LOGD("demo test: CreateStream exit"); + return RC_OK; } ``` CaptureON()接口调用streamOperator的Capture()方法获取Camera数据并轮转buffer,拉起一个线程接收相应类型的数据。 - ``` - RetCode CameraDemo::CaptureON(const int streamId, const int captureId, CaptureMode mode) + ```c++ + RetCode OhosCameraDemo::CaptureON(const int streamId, + const int captureId, CaptureMode mode) { - std::shared_ptr captureInfo = std::make_shared(); // 创建并填充CaptureInfo - captureInfo->streamIds_ = {streamId}; - captureInfo->captureSetting_ = ability_; - captureInfo->enableShutterCallback_ = false; - - int rc = streamOperator_->Capture(captureId, captureInfo, true); // 实际capture开始,buffer轮转开始 + CAMERA_LOGI("demo test: CaptureON enter streamId == %{public}d and captureId == %{public}d and mode == %{public}d", + streamId, captureId, mode); + std::lock_guard l(metaDatalock_); + if (mode == CAPTURE_SNAPSHOT) { + constexpr double latitude = 27.987500; // dummy data: Qomolangma latitde + constexpr double longitude = 86.927500; // dummy data: Qomolangma longituude + constexpr double altitude = 8848.86; // dummy data: Qomolangma altitude + constexpr size_t entryCapacity = 100; + constexpr size_t dataCapacity = 2000; + captureSetting_ = std::make_shared(entryCapacity, dataCapacity); + captureQuality_ = OHOS_CAMERA_JPEG_LEVEL_HIGH; + captureOrientation_ = OHOS_CAMERA_JPEG_ROTATION_270; + mirrorSwitch_ = OHOS_CAMERA_MIRROR_ON; + gps_.push_back(latitude); + gps_.push_back(longitude); + gps_.push_back(altitude); + captureSetting_->addEntry(OHOS_JPEG_QUALITY, static_cast(&captureQuality_), + sizeof(captureQuality_)); + captureSetting_->addEntry(OHOS_JPEG_ORIENTATION, static_cast(&captureOrientation_), + sizeof(captureOrientation_)); + captureSetting_->addEntry(OHOS_CONTROL_CAPTURE_MIRROR, static_cast(&mirrorSwitch_), + sizeof(mirrorSwitch_)); + captureSetting_->addEntry(OHOS_JPEG_GPS_COORDINATES, gps_.data(), gps_.size()); + } + + std::vector setting; + MetadataUtils::ConvertMetadataToVec(captureSetting_, setting); + captureInfo_.streamIds_ = {streamId}; + if (mode == CAPTURE_SNAPSHOT) { + captureInfo_.captureSetting_ = setting; + } else { + captureInfo_.captureSetting_ = cameraAbility_; + } + captureInfo_.enableShutterCallback_ = false; + + int rc = streamOperator_->Capture(captureId, captureInfo_, true); // 实际capture开始,buffer轮转开始 + if (rc != HDI::Camera::V1_0::NO_ERROR) { + CAMERA_LOGE("demo test: CaptureStart Capture error\n"); + streamOperator_->ReleaseStreams(captureInfo_.streamIds_); + return RC_ERROR; + } + if (mode == CAPTURE_PREVIEW) { - streamCustomerPreview_->ReceiveFrameOn(nullptr); // 创建预览线程接收递上来的buffer + streamCustomerPreview_->ReceiveFrameOn(nullptr); // 创建预览线程接收传递上来的buffer } else if (mode == CAPTURE_SNAPSHOT) { - streamCustomerCapture_->ReceiveFrameOn([this](void* addr, const uint32_t size) { // 创建capture线程通过StoreImage回调接收递上来的buffer + streamCustomerCapture_->ReceiveFrameOn([this](void* addr, const uint32_t size) { // 创建capture线程通过StoreImage回调接收传递上来的buffer StoreImage(addr, size); }); } else if (mode == CAPTURE_VIDEO) { OpenVideoFile(); - streamCustomerVideo_->ReceiveFrameOn([this](void* addr, const uint32_t size) {// 创建Video线程通过StoreVideo回调接收递上来的buffer + + streamCustomerVideo_->ReceiveFrameOn([this](void* addr, const uint32_t size) { // 创建video线程通过StoreImage回调接收传递上来的buffer StoreVideo(addr, size); }); } + CAMERA_LOGD("demo test: CaptureON exit"); + return RC_OK; } ``` 3. ManuList()函数从控制台通过fgets()接口获取字符,不同字符所对应demo支持的功能不同,并打印出该demo所支持功能的菜单。 - ``` - static void ManuList(const std::shared_ptr& mainDemo, + ```c++ + static void ManuList(const std::shared_ptr& mainDemo, const int argc, char** argv) { int idx, c; - int awb = 1; - constexpr char shortOptions[] = "h:cwvaqof:"; - c = getopt_long(argc, argv, shortOptions, longOptions, &idx); - while(1) { + bool isAwb = true; + const char *shortOptions = "h:cwvaeqof:"; + c = getopt_long(argc, argv, shortOptions, LONG_OPTIONS, &idx); + while (1) { switch (c) { case 'h': c = PutMenuAndGetChr(); // 打印菜单 break; - - case 'f': + case 'f': FlashLightTest(mainDemo); // 手电筒功能测试 c = PutMenuAndGetChr(); break; @@ -670,27 +944,30 @@ Camera驱动的开发过程主要包含以下步骤: c = PutMenuAndGetChr(); break; case 'w': // AWB功能测试 - if (awb) { + if (isAwb) { mainDemo->SetAwbMode(OHOS_CAMERA_AWB_MODE_INCANDESCENT); } else { mainDemo->SetAwbMode(OHOS_CAMERA_AWB_MODE_OFF); } - awb = !awb; + isAwb = !isAwb; c = PutMenuAndGetChr(); break; case 'a': // AE功能测试 mainDemo->SetAeExpo(); c = PutMenuAndGetChr(); break; - case 'v': // Video功能测试 + case 'e': // Metadata测试 + mainDemo->SetMetadata(); + c = PutMenuAndGetChr(); + break; + case 'v': // VIDEO功能测试 VideoTest(mainDemo); c = PutMenuAndGetChr(); break; case 'q': // 退出demo PreviewOff(mainDemo); mainDemo->QuitDemo(); - exit(EXIT_SUCCESS); - + return; default: CAMERA_LOGE("main test: command error please retry input command"); c = PutMenuAndGetChr(); @@ -702,7 +979,7 @@ Camera驱动的开发过程主要包含以下步骤: PutMenuAndGetChr()接口打印了demo程序的菜单,并调用fgets()等待从控制台输入命令,内容如下: - ``` + ```c++ static int PutMenuAndGetChr(void) { constexpr uint32_t inputCount = 50; @@ -724,7 +1001,7 @@ Camera驱动的开发过程主要包含以下步骤: 控制台输出菜单详情如下: - ``` + ```c++ "Options:\n" "-h | --help Print this message\n" "-o | --offline stream offline test\n" @@ -732,8 +1009,24 @@ Camera驱动的开发过程主要包含以下步骤: "-w | --set WB Set white balance Cloudy\n" "-v | --video capture Video of 10s\n" "-a | --Set AE Set Auto exposure\n" + "-e | --Set Metadeta Set Metadata\n" "-f | --Set Flashlight Set flashlight ON 5s OFF\n" "-q | --quit stop preview and quit this app\n"); ``` - +4. 编译用例 + 在drivers/peripheral/camera/hal/BUILD.gn文件中的deps中添加“init:ohos_camera_demo”,示例代码如下: + ``` + deps = [ + "buffer_manager:camera_buffer_manager", + "device_manager:camera_device_manager", + "hdi_impl:camera_host_service_1.0", + "pipeline_core:camera_pipeline_core", + "utils:camera_utils", + "init:ohos_camera_demo", + ] + ``` + + 以RK3568为例: + 1. 执行全量编译命令./build.sh --product-name rk3568 --ccache,生成可执行二进制文件ohos_camera_demo,路径为:out/rk3568/packages/phone/vendor/bin/。 + 2. 将可执行文件ohos_camera_demo导入开发板,修改权限直接运行即可。 diff --git a/zh-cn/device-dev/driver/driver-peripherals-usb-des.md b/zh-cn/device-dev/driver/driver-peripherals-usb-des.md index c7dc8513b9e69d1dc158868e95350200c7952c6c..110197acf4352730f2df6e079b7e1c3cde344a6b 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-usb-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-usb-des.md @@ -1,90 +1,120 @@ # USB +## 概述 -## 概述 +### 功能简介 -USB Host部分,主要包括协议封装、设备管理、驱动安装与卸载等。 +USB(Universal Serial Bus)通用串行总线,包含了主机端(Host)和设备端(Device)。主机端负责USB总线中的数据传输及端口管理,设备端则可以连接各种外设,所以USB驱动开发又分为主机端驱动开发和设备端驱动开发。 -USB Device部分,支持USB功能设备的开发,提供USB设备相关功能,主要包括设备管理、配置管理、IO管理,实现USB功能设备创建、配置、数据通信等。 +OpenHarmony系统USB模块支持USB业务的开发,提供USB相关的功能,提供用户态第三方功能驱动的USB设备数据读写接口,以及提供创建和删除USB设备,接口的事件获取、打开和关闭等,管道同步异步读写通信,设置USB自定义属性等。 - USB Host和Device驱动模型如下图所示: +USB DDK(USB DriverDevelop Kit)是HDF驱动框架为开发者提供的USB驱动程序开发套件,包括USB Host DDK及USB Device DDK两部分,支持基于用户态开发USB设备驱动的同时,还提供了丰富的USB驱动开发能力,让广大开发者能精准且高效的开发USB驱动程序。 + +### 基本概念 + +- 管道 + + 管道(Pipe)是主机端和设备端点之间数据传输的模型。任何USB设备一旦上电就存在一个信息管道,即默认的控制管道,USB主机通过该管道来获取设备的描述、配置、状态,并对设备进行配置;管道和端点关联,两者有相同的属性,如支持的传输类型、最大包长度、传输方向等。 + +- 端点 + + 端点(Endpoint)是USB设备中的可以进行数据收发的最小单元,支持单向或者双向的数据传输。一个USB设备可以包括若干个端点,不同的端点以端点编号和方向区分。不同端点可以支持不同的传输类型、访问间隔以及最大数据包大小。除端点0外,所有的端点只支持一个方向的数据传输。端点0是一个特殊的端点,它支持双向的控制传输。 + +- 接口 + + 应用软件通过和设备之间的数据交换来完成设备的控制和数据传输。由于同一管道只支持一种类型的数据传输,因此这个过程中通常需要多个管道来完成数据交换。像这样用在一起来对设备进行控制的若干管道的集合称为接口。 + +- 描述符 + + 描述符(Descriptor)是用于描述设备属性(Attributes)的数据结构,第一个字节表示描述符的大小(字节数),第二个字节表示描述符的类型(Type)。 + +### 运作机制 + +#### USB Host DDK + +USB Host DDK为开发者提供了主机端USB驱动开发能力,按照功能分为三大类,分别是DDK初始化类、interface对象操作类及request对象操作类。 **图1** USB Host驱动模型图 ![image](figures/USB-Host驱动模型图.png "USB-Host驱动模型图") - +- USB Interface Pool负责USB Interface管理。提供USB Interface接口对象的申请和回收,USB Interface接口对象用来记录设备端口信息以及资源。USB Interface Pool按照USB Port对USB Interface进行分类管理。同时,此模块还提供了USB DDK API,方便开发者进行USB数据读写操作。 + +- USB Protocol Layer提供USB协议封装,根据USB协议对设备IO/控制命令进行翻译和解析”,同时负责设备描述符的管理,根据USB Device上报的枚举信息,匹配对应的描述符;构建对应的USB Interface接口对象,并将其加入到USB Interface Pool中管理。 + +- Device IO Manager负责USB IO请求管理,提供了同步IO和异步IO管理机制,对于异步IO,IO Manager负责将该请求记录下来,然后通过Raw API Library提供的接口依次处理待发送的IO请求;当收到USB控制器应答的处理结果后,IO接收线程负责解析并上报处理结果给上层调用者。 + +- Raw API Library抽象了底层OS能力,定义了统一的OS能力接口,对外提供了USB RAW API,方便开发者实现更加复杂的驱动功能。 + +- OS Adapter用于封装与平台(Linux和LiteOS)相关的操作,根据不同平台配置编译对应平台的封装接口。在Linux平台上,访问USB FS的操作,全部都封装在这个模块中;而在LiteOS平台上,基于FreeBSD USB框架的设备访问操作,也都全部封装在这个模块中。 + +- PNP Notify用于动态监测USB状态变化,当有新设备添加/移除时,变化设备信息。同时将所有USB设备信息都通过KHDF上报给UHDF侧的PNP Notify Manager模块来完成加载/卸载第三方功能驱动。 + +#### USB Device DDK + +USB Device DDK向开发者提供了设备端USB驱动开发能力。例如,USB端口动态注册和去注册能力,开发者可以基于能力实现USB端口的动态添加和组合;动态实例化能力,支持根据动态下发设备、配置、接口及端点描述符创建设备实例及传输通道;用户态的数据发送及接收能力,支持用户态下发送及接收数据;复合设备能力,支持一个物理设备上多个逻辑设备,实现多个逻辑设备间隔离,并支持不同逻辑设备同时被不同的应用进程访问。 + **图2** USB Device驱动模型图 ![image](figures/USB-Device驱动模型图.png "USB-Device驱动模型图") -USB驱动模型对外开放的API接口能力如下: +- SDK IF负责将USB设备按照设备、接口、管道进行逻辑划分,对配置管理、设备管理、IO管理进行封装。此模块还向开发者提供了设备创建、获取接口、接收Event事件、收发数据等设备测驱动开发的能力接口。 + +- Configuration Manager负责解析HCS文件描述的USB描述符信息,得到的USB描述符信息用于设备创建,同时模块还提供了自定义属性的读取、创建、删除、修改等操作。 + +- Device Manager负责根据配置模块解析USB描述符,并根据USB描述符创建设备。同时还负责获取设备、删除设备、获取设备状态,获取设备上面接口信息。 + +- IO Manager负责数据的读写,包括Events事件、数据读写完成后事件的接收,支持同步和异步模式数据读写。 + +- Adapter IF主要是对复合设备配置驱动及通用功能驱动设备节点操作进行封装,为上层提供统一的设备管理接口。 + +- Adapter该模块由复合设备配置驱动及通用功能驱动提供。 + +## 开发指导 -- USB Host DDK提供给用户态可直接调用的驱动能力接口,按照功能分类三大类:DDK初始化类、对interface对象操作类、对request对象操作类,可以提供DDK初始化、interface绑定和释放,打开和关闭操作,request的申请和释放,同步和异步传输等。 +由于内核态开发USB驱动较复杂,需要开发者对USB协议要有较深的了解才能很好的使用,对开发者的要求相对较高。USB DDK的引入是为了让开发者能在用户态更方便的开发USB驱动。 -- USB Device DDK提供设备管理、IO管理、配置管理,主要功能有:创建和删除设备、获取和打开接口、同步和异步传输等。 +### 场景介绍 +USB Host DDK为开发者提供了普通模式和专家模式,普通模式下,开发者可通过USB DDK API直接完成相关USB数据读写操作,不需要过多关注底层的传输细节。专家模式下,开发者通过USB RAW API直接访问OS平台中USB通道的接口,自定义实现更加复杂的功能。USB Device DDk为开发者提供了管理USB设备、接口定义及USB数据请求等功能。下文将介绍相关API。 ### 接口说明 -USB驱动模型Host侧开放的API接口功能,参考USB Host驱动模型图。 +USB主机端驱动程序开发相关接口(普通模式)如下,具体接口定义[见源码](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/host/usb_ddk_interface.h)。 - **表1** usb_ddk_interface.h + **表1** USB主机端驱动程序开发相关接口(普通模式) | 接口名称 | 功能描述 | | -------- | -------- | | int32_t UsbInitHostSdk(struct UsbSession \*\*session); | USB主机端驱动开发工具包初始化 | -| int32_t UsbExitHostSdk(const struct UsbSession
\*session); | USB主机端驱动开发工具包退出 | | const struct UsbInterface \*UsbClaimInterface(const
struct UsbSession \*session, uint8_t busNum, uint8_t
usbAddr, uint8_t interfaceIndex); | 获取USB接口对象 | -| int32_t UsbReleaseInterface(const struct UsbInterface
\*interfaceObj); | 释放USB接口对象 | -| int32_t UsbAddOrRemoveInterface(const struct UsbSession
\*session, uint8_t busNum, uint8_t usbAddr, uint8_t
interfaceIndex, UsbInterfaceStatus status); | 增加移除接口 | | UsbInterfaceHandle \*UsbOpenInterface(const struct
UsbInterface \*interfaceObj); | 打开USB对象接口 | -| int32_t UsbCloseInterface(const UsbInterfaceHandle
\*interfaceHandle); | 关闭USB接口对象 | -| int32_t UsbSelectInterfaceSetting(const
UsbInterfaceHandle \*interfaceHandle, uint8_t
settingIndex, struct UsbInterface \*\*interfaceObj); | 设置可选配置 | | int32_t UsbGetPipeInfo(const UsbInterfaceHandle
\*interfaceHandle, uint8_t settingIndex, uint8_t pipeId,
struct UsbPipeInfo \*pipeInfo); | 获取指定可选设置的管道信息 | -| int32_t UsbClearInterfaceHalt(const
UsbInterfaceHandle \*interfaceHandle, uint8_t
pipeAddress); | 清除指定索引的管道状态 | | struct UsbRequest \*UsbAllocRequest(const
UsbInterfaceHandle \*interfaceHandle, int32_t isoPackets
, int32_t length); | 分配请求对象 | -| int32_t UsbFreeRequest(const struct UsbRequest
\*request); | 释放请求对象 | -| int32_t UsbSubmitRequestAsync(const struct UsbRequest
\*request); | 发送异步请求 | | int32_t UsbFillRequest(const struct UsbRequest
\*request, const UsbInterfaceHandle \*interfaceHandle,
const struct UsbRequestParams \*params); | 填充请求 | -| int32_t UsbCancelRequest(const struct UsbRequest
\*request); | 取消异步请求 | | int32_t UsbSubmitRequestSync(const struct UsbRequest
\*request); | 发送同步请求 | - **表2** usb_raw_api.h +USB主机端驱动程序开发相关接口(专家模式)如下,具体接口定义[见源码](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/host/usb_raw_api.h)。 + + **表2** USB主机端驱动程序开发相关接口(专家模式) | 接口名称 | 功能描述 | | -------- | -------- | | int32_t UsbRawInit(struct UsbSession \*\*session); | USB驱动开发工具包专家模式初始化 | -| int32_t UsbRawExit(const struct UsbSession \*session); | USB驱动开发工具包专家模式退出 | | UsbRawHandle \*UsbRawOpenDevice(const struct
UsbSession \*session, uint8_t busNum, uint8_t
usbAddr); | 打开USB设备对象 | -| int32_t UsbRawCloseDevice(const UsbRawHandle
\*devHandle); | 关闭USB设备对象 | | int32_t UsbRawSendControlRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbControlRequestData
\*requestData); | 执行同步控制传输 | | int32_t UsbRawSendBulkRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步批量传输 | | int32_t UsbRawSendInterruptRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步中断传输 | | int32_t UsbRawGetConfigDescriptor(const UsbRawDevice
\*rawDev, uint8_t configIndex, struct
UsbRawConfigDescriptor \*\*config); | 获取给定设备指定ID的设备配置描述符 | -| void UsbRawFreeConfigDescriptor(const struct
UsbRawConfigDescriptor \*config); | 释放配置描述符内存空间 | -| int32_t UsbRawGetConfiguration(const UsbRawHandle
\*devHandle, int32_t \*config); | 获取当前激活配置 | -| int32_t UsbRawSetConfiguration(const UsbRawHandle
\*devHandle, int32_t config); | 设置当前激活配置 | -| int32_t UsbRawGetDescriptor(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawDescriptorParam \*param, const unsigned char
\*data); | 获取描述符信息 | -| UsbRawDevice \*UsbRawGetDevice(const UsbRawHandle
\*devHandle); | 由设备句柄获取设备指针 | -| int32_t UsbRawGetDeviceDescriptor(const UsbRawDevice
\*rawDev, struct
UsbDeviceDescriptor \*desc); | 获取给定设备的USB设备描述符 | -| int32_t UsbRawClaimInterface(const UsbRawHandle
\*devHandle, int32_t
interfaceNumber); | 声明给定设备句柄上的接口 | -| int32_t UsbRawReleaseInterface(const UsbRawHandle
\*devHandle, in
t interfaceNumber); | 释放之前声明的接口 | -| int32_t UsbRawResetDevice(const UsbRawHandle
\*devHandle); | 复位设备 | -| struct UsbRawRequest \*UsbRawAllocRequest(const
UsbRawHandle
\*devHandle, int32_t isoPackets, int32_t length); | 分配一个带有指定数量的同步包描述符的传输请求 | -| int32_t UsbRawFreeRequest(const struct UsbRawRequest
\*request); | 释放之前分配的传输请求 | -| int32_t UsbRawFillBulkRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充批量传输请求所需信息 | -| int32_t UsbRawFillControlSetup(const unsigned char \*setup,
const struct UsbControlRequestData \*requestData); | 填充控制传输设置包所需信息 | -| int32_t UsbRawFillControlRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充控制传输请求所需信息 | | int32_t UsbRawFillInterruptRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充中断传输请求所需信息 | | int32_t UsbRawFillIsoRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充同步传输(Isochronous Transfers)请求所需信息 | | int32_t UsbRawSubmitRequest(const struct UsbRawRequest
\*request); | 提交一个传输请求 | | int32_t UsbRawCancelRequest(const struct UsbRawRequest
\*request); | 取消一个传输请求 | | int32_t UsbRawHandleRequests(const UsbRawHandle
\*devHandle); | 传输请求事件完成处理 | -USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型图。 +USB设备端用于管理USB设备的相关接口如下,具体接口定义[见源码](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/device/usbfn_device.h)。 - **表3** usbfn_device.h + **表3** USB设备端用于管理USB设备的相关接口 | 接口名称 | 功能描述 | | -------- | -------- | @@ -92,7 +122,9 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | int32_t UsbFnRemoveDevice(struct UsbFnDevice
\*fnDevice); | 删除USB设备 | | const struct UsbFnDevice \*UsbFnGetDevice(const char
\*udcName); | 获取USB设备 | - **表4** usbfn_interface.h +USB设备端用于USB接口定义的相关接口如下,具体接口定义[见源码](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/device/usbfn_interface.h)。 + + **表4** USB设备端用于USB接口定义的相关接口 | 接口名称 | 功能描述 | | -------- | -------- | @@ -103,7 +135,9 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | int32_t UsbFnGetInterfacePipeInfo(struct UsbFnInterface
\*interface, uint8_t pipeId, struct UsbFnPipeInfo \*info); | 获取管道信息 | | int32_t UsbFnSetInterfaceProp(const struct UsbFnInterface
\*interface, const char \*name, const char \*value); | 设置自定义属性 | - **表5** usbfn_request.h +USB设备端用于管理USB数据请求的相关接口如下,具体接口定义[见源码](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/device/usbfn_request.h)。 + + **表5** USB设备端用于管理USB数据请求的相关接口 | 接口名称 | 功能描述 | | -------- | -------- | @@ -115,113 +149,304 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | int32_t UsbFnCancelRequest(struct UsbFnRequest \*req); | 取消请求 | -## 开发步骤 - -USB驱动是基于HDF框架、PLATFORM和OSAL基础接口进行开发,不区分操作系统和芯片平台,为不同USB器件提供统一的驱动模型。本篇开发指导以串口为例,分别介绍USB Host和USB Device驱动开发。 - +### 开发步骤 + +USB驱动基于HDF框架、Platform和OSAL基础接口进行开发,不区分操作系统和芯片平台,为不同USB器件提供统一的驱动模型。此处以串口为例,分别介绍USB Host和USB Device驱动开发的详细过程。 + +#### Host DDK API驱动开发 + +1. 在设备私有数据HCS中配置,完成主机端驱动总体信息的配置,具体如下: + + ```cpp + root { + module = "usb_pnp_device"; + usb_pnp_config { + match_attr = "usb_pnp_match"; + usb_pnp_device_id = "UsbPnpDeviceId"; + UsbPnpDeviceId { + idTableList = [ + "host_acm_table" + ]; + host_acm_table { + // 驱动模块名,该字段的值必须和驱动入口结构的moduleName一致 + moduleName = "usbhost_acm"; + // 驱动对外发布服务的名称,必须唯一 + serviceName = "usbhost_acm_pnp_service"; + // 驱动私有数据匹配关键字 + deviceMatchAttr = "usbhost_acm_pnp_matchAttr"; + // 从该字段开始(包含该字段)之后数据长度,以byte为单位 + length = 21; + // USB驱动匹配规则vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber + matchFlag = 0x0303; + // 厂商编号 + vendorId = 0x12D1; + // 产品编号 + productId = 0x5000; + // 设备出厂编号,低16位 + bcdDeviceLow = 0x0000; + // 设备出厂编号,高16位 + bcdDeviceHigh = 0x0000; + // USB分配的设备类代码 + deviceClass = 0; + // USB分配的子类代码 + deviceSubClass = 0; + // USB分配的设备协议代码 + deviceProtocol = 0; + // 接口类型,根据实际需要可填写多个 + interfaceClass = [0]; + // 接口子类型,根据实际需要可填写多个 + interfaceSubClass = [2, 0]; + // 接口所遵循的协议,根据实际需要可填写多个 + interfaceProtocol = [1, 2]; + // 接口的编号,根据实际需要可填写多个 + interfaceNumber = [2, 3]; + } + } + } + } + ``` -### Host DDK API驱动开发步骤 +2. USB主机端驱动开发工具包初始化。 -1. 驱动匹配表配置。 + ```cpp + int32_t UsbInitHostSdk(struct UsbSession **session); + ``` -2. 初始化Host DDK。 +3. 步骤2初始化完后获取UsbInterface对象。 -3. 待步骤2初始化完后获取UsbInterface接口对象。 + ```cpp + const struct UsbInterface *UsbClaimInterface(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr, uint8_t interfaceIndex); + ``` 4. 打开步骤3获取到的UsbInterface接口对象,获取相应接口的UsbInterfaceHandle对象。 + ```cpp + UsbInterfaceHandle *UsbOpenInterface(const struct UsbInterface *interfaceObj); + ``` + 5. 根据步骤4获取到的UsbInterfaceHandle对象,获取指定索引为pipeIndex的pipeInfo信息。 + ```cpp + int32_t UsbGetPipeInfo(const UsbInterfaceHandle *interfaceHandle, uint8_t settingIndex, uint8_t pipeId, struct UsbPipeInfo *pipeInfo); + ``` + 6. 为步骤4获取到的UsbInterfaceHandle预先分配待发送的IO Request对象。 + ```cpp + struct UsbRequest *UsbAllocRequest(const UsbInterfaceHandle *interfaceHandle, int32_t isoPackets, int32_t length); + ``` + 7. 根据输入参数params填充步骤6预先分配的IO Request。 + ```cpp + int32_t UsbFillRequest(const struct UsbRequest *request, const UsbInterfaceHandle *interfaceHandle, const struct UsbRequestParams *params); + ``` + 8. 提交IO Request对象,可以选择同步或异步两种模式。 + ```cpp + int32_t UsbSubmitRequestSync(const struct UsbRequest *request); //发送同步IO请求 + int32_t UsbSubmitRequestAsync(const struct UsbRequest *request); //发送异步IO请求 + ``` -### Host RAW API驱动开发步骤 +#### Host RAW API驱动开发 -1. 驱动匹配表配置。 +1. 同Host DDK API的步骤1一样,在设备私有数据HCS中配置。 2. 初始化Host RAW,并打开USB设备,然后获取描述符,通过描述符获取接口、端点信息。 -3. 分配Request,并根据传输类型使用相应接口对Request进行填充。 - -4. 提交IO Request对象,可以选择同步或异步两种模式。 - - -### Device DDK API驱动开发步骤 - -1. 构造描述符。 - -2. 创建设备,使用步骤1构造的描述符实例化一个USB设备。 - -3. 根据创建的设备获取接口(UsbFnDeviceGetInterface),获取Pipe信息(UsbFnInterfaceGetPipeInfo),打开接口获取Handle(UsbFnInterfaceOpen),根据Handle和Pipe号获取Request(UsbFnRequestAlloc)。 + ```cpp + int32_t UsbRawInit(struct UsbSession **session); + ``` + +3. 待步骤2完成后打开USB设备。 + + ```cpp + UsbRawHandle *UsbRawOpenDevice(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr); + ``` + +4. 待步骤3完成后获取描述符,通过描述符获取接口、端点信息。 + + ```cpp + int32_t UsbRawGetConfigDescriptor(const UsbRawDevice *rawDev, uint8_t configIndex, struct UsbRawConfigDescriptor **config); + ``` + +5. 分配Request,并根据传输类型使用相应接口对Request进行填充。 + + ```cpp + int32_t UsbRawFillBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // 填充用于批量传输的请求 + int32_t UsbRawFillControlSetup(const unsigned char *setup, const struct UsbControlRequestData *requestData); + int32_t UsbRawFillControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // 填充用于控制传输的请求 + int32_t UsbRawFillInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // 填充用于中断传输的请求 + int32_t UsbRawFillIsoRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // 填充用于同步传输的请求 + ``` + +6. 提交IO Request对象,可以选择同步或异步两种模式。 + + ```cpp + int32_t UsbRawSendControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbControlRequestData *requestData); //发送同步USB控制传输请求 + int32_t UsbRawSendBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData); //发送同步USB批量传输请求 + int32_t UsbRawSendInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData); //发送同步执行USB中断传输请求 + int32_t UsbRawSubmitRequest(const struct UsbRawRequest *request); //提交异步IO请求 + ``` + +#### Device DDK API驱动开发 + +1. 在设备功能代码中构造描述符。 + + ```cpp + static struct UsbFnFunction g_acmFunction = { // 功能描述符 + .enable = true, + .funcName = "f_generic.a", + .strings = g_acmStrings, + .fsDescriptors = g_acmFsFunction, + .hsDescriptors = g_acmHsFunction, + .ssDescriptors = g_acmSsFunction, + .sspDescriptors = NULL, + }; + struct UsbFnFunction *g_functions[] = { + #ifdef CDC_ECM + &g_ecmFunction, + #endif + #ifdef CDC_ACM + &g_acmFunction, + #endif + NULL + }; + static struct UsbFnConfiguration g_masterConfig = { // 配置描述符 + .configurationValue = 1, + .iConfiguration = USB_FUNC_CONFIG_IDX, + .attributes = USB_CFG_BUS_POWERED, + .maxPower = POWER, + .functions = g_functions, + }; + static struct UsbFnConfiguration *g_configs[] = { + &g_masterConfig, + NULL, + }; + static struct UsbDeviceDescriptor g_cdcMasterDeviceDesc = { // 设备描述符 + .bLength = sizeof(g_cdcMasterDeviceDesc), + .bDescriptorType = USB_DDK_DT_DEVICE, + .bcdUSB = CpuToLe16(BCD_USB), + .bDeviceClass = 0, + .bDeviceSubClass = 0, + .bDeviceProtocol = 0, + .bMaxPacketSize0 = USB_MAX_PACKET_SIZE, + .idVendor = CpuToLe16(DEVICE_VENDOR_ID), + .idProduct = CpuToLe16(DEVICE_PRODUCT_ID), + .bcdDevice = CpuToLe16(DEVICE_VERSION), + .iManufacturer = USB_FUNC_MANUFACTURER_IDX, + .iProduct = USB_FUNC_PRODUCT_IDX, + .iSerialNumber = USB_FUNC_SERIAL_IDX, + .bNumConfigurations = 1, + }; + static struct UsbFnDeviceDesc g_masterFuncDevice = { // 描述符入口 + .deviceDesc = &g_cdcMasterDeviceDesc, + .deviceStrings = g_devStrings, + .configs = g_configs, + }; + ``` + +2. 创建设备。描述符构造完成后,使用UsbFnDeviceCreate函数创建一个USB设备,并传入UDC控制器和UsbFnDescriptorData结构体。 + + ```cpp + if (useHcs == 0) { // 使用代码编写的描述符 + descData.type = USBFN_DESC_DATA_TYPE_DESC; + descData.descriptor = &g_acmFuncDevice; + } else { // 使用hcs编写的描述符 + descData.type = USBFN_DESC_DATA_TYPE_PROP; + descData.property = acm->device->property; + } + // 创建设备 + fnDev = (struct UsbFnDevice *) UsbFnCreateDevice(acm->udcName, &descData); + ``` + +3. 设备创建后,使用UsbFnGetInterface函数获取UsbInterface接口对象,并通过UsbFnGetInterfacePipeInfo函数获取USB管道信息。 + + ```cpp + // 获取接口 + fnIface = (struct UsbFnInterface *)UsbFnGetInterface(fnDev, i); + // 获取Pipe信息 + UsbFnGetInterfacePipeInfo(fnIface, i, &pipeInfo); + // 获取Handle + handle = UsbFnOpenInterface(fnIface); + // 获取控制(EP0)Request + req = UsbFnAllocCtrlRequest(acm->ctrlIface.handle, + sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding)); + // 获取Request + req = UsbFnAllocCtrlRequest(acm->ctrlIface.handle, + sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding)); + ``` + +4. 通过UsbFnStartRecvInterfaceEvent函数接收Event事件,并通过UsbFnEventCallback回调函数对Event事件做出响应。 + + ```cpp + // 开始接收Event事件 + ret = UsbFnStartRecvInterfaceEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm); + // Event处理回调函数 + static void UsbAcmEventCallback(struct UsbFnEvent *event) + { + struct UsbAcmDevice *acm = NULL; + if (event == NULL || event->context == NULL) { + HDF_LOGE("%s: event is null", __func__); + return; + } -4. 接收Event事件(UsbFnInterfaceStartRecvEvent)如Enable、Setup等事件,回调函数(UsbFnEventCallback)中对Event事件做出响应。 + acm = (struct UsbAcmDevice *)event->context; + switch (event->type) { + case USBFN_STATE_BIND: + HDF_LOGI("%s: receive bind event", __func__); + break; + case USBFN_STATE_UNBIND: + HDF_LOGI("%s: receive unbind event", __func__); + break; + case USBFN_STATE_ENABLE: + HDF_LOGI("%s: receive enable event", __func__); + AcmEnable(acm); + break; + case USBFN_STATE_DISABLE: + HDF_LOGI("%s: receive disable event", __func__); + AcmDisable(acm); + acm->enableEvtCnt = 0; + break; + case USBFN_STATE_SETUP: + HDF_LOGI("%s: receive setup event", __func__); + if (event->setup != NULL) { + AcmSetup(acm, event->setup); + } + break; + case USBFN_STATE_SUSPEND: + HDF_LOGI("%s: receive suspend event", __func__); + AcmSuspend(acm); + break; + case USBFN_STATE_RESUME: + HDF_LOGI("%s: receive resume event", __func__); + AcmResume(acm); + break; + default: + break; + } + } + ``` 5. 收发数据,可以选择同步异步发送模式。 + ```cpp + notify = (struct UsbCdcNotification *)req->buf; + ... + if (memcpy_s((void *)(notify + 1), length, data, length) != EOK) { + return HDF_FAILURE; + } + ret = UsbFnSubmitRequestAsync(req); // 异步发送 + ``` -## 开发实例 +### 开发实例 本实例提供USB串口驱动开发示例,并简要对具体关键点进行开发说明。 - -### Host DDK API驱动开发 - - -``` -root { - module = "usb_pnp_device"; - usb_pnp_config { - match_attr = "usb_pnp_match"; - usb_pnp_device_id = "UsbPnpDeviceId"; - UsbPnpDeviceId { - idTableList = [ - "host_acm_table" - ]; - host_acm_table { - // 驱动模块名,该字段的值必须和驱动入口结构的moduleName一致 - moduleName = "usbhost_acm"; - // 驱动对外发布服务的名称,必须唯一 - serviceName = "usbhost_acm_pnp_service"; - // 驱动私有数据匹配关键字 - deviceMatchAttr = "usbhost_acm_pnp_matchAttr"; - // 从该字段开始(包含该字段)之后数据长度,以byte为单位 - length = 21; - // USB驱动匹配规则vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber - matchFlag = 0x0303; - // 厂商编号 - vendorId = 0x12D1; - // 产品编号 - productId = 0x5000; - // 设备出厂编号,低16位 - bcdDeviceLow = 0x0000; - // 设备出厂编号,高16位 - bcdDeviceHigh = 0x0000; - // USB分配的设备类代码 - deviceClass = 0; - // USB分配的子类代码 - deviceSubClass = 0; - // USB分配的设备协议代码 - deviceProtocol = 0; - // 接口类型,根据实际需要可填写多个 - interfaceClass = [0]; - // 接口子类型,根据实际需要可填写多个 - interfaceSubClass = [2, 0]; - // 接口所遵循的协议,根据实际需要可填写多个 - interfaceProtocol = [1, 2]; - // 接口的编号,根据实际需要可填写多个 - interfaceNumber = [2, 3]; - } - } - } -} -``` +#### Host DDK API驱动开发 ```cpp - #include "usb_serial.h" #include "hdf_base.h" #include "hdf_log.h" @@ -234,7 +459,7 @@ root { #define HDF_LOG_TAG USB_HOST_ACM #define STR_LEN 512 -static struct UsbRequest *g_syncRequest = NULL; +static struct UsbRequest *g_syncRequest = NULL; // 定义一个USB请求 static struct UsbRequest *g_ctrlCmdRequest = NULL; static bool g_acmReleaseFlag = false; static uint8_t *g_acmReadBuffer = NULL; @@ -245,42 +470,41 @@ static int32_t SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, int32_t ret; uint16_t index = acm->intPipe->interfaceId; struct UsbControlParams controlParams; - struct UsbRequestParams params; + struct UsbRequestParams params; // 定义一个USB请求参数对象 if (acm == NULL || buf == NULL) { - HDF_LOGE("%s:invalid param", __func__); return HDF_ERR_IO; } if (acm->ctrlReq == NULL) { + // 为获取到的UsbInterfaceHandle预先分配待发送的IO Request对象 acm->ctrlReq = UsbAllocRequest(acm->ctrDevHandle, 0, len); if (acm->ctrlReq == NULL) { - HDF_LOGE("%s: UsbAllocRequest failed", __func__); return HDF_ERR_IO; } } controlParams.request = request; - controlParams.target = USB_REQUEST_TARGET_INTERFACE; - controlParams.reqType = USB_REQUEST_TYPE_CLASS; - controlParams.direction = USB_REQUEST_DIR_TO_DEVICE; + controlParams.target = USB_REQUEST_TARGET_INTERFACE; // 接口对象 + controlParams.reqType = USB_REQUEST_TYPE_CLASS; // 请求类型 + controlParams.direction = USB_REQUEST_DIR_TO_DEVICE; // 从主机到设备的数据传输 controlParams.value = value; controlParams.index = index; controlParams.data = buf; controlParams.size = len; - params.interfaceId = USB_CTRL_INTERFACE_ID; + params.interfaceId = USB_CTRL_INTERFACE_ID; // 定义USB控制接口的默认ID params.pipeAddress = acm->ctrPipe->pipeAddress; params.pipeId = acm->ctrPipe->pipeId; - params.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; - params.timeout = USB_CTRL_SET_TIMEOUT; + params.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; // 控制类型 + params.timeout = USB_CTRL_SET_TIMEOUT; // 设置超时时间 params.ctrlReq = UsbControlSetUp(&controlParams); + // 根据params填充预先分配的IO Request ret = UsbFillRequest(acm->ctrlReq, acm->ctrDevHandle, ¶ms); - if (HDF_SUCCESS != ret) { - HDF_LOGE("%s: failed, ret=%d ", __func__, ret); + if (ret != HDF_SUCCESS) { return ret; } - ret = UsbSubmitRequestSync(acm->ctrlReq); //发送同步IO Request - if (HDF_SUCCESS != ret) { - HDF_LOGE("UsbSubmitRequestSync failed, ret=%d ", ret); + // 发送同步IO Request + ret = UsbSubmitRequestSync(acm->ctrlReq); + if (ret != HDF_SUCCESS) { return ret; } if (!acm->ctrlReq->compInfo.status) { @@ -293,8 +517,8 @@ static struct UsbInterface *GetUsbInterfaceById(const struct AcmDevice *acm, uint8_t interfaceIndex) { struct UsbInterface *tmpIf = NULL; - tmpIf = (struct UsbInterface *)UsbClaimInterface(acm->session, acm->busNum, - acm->devAddr, interfaceIndex); // 获取UsbInterface接口对象 + // 获取UsbInterface接口对象 + tmpIf = (struct UsbInterface *)UsbClaimInterface(acm->session, acm->busNum, acm->devAddr, interfaceIndex); return tmpIf; } ... @@ -303,8 +527,8 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, { uint8_t i; int32_t ret; - struct UsbInterfaceInfo *info = NULL; - UsbInterfaceHandle *interfaceHandle = NULL; + struct UsbInterfaceInfo *info = NULL; // 定义一个USB接口信息对象 + UsbInterfaceHandle *interfaceHandle = NULL; // 定义一个USB接口操作句柄,就是void *类型 if (pipeType == USB_PIPE_TYPE_CONTROL) { info = &acm->ctrIface->info; @@ -313,19 +537,20 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, else { info = &acm->iface[interfaceIndex]->info; + // 根据interfaceIndex获取设备句柄 interfaceHandle = InterfaceIdToHandle(acm, info->interfaceIndex); } for (i = 0; i <= info->pipeNum; i++) { struct UsbPipeInfo p; - ret = UsbGetPipeInfo(interfaceHandle, info->curAltSetting, i, &p);// 获取指定索引为i的pipeInfo信息 + // 获取指定索引为i的pipeInfo信息 + ret = UsbGetPipeInfo(interfaceHandle, info->curAltSetting, i, &p); if (ret < 0) { continue; } if ((p.pipeDirection == pipeDirection) && (p.pipeType == pipeType)) { - struct UsbPipeInfo *pi = OsalMemCalloc(sizeof(*pi)); + struct UsbPipeInfo *pi = OsalMemCalloc(sizeof(*pi)); // 开辟内存并初始化 if (pi == NULL) { - HDF_LOGE("%s: Alloc pipe failed", __func__); return NULL; } p.interfaceId = info->interfaceIndex; @@ -341,7 +566,6 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm, { uint8_t i; if (acm == NULL) { - HDF_LOGE("%s: invalid params", __func__); return NULL; } for (i = 0; i < acm->interfaceCnt; i++) { @@ -349,6 +573,7 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm, if (!acm->iface[i]) { continue; } + // 获取控制pipe的pipeInfo信息 p = EnumePipe(acm, i, pipeType, pipeDirection); if (p == NULL) { continue; @@ -365,40 +590,32 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) errno_t err; struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%s: device is null", __func__); return HDF_ERR_INVALID_OBJECT; } acm = (struct AcmDevice *)OsalMemCalloc(sizeof(*acm)); if (acm == NULL) { - HDF_LOGE("%s: Alloc usb serial device failed", __func__); return HDF_FAILURE; } + // 初始化互斥锁,&acm->lock表示指向互斥量的指针 if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) { - HDF_LOGE("%s:%d OsalMutexInit failed", __func__, __LINE__); goto error; } info = (struct UsbPnpNotifyServiceInfo *)device->priv; if (info != NULL) { - HDF_LOGD("%s:%d busNum=%d,devAddr=%d,interfaceLength=%d", - __func__, __LINE__, info->busNum, info->devNum, info->interfaceLength); acm->busNum = info->busNum; acm->devAddr = info->devNum; acm->interfaceCnt = info->interfaceLength; err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES, (const void*)info->interfaceNumber, info->interfaceLength); if (err != EOK) { - HDF_LOGE("%s:%d memcpy_s failed err=%d", - __func__, __LINE__, err); goto lock_error; } } else { - HDF_LOGE("%s:%d info is NULL!", __func__, __LINE__); goto lock_error; } acm->device = device; device->service = &(acm->service); acm->device->service->Dispatch = UsbSerialDeviceDispatch; - HDF_LOGD("UsbSerialDriverBind=========================OK"); return HDF_SUCCESS; lock_error: @@ -416,9 +633,9 @@ static int32_t AcmAllocReadRequests(struct AcmDevice *acm) int32_t ret; struct UsbRequestParams readParams; for (int32_t i = 0; i < ACM_NR; i++) { - acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // 分配待发送的readReq IO Request对象 + // 分配待发送的readReq IO Request对象 + acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); if (!acm->readReq[i]) { - HDF_LOGE("readReq request failed"); goto error; } readParams.userData = (void *)acm; @@ -426,14 +643,14 @@ static int32_t AcmAllocReadRequests(struct AcmDevice *acm) readParams.pipeId = acm->dataInPipe->pipeId; readParams.interfaceId = acm->dataInPipe->interfaceId; readParams.callback = AcmReadBulk; - readParams.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + readParams.requestType = USB_REQUEST_PARAMS_DATA_TYPE; /* Data type */ readParams.timeout = USB_CTRL_SET_TIMEOUT; readParams.dataReq.numIsoPackets = 0; readParams.dataReq.direction = (acm->dataInPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; readParams.dataReq.length = acm->readSize; - ret = UsbFillRequest(acm->readReq[i], InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), &readParams); // 填充待发送的readReq对象 - if (HDF_SUCCESS != ret) { - HDF_LOGE("%s: UsbFillRequest failed, ret=%d n", __func__, ret); + // 根据readParams填充预先分配待发送的readReq IO Request对象 + ret = UsbFillRequest(acm->readReq[i], InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), &readParams); + if (ret != HDF_SUCCESS) { goto error; } } @@ -448,9 +665,9 @@ static int32_t AcmAllocNotifyRequest(struct AcmDevice *acm) { int32_t ret; struct UsbRequestParams intParams = {}; - acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); // 分配待发送的中断IO Request对象 + // 分配待发送的中断IO Request对象 + acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); if (!acm->notifyReq) { - HDF_LOGE("notifyReq request failed"); return HDF_ERR_MALLOC_FAIL; } intParams.userData = (void *)acm; @@ -463,9 +680,9 @@ static int32_t AcmAllocNotifyRequest(struct AcmDevice *acm) intParams.dataReq.numIsoPackets = 0; intParams.dataReq.direction = (acm->intPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & DIRECTION_MASK; intParams.dataReq.length = acm->intSize; - ret = UsbFillRequest(acm->notifyReq, InterfaceIdToHandle(acm, acm->intPipe->interfaceId), &intParams); // 填充预先分配的中断IO Request - if (HDF_SUCCESS != ret) { - HDF_LOGE("%s: UsbFillRequest failed, ret=%d n", __func__, ret); + // 填充预先分配的中断IO Request + ret = UsbFillRequest(acm->notifyReq, InterfaceIdToHandle(acm, acm->intPipe->interfaceId), &intParams); + if (ret != HDF_SUCCESS) { goto error; } return HDF_SUCCESS; @@ -479,6 +696,7 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm) { for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { + // 释放一个USB接口对象 UsbReleaseInterface(acm->iface[i]); acm->iface[i] = NULL; } @@ -492,22 +710,23 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm) static int32_t AcmClaimInterfaces(struct AcmDevice *acm) { for (int32_t i = 0; i < acm->interfaceCnt; i++) { - acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); // 获取UsbInterface接口对象 + // 获取UsbInterface接口对象 + acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); if (acm->iface[i] == NULL) { - HDF_LOGE("%s: interface%d is null", __func__, acm->interfaceIndex[i]); goto error; } } - acm->ctrIface = GetUsbInterfaceById((const struct AcmDevice *)acm, USB_CTRL_INTERFACE_ID); // 获取控制接口对应的UsbInterface接口对象 + // 获取控制接口对应的UsbInterface接口对象 + acm->ctrIface = GetUsbInterfaceById((const struct AcmDevice *)acm, USB_CTRL_INTERFACE_ID); if (acm->ctrIface == NULL) { - HDF_LOGE("%s: GetUsbInterfaceById null", __func__); goto error; } return HDF_SUCCESS; error: + // 根据acm->interfaceCnt循环释放接口对象 AcmReleaseInterfaces(acm); return HDF_FAILURE; } @@ -516,6 +735,7 @@ static void AcmCloseInterfaces(struct AcmDevice *acm) { for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->devHandle[i]) { + // 关闭一个USB设备对象 UsbCloseInterface(acm->devHandle[i]); acm->devHandle[i] = NULL; } @@ -530,49 +750,49 @@ static int32_t AcmOpenInterfaces(struct AcmDevice *acm) { for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { - acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); // 打开获取到的UsbInterface接口对象 + // 打开获取到的UsbInterface接口对象 + acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); if (acm->devHandle[i] == NULL) { - HDF_LOGE("%s: UsbOpenInterface null", __func__); goto error; } } } acm->ctrDevHandle = UsbOpenInterface(acm->ctrIface); if (acm->ctrDevHandle == NULL) { - HDF_LOGE("%s: ctrDevHandle UsbOpenInterface null", __func__); goto error; } return HDF_SUCCESS; error: + // 关闭所有UsbInterface接口对象 AcmCloseInterfaces(acm); return HDF_FAILURE; } static int32_t AcmGetPipes(struct AcmDevice *acm) { - acm->dataInPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_IN);// 获取dataInPipe的pipeInfo信息 + // 获取dataInPipe的pipeInfo信息 + acm->dataInPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_IN); if (acm->dataInPipe == NULL) { - HDF_LOGE("dataInPipe is NULL"); goto error; } - acm->dataOutPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_OUT);// 获取dataOutPipe的pipeInfo信息 + // 获取dataOutPipe的pipeInfo信息 + acm->dataOutPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_OUT); if (acm->dataOutPipe == NULL) { - HDF_LOGE("dataOutPipe is NULL"); goto error; } - acm->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT); // 获取控制pipe的pipeInfo信息 + // 获取控制pipe的pipeInfo信息 + acm->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT); if (acm->ctrPipe == NULL) { - HDF_LOGE("ctrPipe is NULL"); goto error; } - acm->intPipe = GetPipe(acm, USB_PIPE_TYPE_INTERRUPT, USB_PIPE_DIRECTION_IN);// 获取中断pipe的pipeInfo信息 + // 获取中断pipe的pipeInfo信息 + acm->intPipe = GetPipe(acm, USB_PIPE_TYPE_INTERRUPT, USB_PIPE_DIRECTION_IN); if (acm->intPipe == NULL) { - HDF_LOGE("intPipe is NULL"); goto error; } @@ -580,10 +800,10 @@ static int32_t AcmGetPipes(struct AcmDevice *acm) acm->writeSize = acm->dataOutPipe->maxPacketSize; acm->ctrlSize = acm->ctrPipe->maxPacketSize; acm->intSize = acm->intPipe->maxPacketSize; - return HDF_SUCCESS; error: + // 释放设备中所有的管道信息 AcmFreePipes(acm); return HDF_FAILURE; } @@ -605,29 +825,26 @@ static int32_t AcmAllocRequests(struct AcmDevice *acm) int32_t ret; if (AcmWriteBufAlloc(acm) < 0) { - HDF_LOGE("%s: AcmWriteBufAlloc failed", __func__); return HDF_ERR_MALLOC_FAIL; } for (int32_t i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &(acm->wb[i]); - snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); //分配待发送的IO Request对象 + // 分配待发送的IO Request对象 + snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); snd->instance = acm; if (snd->request == NULL) { - HDF_LOGE("%s:%d snd request failed", __func__, __LINE__); goto error_alloc_write_req; } } - ret = AcmAllocNotifyRequest(acm); // 分配并填充中断IO Request对象 + ret = AcmAllocNotifyRequest(acm); // 分配并填充中断IO Request对象 if (ret != HDF_SUCCESS) { - HDF_LOGE("%s:%d AcmAllocNotifyRequest failed", __func__, __LINE__); goto error_alloc_int_req; } - ret = AcmAllocReadRequests(acm); // 分配并填充readReq IO Request对象 + ret = AcmAllocReadRequests(acm); // 分配并填充readReq IO Request对象 if (ret) { - HDF_LOGE("%s:%d AcmAllocReadRequests failed", __func__, __LINE__); goto error_alloc_read_req; } @@ -648,57 +865,56 @@ static int32_t AcmInit(struct AcmDevice *acm) struct UsbSession *session = NULL; if (acm->initFlag == true) { - HDF_LOGE("%s:%d: initFlag is true", __func__, __LINE__); return HDF_SUCCESS; } - ret = UsbInitHostSdk(NULL); // 初始化Host DDK + // 初始化Host DDK + ret = UsbInitHostSdk(NULL); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: UsbInitHostSdk failed", __func__); return HDF_ERR_IO; } acm->session = session; + // 根据acm->interfaceIndex[i]分别获取UsbInterface接口对象 ret = AcmClaimInterfaces(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: AcmClaimInterfaces failed", __func__); goto error_claim_interfaces; } + // 根据acm->iface[i]分别打开UsbInterface接口对象 ret = AcmOpenInterfaces(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: AcmOpenInterfaces failed", __func__); goto error_open_interfaces; } + // 获取管道信息的指针 ret = AcmGetPipes(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: AcmGetPipes failed", __func__); goto error_get_pipes; } ret = AcmAllocRequests(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: AcmAllocRequests failed", __func__); goto error_alloc_reqs; } - acm->lineCoding.dwDTERate = CpuToLe32(DATARATE); - acm->lineCoding.bCharFormat = CHARFORMAT; + acm->lineCoding.dwDTERate = CpuToLe32(DATARATE); // 转换为小端数据 + acm->lineCoding.bCharFormat = CHARFORMAT; // 8 acm->lineCoding.bParityType = USB_CDC_NO_PARITY; acm->lineCoding.bDataBits = USB_CDC_1_STOP_BITS; acm->initFlag = true; - - HDF_LOGD("%s:%d========OK", __func__, __LINE__); return HDF_SUCCESS; error_alloc_reqs: AcmFreePipes(acm); error_get_pipes: + // 关闭所有UsbInterface接口对象 AcmCloseInterfaces(acm); error_open_interfaces: + // 释放所有UsbInterface接口对象 AcmReleaseInterfaces(acm); error_claim_interfaces: + // 在主机端退出USB DDK,acm->session代表指向会话上下文的指针 UsbExitHostSdk(acm->session); acm->session = NULL; return ret; @@ -707,7 +923,6 @@ error_claim_interfaces: static void AcmRelease(struct AcmDevice *acm) { if (acm->initFlag == false) { - HDF_LOGE("%s:%d: initFlag is false", __func__, __LINE__); return; } @@ -715,9 +930,9 @@ static void AcmRelease(struct AcmDevice *acm) AcmFreePipes(acm); AcmCloseInterfaces(acm); AcmReleaseInterfaces(acm); + // 在主机端退出USB DDK UsbExitHostSdk(acm->session); acm->session = NULL; - acm->initFlag = false; } @@ -727,15 +942,15 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%s: device is null", __func__); return HDF_ERR_INVALID_OBJECT; } acm = (struct AcmDevice *)device->service; + // 初始化互斥锁,&acm->readLock表示指向互斥量的指针 OsalMutexInit(&acm->readLock); OsalMutexInit(&acm->writeLock); - HDF_LOGD("%s:%d busNum=%d,devAddr=%d", - __func__, __LINE__, acm->busNum, acm->devAddr); + HDF_LOGD("%s:%d busNum=%d,devAddr=%d", __func__, __LINE__, acm->busNum, acm->devAddr); + // 给USB串口设备信息开辟空间并赋值 ret = UsbSerialDeviceAlloc(acm); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: Serial Device alloc failed", __func__); @@ -743,9 +958,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) acm->initFlag = false; g_acmReleaseFlag = false; - - HDF_LOGD("%s:%d init ok!", __func__, __LINE__); - return ret; } @@ -754,43 +966,40 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%s: device is NULL", __func__); return; } acm = (struct AcmDevice *)device->service; if (acm == NULL) { - HDF_LOGE("%s: acm is null", __func__); return; } g_acmReleaseFlag = true; if (acm->initFlag == true) { - HDF_LOGE("%s:%d AcmRelease", __func__, __LINE__); AcmRelease(acm); } + // 释放usb串口设备信息 UsbSeriaDevicelFree(acm); + // 释放互斥锁 OsalMutexDestroy(&acm->writeLock); OsalMutexDestroy(&acm->readLock); OsalMutexDestroy(&acm->lock); OsalMemFree(acm); acm = NULL; - HDF_LOGD("%s:%d exit", __func__, __LINE__); } +// 驱动的Bind、Init、及Release操作 struct HdfDriverEntry g_usbSerialDriverEntry = { .moduleVersion = 1, - .moduleName = "usbhost_acm", // 驱动模块名称,必须与hcs文件中配置的名称一致 + .moduleName = "usbhost_acm", // 驱动模块名称,必须与hcs文件中配置的名称一致 .Bind = UsbSerialDriverBind, .Init = UsbSerialDriverInit, .Release = UsbSerialDriverRelease, }; -HDF_INIT(g_usbSerialDriverEntry); +HDF_INIT(g_usbSerialDriverEntry); // 驱动入口 ``` - -### Host RAW API驱动开发 - +#### Host RAW API驱动开发 ```cpp root { @@ -851,7 +1060,7 @@ root { #include "hdf_log.h" #include "hdf_usb_pnp_manage.h" -#define HDF_LOG_TAG USB_HOST_ACM_RAW_API +#define HDF_LOG_TAG USB_HOST_ACM_RAW_API // 日志中可查寻的标签 #define USB_CTRL_REQ_SIZE 64 #define USB_IO_THREAD_STACK_SIZE 8192 #define USB_RAW_IO_SLEEP_MS_TIME 100 @@ -870,32 +1079,27 @@ static int32_t UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConf int32_t ret; if (devHandle == NULL) { - HDF_LOGE("%s:%d devHandle is NULL", - __func__, __LINE__); return HDF_ERR_INVALID_PARAM; } + // 获取主用设备配置 ret = UsbRawGetConfiguration(devHandle, &activeConfig); - if (ret) { - HDF_LOGE("%s:%d UsbRawGetConfiguration failed, ret=%d", - __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { return HDF_FAILURE; } - HDF_LOGE("%s:%d activeConfig=%d", __func__, __LINE__, activeConfig); + + // 根据指定的设备句柄获取设备指针 dev = UsbRawGetDevice(devHandle); if (dev == NULL) { - HDF_LOGE("%s:%d UsbRawGetDevice failed", - __func__, __LINE__); return HDF_FAILURE; } + // 根据指定的设备ID获取设备配置描述符 ret = UsbRawGetConfigDescriptor(dev, activeConfig, config); - if (ret) { - HDF_LOGE("UsbRawGetConfigDescriptor failed, ret=%dn", ret); - return HDF_FAILURE; + if (ret != HDF_SUCCESS) { + HDF_LOGE("UsbRawGetConfigDescriptor failed, ret=%d\n", ret); } - - return HDF_SUCCESS; + return ret; } ... static int32_t UsbAllocWriteRequests(struct AcmDevice *acm) @@ -904,10 +1108,10 @@ static int32_t UsbAllocWriteRequests(struct AcmDevice *acm) for (i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &acm->wb[i]; + // 分配一个具有指定数目的同步传输分组描述符的传输请求 snd->request = UsbRawAllocRequest(acm->devHandle, 0, acm->dataOutEp->maxPacketSize); snd->instance = acm; if (snd->request == NULL) { - HDF_LOGE("%s: UsbRawAllocRequest failed", __func__); return HDF_ERR_MALLOC_FAIL; } } @@ -923,17 +1127,14 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) errno_t err; if (device == NULL) { - HDF_LOGE("%s: device is null", __func__); return HDF_ERR_INVALID_OBJECT; } acm = (struct AcmDevice *)OsalMemCalloc(sizeof(*acm)); if (acm == NULL) { - HDF_LOGE("%s: Alloc usb serial device failed", __func__); return HDF_FAILURE; } if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) { - HDF_LOGE("%s:%d OsalMutexInit failed", __func__, __LINE__); goto error; } @@ -945,19 +1146,15 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES, (const void*)info->interfaceNumber, info->interfaceLength); if (err != EOK) { - HDF_LOGE("%s:%d memcpy_s failed err=%d", - __func__, __LINE__, err); goto lock_error; } } else { - HDF_LOGE("%s:%d info is NULL!", __func__, __LINE__); goto lock_error; } device->service = &(acm->service); device->service->Dispatch = UsbSerialDeviceDispatch; acm->device = device; - HDF_LOGD("UsbSerialDriverBind=========================OK"); return HDF_SUCCESS; lock_error: @@ -977,9 +1174,9 @@ static int32_t UsbAllocReadRequests(struct AcmDevice *acm) int32_t ret; for (int32_t i = 0; i < ACM_NR; i++) { + // 分配一个具有指定数目的同步传输分组描述符的传输请求 acm->readReq[i] = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->readReq[i]) { - HDF_LOGE("readReq request failed"); return HDF_ERR_MALLOC_FAIL; } @@ -990,10 +1187,9 @@ static int32_t UsbAllocReadRequests(struct AcmDevice *acm) reqData.timeout = USB_CTRL_SET_TIMEOUT; reqData.length = size; + // 在批量传输请求中填写所需信息 ret = UsbRawFillBulkRequest(acm->readReq[i], acm->devHandle, &reqData); - if (ret) { - HDF_LOGE("%s: FillBulkRequest failed, ret=%d n", - __func__, ret); + if (ret != HDF_SUCCESS) { return HDF_FAILURE; } } @@ -1007,9 +1203,9 @@ static int32_t UsbAllocNotifyRequest(struct AcmDevice *acm) int32_t size = acm->notifyEp->maxPacketSize; int32_t ret; + // 分配一个具有指定数目的同步传输分组描述符的传输请求 acm->notifyReq = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->notifyReq) { - HDF_LOGE("notifyReq request failed"); return HDF_ERR_MALLOC_FAIL; } @@ -1020,9 +1216,9 @@ static int32_t UsbAllocNotifyRequest(struct AcmDevice *acm) fillRequestData.userData = (void *)acm; fillRequestData.timeout = USB_CTRL_SET_TIMEOUT; + // 在中断传输请求中填充所需的信息 ret = UsbRawFillInterruptRequest(acm->notifyReq, acm->devHandle, &fillRequestData); - if (ret) { - HDF_LOGE("%s: FillInterruptRequest failed, ret=%d", __func__, ret); + if (ret != HDF_SUCCESS) { return HDF_FAILURE; } @@ -1036,62 +1232,55 @@ static int32_t UsbSerialInit(struct AcmDevice *acm) int32_t ret; if (acm->initFlag == true) { - HDF_LOGE("%s:%d: initFlag is true", __func__, __LINE__); return HDF_SUCCESS; } + // 以专家模式初始化USB DDK ret = UsbRawInit(NULL); - if (ret) { - HDF_LOGE("%s:%d UsbRawInit failed", __func__, __LINE__); + if (ret != HDF_SUCCESS) { return HDF_ERR_IO; } acm->session = session; + // 打开一个USB设备对象 devHandle = UsbRawOpenDevice(session, acm->busNum, acm->devAddr); if (devHandle == NULL) { - HDF_LOGE("%s:%d UsbRawOpenDevice failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_open_device; } acm->devHandle = devHandle; + // 获取主用设备配置、设备指针及配置描述符 ret = UsbGetConfigDescriptor(devHandle, &acm->config); - if (ret) { - HDF_LOGE("%s:%d UsbGetConfigDescriptor failed", __func__, __LINE__); + if (ret != HDF_SUCCESS) { ret = HDF_FAILURE; goto err_get_desc; } ret = UsbParseConfigDescriptor(acm, acm->config); if (ret != HDF_SUCCESS) { - HDF_LOGE("%s:%d UsbParseConfigDescriptor failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_parse_desc; } ret = AcmWriteBufAlloc(acm); if (ret < 0) { - HDF_LOGE("%s:%d AcmWriteBufAlloc failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_alloc_write_buf; } ret = UsbAllocWriteRequests(acm); if (ret < 0) { - HDF_LOGE("%s:%d UsbAllocWriteRequests failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_alloc_write_reqs; } ret = UsbAllocNotifyRequest(acm); if (ret) { - HDF_LOGE("%s:%d UsbAllocNotifyRequests failed", __func__, __LINE__); goto err_alloc_notify_req; } ret = UsbAllocReadRequests(acm); if (ret) { - HDF_LOGE("%s:%d UsbAllocReadRequests failed", __func__, __LINE__); goto err_alloc_read_reqs; } ret = UsbStartIo(acm); if (ret) { - HDF_LOGE("%s:%d UsbAllocReadRequests failed", __func__, __LINE__); goto err_start_io; } @@ -1102,18 +1291,14 @@ static int32_t UsbSerialInit(struct AcmDevice *acm) ret = UsbRawSubmitRequest(acm->notifyReq); if (ret) { - HDF_LOGE("%s:%d UsbRawSubmitRequest failed", __func__, __LINE__); goto err_submit_req; } acm->initFlag = true; - - HDF_LOGD("%s:%d=========================OK", __func__, __LINE__); - return HDF_SUCCESS; err_submit_req: - UsbStopIo(acm); + UsbStopIo(acm); // 停止IO线程并释放所有资源 err_start_io: UsbFreeReadRequests(acm); err_alloc_read_reqs: @@ -1128,9 +1313,9 @@ err_parse_desc: UsbRawFreeConfigDescriptor(acm->config); acm->config = NULL; err_get_desc: - (void)UsbRawCloseDevice(devHandle); + (void)UsbRawCloseDevice(devHandle); // 关闭USB设备对象 err_open_device: - UsbRawExit(acm->session); + UsbRawExit(acm->session); // 退出USB DDK的专家模式 return ret; } @@ -1138,7 +1323,6 @@ err_open_device: static void UsbSerialRelease(struct AcmDevice *acm) { if (acm->initFlag == false) { - HDF_LOGE("%s:%d: initFlag is false", __func__, __LINE__); return; } @@ -1156,6 +1340,7 @@ static void UsbSerialRelease(struct AcmDevice *acm) UsbReleaseInterfaces(acm); UsbRawFreeConfigDescriptor(acm->config); acm->config = NULL; + // 退出USB DDK的专家模式 UsbRawExit(acm->session); acm->initFlag = false; @@ -1167,7 +1352,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) int32_t ret; if (device == NULL) { - HDF_LOGE("%s:%d device is null", __func__, __LINE__); return HDF_ERR_INVALID_OBJECT; } acm = (struct AcmDevice *)device->service; @@ -1181,9 +1365,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) acm->initFlag = false; g_rawAcmReleaseFlag = false; - - HDF_LOGD("%s:%d init ok!", __func__, __LINE__); - return ret; } @@ -1191,20 +1372,17 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) { struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%s: device is NULL", __func__); return; } acm = (struct AcmDevice *)device->service; if (acm == NULL) { - HDF_LOGE("%s: acm is null", __func__); return; } g_rawAcmReleaseFlag = true; if (acm->initFlag == true) { - HDF_LOGE("%s:%d UsbSerialRelease", __func__, __LINE__); UsbSerialRelease(acm); } UsbSeriaDevicelFree(acm); @@ -1213,12 +1391,11 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) OsalMutexDestroy(&acm->lock); OsalMemFree(acm); acm = NULL; - HDF_LOGD("%s:%d exit", __func__, __LINE__); } struct HdfDriverEntry g_usbSerialRawDriverEntry = { .moduleVersion = 1, - .moduleName = "usbhost_acm_rawapi", //驱动模块名称,必须与hcs文件中配置的名称一致 + .moduleName = "usbhost_acm_rawapi", // 驱动模块名称,必须与hcs文件中配置的名称一致 .Bind = UsbSerialDriverBind, .Init = UsbSerialDriverInit, .Release = UsbSerialDriverRelease, @@ -1226,108 +1403,134 @@ struct HdfDriverEntry g_usbSerialRawDriverEntry = { HDF_INIT(g_usbSerialRawDriverEntry); ``` - -### Device DDK API驱动开发 +#### Device DDK API驱动开发 USB ACM设备核心代码路径为drivers\peripheral\usb\gadget\function\acm\cdcacm.c。其使用示例如下所示,首先根据描述符创建设备,然后获取接口,打开接口,获取Pipe信息,接收Event事件,接着进行USB通信(读写等),设备卸载时候,关闭接口,停止Event接收,删除设备。 -1、创建设备 -```cpp -static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, - struct DeviceResourceIface *iface) -{ - struct UsbFnDevice *fnDev = NULL; -struct UsbFnDescriptorData descData; -uint8_t useHcs; - ... -if (useHcs == 0) { - descData.type = USBFN_DESC_DATA_TYPE_DESC; - descData.descriptor = &g_masterFuncDevice; -} else { - descData.type = USBFN_DESC_DATA_TYPE_PROP; - descData.property = device->property; -} -/* 创建设备 */ - fnDev = (struct UsbFnDevice *)UsbFnDeviceCreate(acm->udcName, &descData); - if (fnDev == NULL) { - HDF_LOGE("%s: create usb function device failed", __func__); - return HDF_FAILURE; - } - ... -} -``` -2、获取接口,打开接口,获取Pipe信息 -```cpp -static int32_t AcmParseEachPipe(struct UsbAcmDevice *acm, struct UsbAcmInterface *iface) -{ - ... - for (i = 0; i < fnIface->info.numPipes; i++) { - struct UsbFnPipeInfo pipeInfo; -/* 获取pipe信息 */ - ret = UsbFnInterfaceGetPipeInfo(fnIface, i, &pipeInfo); +1. 创建设备。 + + ```cpp + static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, struct DeviceResourceIface *iface) + { + struct UsbFnDevice *fnDev = NULL; + struct UsbFnDescriptorData descData; + uint8_t useHcs; + ... + if (useHcs == 0) { // 描述符来自于代码中编码 + descData.type = USBFN_DESC_DATA_TYPE_DESC; + descData.descriptor = &g_masterFuncDevice; + } else { // 描述符来自于解析hcs文件 + descData.type = USBFN_DESC_DATA_TYPE_PROP; + descData.property = device->property; + } + /* 创建设备 */ + fnDev = (struct UsbFnDevice *)UsbFnDeviceCreate(acm->udcName, &descData); + if (fnDev == NULL) { + return HDF_FAILURE; + } ... } - return HDF_SUCCESS; -} -/* 获取接口,打开接口获取handle */ -static int32_t AcmParseEachIface(struct UsbAcmDevice *acm, struct UsbFnDevice *fnDev) -{ - ... - for (i = 0; i < fnDev->numInterfaces; i++) { - /* 获取接口 */ - fnIface = (struct UsbFnInterface *)UsbFnDeviceGetInterface(fnDev, i); + ``` + +2. 获取接口,打开接口,获取Pipe信息 + + ```cpp + static int32_t AcmParseEachPipe(struct UsbAcmDevice *acm, struct UsbAcmInterface *iface) + { ... - /* 打开接口 */ - handle = UsbFnInterfaceOpen(fnIface); + for (i = 0; i < fnIface->info.numPipes; i++) { + struct UsbFnPipeInfo pipeInfo; + /* 获取pipe信息 */ + ret = UsbFnInterfaceGetPipeInfo(fnIface, i, &pipeInfo); + ... + } + return HDF_SUCCESS; + } + /* 获取接口,打开接口获取handle */ + static int32_t AcmParseEachIface(struct UsbAcmDevice *acm, struct UsbFnDevice *fnDev) + { ... + for (i = 0; i < fnDev->numInterfaces; i++) { + /* 获取接口 */ + fnIface = (struct UsbFnInterface *)UsbFnGetInterface(fnDev, i); + ... + /* 打开接口 */ + handle = UsbFnInterfaceOpen(fnIface); + ... + } + return HDF_SUCCESS; } - return HDF_SUCCESS; -} -``` + ``` -3、接收Event事件 -```cpp -static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int32_t num) -{ - ... +3. 接收Event事件(EP0控制传输) + + ```cpp + static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int32_t num) + { + ... req = UsbFnCtrlRequestAlloc(acm->ctrlIface.handle, sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding)); - ... -} -static int32_t AcmDriverInit(struct HdfDeviceObject *device) -{ -... -/* 开始接收Event */ - ret = UsbFnInterfaceStartRecvEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm); - ... -} -``` -4、进行USB通信(读写等) -```cpp -static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, - uint16_t value, void *data, uint32_t length) -{ -... -/* 异步发送 */ - ret = UsbFnRequestSubmitAsync(req); - ... -} -``` -5、关闭接口,停止Event接收,删除设备 -```cpp -static int32_t AcmReleaseFuncDevice(struct UsbAcmDevice *acm) -{ -int32_t ret; -/* 关闭接口 */ - (void)UsbFnInterfaceClose(acm->ctrlIface.handle); -(void)UsbFnInterfaceClose(acm->dataIface.handle); -/* 停止接收Event */ -(void)UsbFnInterfaceStopRecvEvent(acm->ctrlIface.fn); -/* 删除设备 */ - ret = UsbFnDeviceRemove(acm->fnDev); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: remove usb function device failed", __func__); + ... } - return ret; -} -``` + static int32_t AcmDriverInit(struct HdfDeviceObject *device) + { + ... + /* 开始接收Event */ + ret = UsbFnInterfaceStartRecvEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm); + ... + } + ``` + +4. 进行USB通信(读写等) + + ```cpp + static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, + uint16_t value, void *data, uint32_t length) + { + ... + /* 异步发送 */ + ret = UsbFnRequestSubmitAsync(req); + ... + } + ``` + +5. 关闭接口,停止Event接收,删除设备 + + ```cpp + static int32_t AcmReleaseFuncDevice(struct UsbAcmDevice *acm) + { + int32_t ret; + /* 关闭接口 */ + (void)UsbFnInterfaceClose(acm->ctrlIface.handle); + (void)UsbFnInterfaceClose(acm->dataIface.handle); + /* 停止接收Event EP0控制传输 */ + (void)UsbFnInterfaceStopRecvEvent(acm->ctrlIface.fn); + /* 删除设备 */ + ret = UsbFnDeviceRemove(acm->fnDev); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: remove usb function device failed", __func__); + } + return ret; + } + ``` + +## 参考 + +- 代码仓库如下: + + **[drivers\_hdf\_core](https://gitee.com/openharmony/drivers_hdf_core)** + + [drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral) + + [drivers\_interface](https://gitee.com/openharmony/drivers_interface) + +- 代码路径如下: + + USB驱动模型liteos适配://drivers/hdf_core/adapter/khdf/liteos/model/usb + + USB DDK驱动加载实现://drivers/hdf_core/framework/model/usb + + USB HDI服务端实现://drivers/peripheral/usb/hdi_service + + USB HDI对外接口://out/{product_name}/gen/drivers/interface/usb/v1_0 + diff --git a/zh-cn/device-dev/driver/driver-platform-adc-des.md b/zh-cn/device-dev/driver/driver-platform-adc-des.md index 4be6d40457169e8ca9380806d4ba16a5a4bdd10d..d478bd0a69d0a4dfd188541e8139799eb0d7caf2 100755 --- a/zh-cn/device-dev/driver/driver-platform-adc-des.md +++ b/zh-cn/device-dev/driver/driver-platform-adc-des.md @@ -4,65 +4,61 @@ ### 功能简介 -ADC(Analog to Digital Converter),即模拟-数字转换器,是一种将模拟信号转换成对应数字信号的设备。 +ADC(Analog to Digital Converter),即模拟-数字转换器,可将模拟信号转换成对应的数字信号,便于存储与计算等操作。除电源线和地线之外,ADC只需要1根线与被测量的设备进行连接,其物理连线如图1: + +**图 1** ADC物理连线示意图 +![](figures/ADC物理连线示意图.png "ADC物理连线示意图") + +ADC接口定义了完成AD转换的通用方法集合,包括: -ADC接口定义了完成ADC传输的通用方法集合,包括: - ADC设备管理:打开或关闭ADC设备。 - ADC读取转换结果:读取AD转换结果。 ### 基本概念 -ADC主要用于将模拟量转换成数字量,从而便于存储与计算等。 - -ADC的主要技术参数有: - - 分辨率 + 分辨率指的是ADC模块能够转换的二进制位数,位数越多分辨率越高。 - 转换误差 + 转换误差通常是以输出误差的最大值形式给出。它表示A/D转换器实际输出的数字量和理论上的输出数字量之间的差别。常用最低有效位的倍数表示。 - 转换时间 + 转换时间是指A/D转换器从转换控制信号到来开始,到输出端得到稳定的数字信号所经过的时间。 ### 运作机制 在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),如果采用独立服务模式则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。ADC模块接口适配模式采用统一服务模式。 -ADC模块各分层的作用为:接口层提供打开设备,写入数据,关闭设备的接口。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其他具体的功能。 - -除电源线和地线之外,ADC只需要1根线与被测量的设备进行连接,其物理连线如[图1](#fig1)所示: - -**图 1** ADC物理连线示意图 -![](figures/ADC物理连线示意图.png "ADC物理连线示意图") - ### 约束与限制 -ADC模块当前仅支持轻量和小型系统内核(LiteOS) 。 +ADC模块仅支持轮询方式读取数据。 ## 使用指导 ### 场景介绍 -ADC设备通常用于将模拟电压转换为数字量,如与咪头搭配进行声音采集、与NTC电阻搭配进行温度测量,或者将其他模拟传感器的输出量转换为数字量的场景。 +ADC设备通常用于将模拟电压或电流转换为数字量,例如与NTC电阻搭配进行温度测量,或者将其他模拟传感器的输出量转换为数字量的场景。 ### 接口说明 -ADC模块提供的主要接口如[表1](#table1)所示,更多关于接口的介绍请参考对应的API接口文档。 +ADC模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/adc_if.h。 **表 1** ADC驱动API接口功能介绍 -| 接口名 | 描述 | +| 接口名 | 接口描述 | | -------- | ---------------- | -| AdcOpen | 打开ADC设备 | -| AdcClose | 关闭ADC设备 | -| AdcRead | 读取AD转换结果值 | +| DevHandle AdcOpen(uint32_t number) | 打开ADC设备 | +| void AdcClose(DevHandle handle) | 关闭ADC设备 | +| int32_t AdcRead(DevHandle handle, uint32_t channel, uint32_t \*val) | 读取AD转换结果值 | ### 开发步骤 -使用ADC设备的一般流程如[图2](#fig2)所示。 +使用ADC设备的一般流程如图2所示。 **图 2** ADC使用流程图 ![](figures/ADC使用流程图.png "ADC使用流程图") @@ -156,13 +152,11 @@ AdcClose(adcHandle); /* 关闭ADC设备 */ ### 使用实例 -本例程以操作开发板上的ADC设备为例,详细展示ADC接口的完整使用流程。 - -本例拟对Hi3516DV300某开发板上ADC设备进行简单的读取操作,基本硬件信息如下: +本例拟对Hi3516DV300开发板上ADC设备进行简单的读取操作,基本硬件信息如下: - SOC:hi3516dv300。 -- 原理图信息:电位器挂接在0号ADC设备1通道下。 +- 硬件连接:电位器挂接在0号ADC设备1通道下。 本例程对测试ADC进行连续读取操作,测试ADC功能是否正常。 @@ -173,16 +167,17 @@ AdcClose(adcHandle); /* 关闭ADC设备 */ #include "hdf_log.h" /* 标准日志打印头文件 */ /* 设备号0,通道号1 */ -#define ADC_DEVICE_NUM 0 +#define ADC_DEVICE_NUM 0 #define ADC_CHANNEL_NUM 1 +#define ADC_TEST_NUM 30 /* ADC例程总入口 */ static int32_t TestCaseAdc(void) { int32_t i; int32_t ret; - DevHandle adcHandle; - uint32_t readBuf[30] = {0}; + DevHandle adcHandle = NULL; + uint32_t readBuf[ADC_TEST_NUM] = {0}; /* 打开ADC设备 */ adcHandle = AdcOpen(ADC_DEVICE_NUM); @@ -192,7 +187,7 @@ static int32_t TestCaseAdc(void) } /* 连续进行30次AD转换并读取转换结果 */ - for (i = 0; i < 30; i++) { + for (i = 0; i < ADC_TEST_NUM; i++) { ret = AdcRead(adcHandle, ADC_CHANNEL_NUM, &readBuf[i]); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: ADC read fail!:%d", __func__, ret); diff --git a/zh-cn/device-dev/driver/driver-platform-adc-develop.md b/zh-cn/device-dev/driver/driver-platform-adc-develop.md index 00f17c7790ef4eccb41a75f97d94b9da3d0dff1c..21843636451da3b08f8d2d0cfaf437ee2da1bf8f 100755 --- a/zh-cn/device-dev/driver/driver-platform-adc-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-adc-develop.md @@ -1,40 +1,113 @@ # ADC - ## 概述 -ADC(Analog to Digital Converter),即模拟-数字转换器,是一种将模拟信号转换成对应数字信号的设备。在HDF框架中,ADC模块接口适配模式采用统一服务模式,这需要一个设备服务来作为ADC模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如ADC可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 +### 功能简介 - **图1** ADC统一服务 +ADC(Analog to Digital Converter),即模拟-数字转换器,是一种将模拟信号转换成对应数字信号的设备。 - ![image](figures/统一服务模式结构图.png "ADC统一服务模式结构图") +### 基本概念 +- 分辨率 -## 接口说明 + 分辨率指的是ADC模块能够转换的二进制位数,位数越多分辨率越高。 -AdcMethod定义: +- 转换误差 + 转换误差通常是以输出误差的最大值形式给出。它表示A/D转换器实际输出的数字量和理论上的输出数字量之间的差别。常用最低有效位的倍数表示。 -``` +- 转换时间 + + 转换时间是指A/D转换器从转换控制信号到来开始,到输出端得到稳定的数字信号所经过的时间。 + + +### 运作机制 + +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。ADC模块即采用统一服务模式(如图1)。 + +ADC模块各分层的作用为: + +- 接口层:提供打开设备,写入数据,关闭设备的能力。 +- 核心层:主要负责服务绑定、初始化以及释放管理器,并提供添加、删除以及获取控制器的能力。 +- 适配层:由驱动适配者实现与硬件相关的具体功能,如控制器的初始化等。 + +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 + +**图1** ADC统一服务模式结构图 +![image](figures/统一服务模式结构图.png "ADC统一服务模式结构图") + +## 使用指导 + +### 场景介绍 + +ADC设备通常用于将模拟电压转换为数字量,例如与NTC电阻搭配进行温度测量,或者将其他模拟传感器的输出量转换为数字量的场景。当驱动开发者需要将ADC设备适配到OpenHarmony时,需要进行ADC驱动适配,下文将介绍如何进行ADC驱动适配。 + +### 接口说明 + +为了保证上层在调用ADC接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/adc/adc_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 + +AdcMethod和AdcLockMethod定义: + +```c struct AdcMethod { - int32_t (*read)(struct AdcDevice *device, uint32_t channel, uint32_t *val); - int32_t (*start)(struct AdcDevice *device); - int32_t (*stop)(struct AdcDevice *device); + int32_t (*read)(struct AdcDevice *device, uint32_t channel, uint32_t *val); + int32_t (*start)(struct AdcDevice *device); + int32_t (*stop)(struct AdcDevice *device); }; + +struct AdcLockMethod { + int32_t (*lock)(struct AdcDevice *device); + void (*unlock)(struct AdcDevice *device); +}; + ``` - **表1** AdcMethod结构体成员的回调函数功能说明 +在适配层中,AdcMethod必须被实现,AdcLockMethod可根据实际情况考虑是否实现。核心层提供了默认的AdcLockMethod,其中使用Spinlock作为保护临界区的锁: + +```c +static int32_t AdcDeviceLockDefault(struct AdcDevice *device) +{ + if (device == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return OsalSpinLock(&device->spin); +} + +static void AdcDeviceUnlockDefault(struct AdcDevice *device) +{ + if (device == NULL) { + return; + } + (void)OsalSpinUnlock(&device->spin); +} + +static const struct AdcLockMethod g_adcLockOpsDefault = { + .lock = AdcDeviceLockDefault, + .unlock = AdcDeviceUnlockDefault, +}; + +``` + +若实际情况不允许使用Spinlock,驱动适配者可以考虑使用其他类型的锁来实现一个自定义的AdcLockMethod。一旦实现了自定义的AdcLockMethod,默认的AdcLockMethod将被覆盖。 + + **表1** AdcMethod结构体成员的钩子函数功能说明 | 函数成员 | 入参 | 出参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -------- | -| read | device:结构体指针,核心层ADC控制器
channel:uint32_t,传入的通道号 | val:uint32_t指针,要传出的信号数据 | HDF_STATUS相关状态 | 读取ADC采样的信号数据 | -| stop | device:结构体指针,核心层ADC控制器 | 无 | HDF_STATUS相关状态 | 关闭ADC设备 | -| start | device:结构体指针,核心层ADC控制器 | 无 | HDF_STATUS相关状态 | 开启ADC设备 | +| read | device:结构体指针,核心层ADC控制器
channel:uint32_t,传入的通道号 | val:uint32_t指针,要传出的信号数据 | HDF_STATUS相关状态 | 读取ADC采样的信号数据 | +| stop | device:结构体指针,核心层ADC控制器 | 无 | HDF_STATUS相关状态 | 关闭ADC设备 | +| start | device:结构体指针,核心层ADC控制器 | 无 | HDF_STATUS相关状态 | 开启ADC设备 | +**表2** AdcLockMethod结构体成员函数功能说明 + +| 函数成员 | 入参 | 出参 | 返回值 | 功能 | +| -------- | -------- | -------- | -------- | -------- | +| lock | device:结构体指针,核心层ADC设备对象。 | 无 | HDF_STATUS相关状态 | 获取临界区锁 | +| unlock | devicie:结构体指针,核心层ADC设备对象。 | 无 | HDF_STATUS相关状态 | 释放临界区锁 | -## 开发步骤 +### 开发步骤 -ADC模块适配必选的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +ADC模块适配必选的三个环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 @@ -44,20 +117,15 @@ ADC模块适配必选的三个环节是配置属性文件,实例化驱动入 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加adc_config.hcs器件属性文件。 -3. 实例化ADC控制器对象 +3. 实例化核心层接口函数 - 初始化AdcDevice成员。 - 实例化AdcDevice成员AdcMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化AdcDevice成员AdcMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. 驱动调试 +### 开发实例 - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,信号采集的成功与否等。 - - -## 开发实例 - - 接下来以adc_hi35xx.c为示例, 展示需要厂商提供哪些内容来完整实现设备功能。 + 接下来以Hi3516DV300的驱动//device/soc/hisilicon/common/platform/adc/adc_hi35xx.c为例, 展示需要驱动适配者提供哪些内容来完整实现设备功能。 1. 驱动开发首先需要实例化驱动入口。 @@ -69,128 +137,135 @@ ADC模块适配必选的三个环节是配置属性文件,实例化驱动入 ADC控制器会出现多个设备挂接的情况,因而在HDF框架中首先会为此类型的设备创建一个管理器对象。这样,需要打开某个设备时,管理器对象会根据指定参数查找到指定设备。 - ADC管理器的驱动由核心层实现,厂商不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的AdcDeviceAdd函数,它会实现相应功能。 - - - ``` - static struct HdfDriverEntry g_hi35xxAdcDriverEntry = { - .moduleVersion = 1, - .Init = Hi35xxAdcInit, - .Release = Hi35xxAdcRelease, - .moduleName = "hi35xx_adc_driver", //【必要且与HCS文件里面的名字匹配】 - }; - HDF_INIT(g_hi35xxAdcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 - - // 核心层adc_core.c管理器服务的驱动入口 - struct HdfDriverEntry g_adcManagerEntry = { - .moduleVersion = 1, - .Init = AdcManagerInit, - .Release = AdcManagerRelease, - .moduleName = "HDF_PLATFORM_ADC_MANAGER",// 这与device_info文件中device0对应 - }; - HDF_INIT(g_adcManagerEntry); - ``` - -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在adc_config.hcs中配置器件属性。 - - deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层AdcDevice相关成员的默认值或限制范围有密切关系。 - - 统一服务模式的特点是device_info文件中第一个设备节点必须为ADC管理器,其各项参数必须如下设置: - - - | 成员名 | 值 | - | -------- | -------- | - | moduleName | 固定为HDF_PLATFORM_ADC_MANAGER | - | serviceName | 无 | - | policy | 具体配置为0,不发布服务 | - | deviceMatchAttr | 没有使用,可忽略 | - - - 从第二个节点开始配置具体ADC控制器信息,此节点并不表示某一路ADC控制器,而是代表一个资源性质设备,用于描述一类ADC控制器的信息。本例只有一个ADC设备,如有多个设备,则需要在device_info文件增加deviceNode信息,以及在adc_config文件中增加对应的器件属性。 + ADC管理器的驱动由核心层实现,驱动适配者不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的AdcDeviceAdd函数,它会实现相应功能。 + + ```c + static struct HdfDriverEntry g_hi35xxAdcDriverEntry = { + .moduleVersion = 1, + .Init = Hi35xxAdcInit, + .Release = Hi35xxAdcRelease, + .moduleName = "hi35xx_adc_driver", //【必要且与device_info.hcs文件内的模块名匹配】 + }; + HDF_INIT(g_hi35xxAdcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + + /* 核心层adc_core.c管理器服务的驱动入口 */ + struct HdfDriverEntry g_adcManagerEntry = { + .moduleVersion = 1, + .Init = AdcManagerInit, + .Release = AdcManagerRelease, + .moduleName = "HDF_PLATFORM_ADC_MANAGER", // 这与device_info.hcs文件中device0对应 + }; + HDF_INIT(g_adcManagerEntry); + ``` + +2. 完成驱动入口注册之后,下一步请在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode信息,并在adc_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值对于驱动适配者的驱动实现以及核心层AdcDevice相关成员的默认值或限制范围有密切关系。 + + 统一服务模式的特点是device_info.hcs文件中第一个设备节点必须为ADC管理器,其各项参数必须如下设置: + + | 成员名 | 值 | + | -------- | -------- | + | moduleName | 固定为HDF_PLATFORM_ADC_MANAGER | + | serviceName | 无 | + | policy | 具体配置为0,不发布服务 | + | deviceMatchAttr | 没有使用,可忽略 | + + 从第二个节点开始配置具体ADC控制器信息,第一个节点并不表示某一路ADC控制器,而是代表一个资源性质设备,用于描述一类ADC控制器的信息。本例只有一个ADC设备,如有多个设备,则需要在device_info.hcs文件增加deviceNode信息,以及在adc_config文件中增加对应的器件属性。 - device_info.hcs配置参考 - - ``` + ```c root { device_info { - platform :: host { - device_adc :: device { - device0 :: deviceNode { - policy = 0; - priority = 50; - permission = 0644; - moduleName = "HDF_PLATFORM_ADC_MANAGER"; - serviceName = "HDF_PLATFORM_ADC_MANAGER"; - } - device1 :: deviceNode { - policy = 0; // 等于0,不需要发布服务。 - priority = 55; // 驱动启动优先级。 - permission = 0644; // 驱动创建设备节点权限。 - moduleName = "hi35xx_adc_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 - serviceName = "HI35XX_ADC_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 - deviceMatchAttr = "hisilicon_hi35xx_adc";//【必要】用于配置控制器私有数据,要与adc_config.hcs中对应控制器保持一致, - // 具体的控制器信息在adc_config.hcs中。 - } - } + platform :: host { + device_adc :: device { + device0 :: deviceNode { + policy = 0; + priority = 50; + permission = 0644; + moduleName = "HDF_PLATFORM_ADC_MANAGER"; + serviceName = "HDF_PLATFORM_ADC_MANAGER"; + } + device1 :: deviceNode { + policy = 0; // 等于0,不需要发布服务。 + priority = 55; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + moduleName = "hi35xx_adc_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HI35XX_ADC_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_adc"; //【必要】用于配置控制器私有数据,要与adc_config.hcs中对应控制器保持一致, + // 具体的控制器信息在adc_config.hcs中。 + } + } + } } - } } ``` + - adc_config.hcs配置参考 - - ``` + 此处以Hi3516DV300为例,给出HCS配置参考。其中部分字段为Hi3516DV300特有功能,驱动适配者可根据需要进行删除或添加字段。 + + ```c root { - platform { - adc_config_hi35xx { - match_attr = "hisilicon_hi35xx_adc"; - template adc_device { - regBasePhy = 0x120e0000;// 寄存器物理基地址 - regSize = 0x34; // 寄存器位宽 - deviceNum = 0; // 设备号 - validChannel = 0x1; // 有效通道 - dataWidth = 10; // 信号接收的数据位宽 - scanMode = 1; // 扫描模式 - delta = 0; // delta参数 - deglitch = 0; - glitchSample = 5000; - rate = 20000; - } - device_0 :: adc_device { - deviceNum = 0; - validChannel = 0x2; - } + platform { + adc_config_hi35xx { + match_attr = "hisilicon_hi35xx_adc"; + template adc_device { + regBasePhy = 0x120e0000; // 寄存器物理基地址 + regSize = 0x34; // 寄存器位宽 + deviceNum = 0; // 设备号 + validChannel = 0x1; // 有效通道 + dataWidth = 10; // AD转换后的数据位宽,即分辨率 + scanMode = 1; // 扫描模式 + delta = 0; // 转换结果误差范围 + deglitch = 0; // 滤毛刺开关 + glitchSample = 5000; // 滤毛刺时间窗口 + rate = 20000; // 转换速率 + } + device_0 :: adc_device { + deviceNum = 0; + validChannel = 0x2; + } + } } } - } ``` -3. 完成驱动入口注册之后,下一步就是以核心层AdcDevice对象的初始化为核心,包括初始化厂商自定义结构体(传递参数和数据),实例化AdcDevice成员AdcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + 需要注意的是,新增adc_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中adc_config.hcs所在路径为//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/adc/adc_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/adc/adc_config.hcs" // 配置文件相对路径 + ``` + + 本例基于Hi3516DV300开发板的小型系统LiteOS内核运行,对应的hdf.hcs文件路径为vendor/hisilicon/hispark_taurus/hdf_config/hdf.hcs以及//device/hisilicon/hispark_taurus/sdk_liteos/hdf_config/hdf.hcs。驱动适配者需根据实际情况选择对应路径下的文件进行修改。 + +3. 完成驱动入口注册之后,下一步就是以核心层AdcDevice对象的初始化为核心,包括初始化驱动适配者自定义结构体(传递参数和数据),实例化AdcDevice成员AdcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 - 自定义结构体参考。 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且adc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层AdcDevice对象,例如设备号、总线号等。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且adc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,其中一些重要数值(例如设备号、总线号等)也会传递给核心层AdcDevice对象。 - - ``` + ```c struct Hi35xxAdcDevice { - struct AdcDevice device; //【必要】是核心层控制对象,具体描述见下面。 - volatile unsigned char *regBase;//【必要】寄存器基地址 + struct AdcDevice device; //【必要】是核心层控制对象,必须作为自定义结构体的首个成员,其具体描述见下方。 + volatile unsigned char *regBase; //【必要】寄存器基地址 volatile unsigned char *pinCtrlBase; - uint32_t regBasePhy; //【必要】寄存器物理基地址 - uint32_t regSize; //【必要】寄存器位宽 - uint32_t deviceNum; //【必要】设备号 - uint32_t dataWidth; //【必要】信号接收的数据位宽 - uint32_t validChannel; //【必要】有效通道 - uint32_t scanMode; //【必要】扫描模式 + uint32_t regBasePhy; //【必要】寄存器物理基地址 + uint32_t regSize; //【必要】寄存器位宽 + uint32_t deviceNum; //【必要】设备号 + uint32_t dataWidth; //【必要】信号接收的数据位宽 + uint32_t validChannel; //【必要】有效通道 + uint32_t scanMode; //【必要】扫描模式 uint32_t delta; uint32_t deglitch; uint32_t glitchSample; - uint32_t rate; //【必要】采样率 + uint32_t rate; //【必要】采样率 }; - // AdcDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + /* AdcDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值。*/ struct AdcDevice { const struct AdcMethod *ops; OsalSpinlock spin; @@ -201,50 +276,50 @@ ADC模块适配必选的三个环节是配置属性文件,实例化驱动入 }; ``` - - AdcDevice成员回调函数结构体AdcMethod的实例化。 + - AdcDevice成员钩子函数结构体AdcMethod的实例化。 - AdcLockMethod回调函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 + AdcLockMethod钩子函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 - - ``` + ```c static const struct AdcMethod g_method = { .read = Hi35xxAdcRead, .stop = Hi35xxAdcStop, .start = Hi35xxAdcStart, }; ``` - - Init函数参考 + + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 - | 状态(值) | 问题描述 | + | 状态(值) | 问题描述 | | -------- | -------- | - | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | - | HDF_ERR_INVALID_PARAM | 参数非法 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_IO | I/O错误 | - | HDF_SUCCESS | 传输成功 | - | HDF_FAILURE | 传输失败 | + | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | + | HDF_ERR_INVALID_PARAM | 参数非法 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_IO | I/O错误 | + | HDF_SUCCESS | 传输成功 | + | HDF_FAILURE | 传输失败 | 函数说明: - 初始化自定义结构体对象,初始化AdcDevice成员,并调用核心层AdcDeviceAdd函数。 + 初始化自定义结构体对象,初始化AdcDevice成员,并调用核心层AdcDeviceAdd函数。 - ``` + ```c static int32_t Hi35xxAdcInit(struct HdfDeviceObject *device) { int32_t ret; struct DeviceResourceNode *childNode = NULL; ... - // 遍历、解析adc_config.hcs中的所有配置节点,并分别调用Hi35xxAdcParseInit函数来初始化device。 + /* 遍历、解析adc_config.hcs中的所有配置节点,并分别调用Hi35xxAdcParseInit函数来初始化device。*/ DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { - ret = Hi35xxAdcParseInit(device, childNode);// 函数定义见下 + ret = Hi35xxAdcParseInit(device, childNode); // 函数定义见下方 ... } return ret; @@ -252,43 +327,70 @@ ADC模块适配必选的三个环节是配置属性文件,实例化驱动入 static int32_t Hi35xxAdcParseInit(struct HdfDeviceObject *device, struct DeviceResourceNode *node) { - int32_t ret; - struct Hi35xxAdcDevice *hi35xx = NULL; //【必要】自定义结构体对象 - (void)device; - - hi35xx = (struct Hi35xxAdcDevice *)OsalMemCalloc(sizeof(*hi35xx)); //【必要】内存分配 - ... - ret = Hi35xxAdcReadDrs(hi35xx, node); //【必要】将adc_config文件的默认值填充到结构体中 - ... - hi35xx->regBase = OsalIoRemap(hi35xx->regBasePhy, hi35xx->regSize);//【必要】地址映射 - ... - hi35xx->pinCtrlBase = OsalIoRemap(HI35XX_ADC_IO_CONFIG_BASE, HI35XX_ADC_IO_CONFIG_SIZE); - ... - Hi35xxAdcDeviceInit(hi35xx); //【必要】ADC设备的初始化 - hi35xx->device.priv = (void *)node; //【必要】存储设备属性 - hi35xx->device.devNum = hi35xx->deviceNum;//【必要】初始化AdcDevice成员 - hi35xx->device.ops = &g_method; //【必要】AdcMethod的实例化对象的挂载 - ret = AdcDeviceAdd(&hi35xx->device); //【必要且重要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 - ... - return HDF_SUCCESS; + int32_t ret; + struct Hi35xxAdcDevice *hi35xx = NULL; //【必要】自定义结构体对象 + (void)device; + + hi35xx = (struct Hi35xxAdcDevice *)OsalMemCalloc(sizeof(*hi35xx)); //【必要】内存分配 + ... + ret = Hi35xxAdcReadDrs(hi35xx, node); //【必要】将adc_config文件的默认值填充到结构体中,函数定义见下方 + ... + hi35xx->regBase = OsalIoRemap(hi35xx->regBasePhy, hi35xx->regSize); //【必要】地址映射 + ... + hi35xx->pinCtrlBase = OsalIoRemap(HI35XX_ADC_IO_CONFIG_BASE, HI35XX_ADC_IO_CONFIG_SIZE); + ... + Hi35xxAdcDeviceInit(hi35xx); //【必要】ADC设备的初始化 + hi35xx->device.priv = (void *)node; //【必要】存储设备属性 + hi35xx->device.devNum = hi35xx->deviceNum; //【必要】初始化AdcDevice成员 + hi35xx->device.ops = &g_method; //【必要】AdcMethod的实例化对象的挂载 + ret = AdcDeviceAdd(&hi35xx->device); //【必要且重要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 + ... + return HDF_SUCCESS; __ERR__: - if (hi35xx != NULL) { // 不成功的话,需要反向执行初始化相关函数。 - if (hi35xx->regBase != NULL) { - OsalIoUnmap((void *)hi35xx->regBase); - hi35xx->regBase = NULL; + if (hi35xx != NULL) { // 若不成功,需要执行去初始化相关函数。 + if (hi35xx->regBase != NULL) { + OsalIoUnmap((void *)hi35xx->regBase); + hi35xx->regBase = NULL; + } + AdcDeviceRemove(&hi35xx->device); + OsalMemFree(hi35xx); } - AdcDeviceRemove(&hi35xx->device); - OsalMemFree(hi35xx); + return ret; } - return ret; + + static int32_t Hi35xxAdcReadDrs(struct Hi35xxAdcDevice *hi35xx, const struct DeviceResourceNode *node) + { + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + + /* 获取drsOps方法 */ + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL) { + HDF_LOGE("%s: invalid drs ops", __func__); + return HDF_ERR_NOT_SUPPORT; + } + /* 将配置参数依次读出,并填充至结构体中 */ + ret = drsOps->GetUint32(node, "regBasePhy", &hi35xx->regBasePhy, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read regBasePhy failed", __func__); + return ret; + } + ret = drsOps->GetUint32(node, "regSize", &hi35xx->regSize, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read regSize failed", __func__); + return ret; + } + ··· + return HDF_SUCCESS; } ``` - - Release函数参考 + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -298,41 +400,38 @@ ADC模块适配必选的三个环节是配置属性文件,实例化驱动入 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
- > 所有强制转换获取相应对象的操作的前提是在Init函数中具备对应赋值的操作。 - - - ``` + ```c static void Hi35xxAdcRelease(struct HdfDeviceObject *device) { - const struct DeviceResourceNode *childNode = NULL; - ... - // 遍历、解析adc_config.hcs中的所有配置节点,并分别进行Release操作。 - DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { - Hi35xxAdcRemoveByNode(childNode);// 函数定义见下 - } + const struct DeviceResourceNode *childNode = NULL; + ... + /* 遍历、解析adc_config.hcs中的所有配置节点,并分别进行Release操作。*/ + DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { + Hi35xxAdcRemoveByNode(childNode);// 函数定义见下 + } } static void Hi35xxAdcRemoveByNode(const struct DeviceResourceNode *node) { - int32_t ret; - int32_t deviceNum; - struct AdcDevice *device = NULL; - struct Hi35xxAdcDevice *hi35xx = NULL; - struct DeviceResourceIface *drsOps = NULL; - - drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); - ... - ret = drsOps->GetUint32(node, "deviceNum", (uint32_t *)&deviceNum, 0); - ... - // 可以调用AdcDeviceGet函数通过设备的deviceNum获取AdcDevice对象,以及调用AdcDeviceRemove函数来释放AdcDevice对象的内容。 - device = AdcDeviceGet(deviceNum); - if (device != NULL && device->priv == node) { - AdcDevicePut(device); - AdcDeviceRemove(device); //【必要】主要是从管理器驱动那边移除AdcDevice对象 - hi35xx = (struct Hi35xxAdcDevice *)device;//【必要】通过强制转换获取自定义的对象并进行Release操作 - OsalIoUnmap((void *)hi35xx->regBase); - OsalMemFree(hi35xx); + int32_t ret; + int32_t deviceNum; + struct AdcDevice *device = NULL; + struct Hi35xxAdcDevice *hi35xx = NULL; + struct DeviceResourceIface *drsOps = NULL; + + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + ... + ret = drsOps->GetUint32(node, "deviceNum", (uint32_t *)&deviceNum, 0); + ... + /* 可以调用AdcDeviceGet函数通过设备的deviceNum获取AdcDevice对象,以及调用AdcDeviceRemove函数来释放AdcDevice对象的内容。*/ + device = AdcDeviceGet(deviceNum); + if (device != NULL && device->priv == node) { + AdcDevicePut(device); + AdcDeviceRemove(device); //【必要】主要是从管理器驱动那边移除AdcDevice对象。 + hi35xx = (struct Hi35xxAdcDevice *)device; //【必要】通过强制转换获取自定义的对象并进行Release操作。这一步的前提是device必须作为自定义结构体的首个成员。 + OsalIoUnmap((void *)hi35xx->regBase); + OsalMemFree(hi35xx); + } + return; } - return ``` diff --git a/zh-cn/device-dev/driver/driver-platform-dac-des.md b/zh-cn/device-dev/driver/driver-platform-dac-des.md index 7238d1453b8db78e43bd1227841de29a62d0c582..4f4e4b47f12e04e5559af1794dc0ac2dde1e2b4b 100644 --- a/zh-cn/device-dev/driver/driver-platform-dac-des.md +++ b/zh-cn/device-dev/driver/driver-platform-dac-des.md @@ -4,7 +4,10 @@ ### 功能简介 -DAC(Digital to Analog Converter)是一种通过电流、电压或电荷的形式将数字信号转换为模拟信号的设备。 +DAC(Digital to Analog Converter)是一种通过电流、电压或电荷的形式将数字信号转换为模拟信号的设备,主要用于: + +- 作为过程控制计算机系统的输出通道,与执行器相连,实现对生产过程的自动控制。 +- 在利用反馈技术的模数转换器设计中,作为重要的功能模块呈现。 DAC接口定义了完成DAC传输的通用方法集合,包括: - DAC设备管理:打开或关闭DAC设备。 @@ -12,11 +15,6 @@ DAC接口定义了完成DAC传输的通用方法集合,包括: ### 基本概念 -DAC模块支持数模转换的开发,它主要用于: - -1. 作为过程控制计算机系统的输出通道,与执行器相连,实现对生产过程的自动控制。 -2. 在利用反馈技术的模数转换器设计中,作为重要的功能模块呈现。 - - 分辨率 分辨率指的是DAC模块能够转换的二进制位数,位数越多分辨率越高。 @@ -35,7 +33,7 @@ DAC模块支持数模转换的开发,它主要用于: ### 运作机制 -在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),如果采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。DAC模块接口适配模式采用统一服务模式,如图1所示。 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),如果采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。DAC模块接口适配模式采用统一服务模式(如图1)。 DAC模块各分层的作用为:接口层提供打开设备、写入数据和关闭设备的接口。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其它具体的功能。 @@ -47,7 +45,7 @@ DAC模块各分层的作用为:接口层提供打开设备、写入数据和 ### 约束与限制 -DAC模块当前仅支持轻量和小型系统内核(LiteOS)。 +DAC模块当前仅支持轻量和小型系统内核(LiteOS-A)。 ## 使用指导 @@ -57,11 +55,11 @@ DAC模块的主要工作是以电流、电压或电荷的形式将数字信号 ### 接口说明 -DAC模块提供的主要接口如下所示,更多关于接口的介绍请参考对应的API接口文档。 +DAC模块提供的主要接口如下所示,具体API详见//drivers/hdf_core/framework/include/platform/dac_if.h。 **表 1** DAC驱动API接口功能介绍 -| 接口名 | 描述 | +| 接口名 | 接口描述 | | ------------------------------------------------------------------ | ------------ | | DevHandle DacOpen(uint32_t number) | 打开DAC设备。 | | void DacClose(DevHandle handle) | 关闭DAC设备。 | @@ -94,7 +92,7 @@ DevHandle DacOpen(uint32_t number); 假设系统中存在2个DAC设备,编号从0到1,现在打开1号设备。 ```c++ -DevHandle dacHandle = NULL; /* DAC设备句柄 / +DevHandle dacHandle = NULL; // DAC设备句柄 /* 打开DAC设备 */ dacHandle = DacOpen(1); @@ -123,12 +121,12 @@ int32_t DacWrite(DevHandle handle, uint32_t channel, uint32_t val); ```c++ /* 通过DAC_CHANNEL_NUM设备通道写入目标val值 */ - ret = DacWrite(dacHandle, DAC_CHANNEL_NUM, val); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: tp DAC write reg fail!:%d", __func__, ret); - DacClose(dacHandle); - return -1; - } +ret = DacWrite(dacHandle, DAC_CHANNEL_NUM, val); +if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: tp DAC write reg fail!:%d", __func__, ret); + DacClose(dacHandle); + return -1; +} ``` #### 关闭DAC设备 diff --git a/zh-cn/device-dev/driver/driver-platform-dac-develop.md b/zh-cn/device-dev/driver/driver-platform-dac-develop.md index 54b624b17ef8eb16385e4b2ecea4ce4e7c39b910..b2d5bfb0cb57d7910bbdc5dc26a616b24c569f26 100644 --- a/zh-cn/device-dev/driver/driver-platform-dac-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-dac-develop.md @@ -9,7 +9,7 @@ DAC(Digital to Analog Converter)是一种通过电流、电压或电荷的 DAC模块支持数模转换的开发。它主要用于: - 作为过程控制计算机系统的输出通道,与执行器相连,实现对生产过程的自动控制。 -- 在利用反馈技术的魔术转换器设计中,作为重要的功能模块呈现。 +- 在利用反馈技术的模数转换器设计中,作为重要的功能模块呈现。 ### 基本概念 @@ -31,44 +31,82 @@ DAC模块支持数模转换的开发。它主要用于: ### 运作机制 -在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。DAC模块接口适配模式采用统一服务模式(如图1所示)。 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。DAC模块即采用统一服务模式(如图1)。 -DAC模块各分层的作用为:接口层提供打开设备、写入数据和关闭设备接口的能力。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其他具体的功能。 +DAC模块各分层的作用为: +- 接口层:提供打开设备、写入数据和关闭设备接口的能力。 +- 核心层:主要提供绑定设备、初始化设备以及释放设备的能力。 +- 适配层:由驱动适配者实现与硬件相关的具体功能,如控制器的初始化等。 + +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 ![](../public_sys-resources/icon-note.gif) 说明:
核心层可以调用接口层的函数,也可以通过钩子函数调用适配层函数,从而使得适配层间接的可以调用接口层函数,但是不可逆转接口层调用适配层函数。 -**图 1** 统一服务模式 +**图 1** 统一服务模式结构图 ![](figures/统一服务模式结构图.png "DAC统一服务模式") ### 约束与限制 -DAC模块当前仅支持轻量和小型系统内核(LiteOS)。 +DAC模块当前仅支持轻量和小型系统内核(LiteOS-A)。 ## 开发指导 ### 场景介绍 -DAC模块主要在设备中数模转换、音频输出和电机控制等设备使用,设置将DAC模块传入的数字信号转换为输出模拟信号时需要用到DAC数模转换驱动。 +DAC模块主要在设备中数模转换、音频输出和电机控制等设备使用,设置将DAC模块传入的数字信号转换为输出模拟信号时需要用到DAC数模转换驱动。当驱动开发者需要将DAC设备适配到OpenHarmony时,需要进行DAC驱动适配,下文将介绍如何进行DAC驱动适配。 ### 接口说明 -通过以下DacMethod中的函数调用DAC驱动对应的函数。 +为了保证上层在调用DAC接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/dac/dac_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 -DacMethod定义: +DacMethod和DacLockMethod定义: ```c++ struct DacMethod { - // 写入数据的钩子函数 + /* 写入数据的钩子函数 */ int32_t (*write)(struct DacDevice *device, uint32_t channel, uint32_t val); - // 启动DAC设备的钩子函数 + /* 启动DAC设备的钩子函数 */ int32_t (*start)(struct DacDevice *device); - // 停止DAC设备的钩子函数 + /* 停止DAC设备的钩子函数 */ int32_t (*stop)(struct DacDevice *device); }; + +struct DacLockMethod { + int32_t (*lock)(struct DacDevice *device); + void (*unlock)(struct DacDevice *device); +}; ``` +在适配层中,DacMethod必须被实现,DacLockMethod可根据实际情况考虑是否实现。核心层提供了默认的DacLockMethod,其中使用Spinlock作为保护临界区的锁: + +```c +static int32_t DacDeviceLockDefault(struct DacDevice *device) +{ + if (device == NULL) { + HDF_LOGE("%s: device is null", __func__); + return HDF_ERR_INVALID_OBJECT; + } + return OsalSpinLock(&device->spin); +} + +static void DacDeviceUnlockDefault(struct DacDevice *device) +{ + if (device == NULL) { + HDF_LOGE("%s: device is null", __func__); + return; + } + (void)OsalSpinUnlock(&device->spin); +} + +static const struct DacLockMethod g_dacLockOpsDefault = { + .lock = DacDeviceLockDefault, + .unlock = DacDeviceUnlockDefault, +}; +``` + +若实际情况不允许使用Spinlock,驱动适配者可以考虑使用其他类型的锁来实现一个自定义的DacLockMethod。一旦实现了自定义的DacLockMethod,默认的DacLockMethod将被覆盖。 -**表 1** DacMethod结构体成员的回调函数功能说明 +**表 1** DacMethod结构体成员的钩子函数功能说明 | 函数成员 | 入参 | 出参 | 返回值 | 功能 | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -------------- | @@ -76,6 +114,14 @@ struct DacMethod { | start | device:结构体指针,核心层DAC控制器 | 无 | HDF_STATUS相关状态 | 开启DAC设备 | | stop | device:结构体指针,核心层DAC控制器 | 无 | HDF_STATUS相关状态 | 关闭DAC设备 | +**表2** DacLockMethod结构体成员函数功能说明 + +| 函数成员 | 入参 | 出参 | 返回值 | 功能 | +| -------- | -------- | -------- | -------- | -------- | +| lock | device:结构体指针,核心层DAC设备对象。 | 无 | HDF_STATUS相关状态 | 获取临界区锁 | +| unlock | devicie:结构体指针,核心层DAC设备对象。 | 无 | HDF_STATUS相关状态 | 释放临界区锁 | + + ### 开发步骤 DAC模块适配包含以下四个步骤: @@ -87,11 +133,11 @@ DAC模块适配包含以下四个步骤: ### 开发实例 -下方将展示厂商需要提供哪些内容来完整实现设备功能。 +下方将Hi3516DV300的驱动//device/soc/hisilicon/common/platform/dac/dac_hi35xx.c为例,展示驱动适配者需要提供哪些内容来完整实现设备功能。 1. 实例化驱动入口: - 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会汇总所有加载的驱动的HdfDriverEntry对象入口,形成一个类似数组的段地址空间,方便上层调用。 + 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs中保持一致。HDF框架会汇总所有加载的驱动的HdfDriverEntry对象入口,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 @@ -101,15 +147,15 @@ DAC模块适配包含以下四个步骤: .Init = VirtualDacInit, .Release = VirtualDacRelease, .moduleName = "virtual_dac_driver", //【必要且与HCS里面的名字匹配】 - }; - HDF_INIT(g_dacDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + }; + HDF_INIT(g_dacDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` 2. 配置属性文件: - - 在vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + - 添加//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs器件属性文件。 - 器件属性值对于厂商驱动的实现以及核心层DacDevice相关成员的默认值或限制范围有密切关系,比如设备通道的个数以及传输速率的最大值,会影响DacDevice相关成员的默认值。 + 器件属性值对于驱动适配者的驱动实现以及核心层DacDevice相关成员的默认值或限制范围有密切关系,比如设备通道的个数以及传输速率的最大值,会影响DacDevice相关成员的默认值。 由于采用了统一服务模式,device_info.hcs文件中第一个设备节点必须为DAC管理器,其各项参数必须如下设置: @@ -122,14 +168,14 @@ DAC模块适配包含以下四个步骤: | serviceName | 固定为HDF_PLATFORM_DAC_MANAGER | | deviceMatchAttr | 没有使用,可忽略 | - 从第二个节点开始配置具体DAC控制器信息,此节点并不表示某一路DAC控制器,而是代表一个资源性质设备,用于描述一类DAC控制器的信息。本例只有一个DAC设备,如有多个设备,则需要在device_info文件增加deviceNode信息,以及在dac_config文件中增加对应的器件属性。 + 从第二个节点开始配置具体DAC控制器信息,此节点并不表示某一路DAC控制器,而是代表一个资源性质设备,用于描述一类DAC控制器的信息。本例只有一个DAC设备,如有多个设备,则需要在device_info.hcs文件增加deviceNode信息,以及在dac_config.hcs文件中增加对应的器件属性。 device_info.hcs配置参考: ```hcs root { device_dac :: device { - // device0是DAC管理器 + /* device0是DAC管理器 */ device0 :: deviceNode { policy = 0; priority = 52; @@ -138,7 +184,7 @@ DAC模块适配包含以下四个步骤: moduleName = "HDF_PLATFORM_DAC_MANAGER"; } } - // dac_virtual是DAC控制器 + /* dac_virtual是DAC控制器 */ dac_virtual :: deviceNode { policy = 0; priority = 56; @@ -152,7 +198,7 @@ DAC模块适配包含以下四个步骤: - 添加dac_test_config.hcs器件属性文件。 - 在vendor/vendor_hisilicon/hispark_taurus/hdf_config/hdf_test/xxx_test_config.hcs目录下新增文件用于驱动配置参数,(例如:vendor/vendor_hisilicon/hispark_taurus/hdf_config/hdf_test/dac_test_config.hcs)其中配置参数如下: + 在具体产品对应目录下新增文件用于驱动配置参数(例如hispark_taurus开发板:vendor/hisilicon/hispark_taurus/hdf_config/hdf_test/dac_test_config.hcs),其中配置参数如下: ```hcs root { @@ -173,6 +219,14 @@ DAC模块适配包含以下四个步骤: } ``` + 需要注意的是,新增dac_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中dac_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/dac/dac_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/dac/dac_config.hcs" // 配置文件相对路径 + ``` + 3. 实例化核心层接口函数: - 初始化DacDevice成员。 @@ -180,59 +234,59 @@ DAC模块适配包含以下四个步骤: 在VirtualDacParseAndInit函数中对DacDevice成员进行初始化操作。 ```c++ - // 虚拟驱动自定义结构体 + /* 虚拟驱动自定义结构体 */ struct VirtualDacDevice { - // DAC设备结构体 + /*DAC设备结构体 */ struct DacDevice device; - // DAC设备号 + /* DAC设备号 */ uint32_t deviceNum; - // 有效通道 + /* 有效通道 */ uint32_t validChannel; - // DAC速率 + /* DAC速率 */ uint32_t rate; }; - // 解析并且初始化核心层DacDevice对象 + /* 解析并且初始化核心层DacDevice对象 */ static int32_t VirtualDacParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) { - // 定义返回值 + /* 定义返回值 */ int32_t ret; - // DAC设备虚拟指针 + /* DAC设备虚拟指针 */ struct VirtualDacDevice *virtual = NULL; (void)device; - // 给virtual指针开辟空间 + /* 给virtual指针开辟空间 */ virtual = (struct VirtualDacDevice *)OsalMemCalloc(sizeof(*virtual)); if (virtual == NULL) { - // 为空则返回错误参数 + /*为空则返回错误参数 */ HDF_LOGE("%s: Malloc virtual fail!", __func__); return HDF_ERR_MALLOC_FAIL; } - // 读取属性文件配置参数 + /* 读取属性文件配置参数 */ ret = VirtualDacReadDrs(virtual, node); if (ret != HDF_SUCCESS) { - // 读取失败 + /* 读取失败 */ HDF_LOGE("%s: Read drs fail! ret:%d", __func__, ret); - // 释放virtual空间 + /* 释放virtual空间 */ OsalMemFree(virtual); - // 指针置为0 + /* 指针置为0 */ virtual = NULL; return ret; } - // 初始化虚拟指针 + /* 初始化虚拟指针 */ VirtualDacDeviceInit(virtual); - // 对DacDevice中priv对象初始化 + /* 对DacDevice中priv对象初始化 */ virtual->device.priv = (void *)node; - // 对DacDevice中devNum对象初始化 + /* 对DacDevice中devNum对象初始化 */ virtual->device.devNum = virtual->deviceNum; - // 对DacDevice中ops对象初始化 + /* 对DacDevice中ops对象初始化 */ virtual->device.ops = &g_method; - // 添加DAC设备 + /* 添加DAC设备 */ ret = DacDeviceAdd(&virtual->device); if (ret != HDF_SUCCESS) { - // 添加设备失败 + /* 添加设备失败 */ HDF_LOGE("%s: add Dac controller failed! ret = %d", __func__, ret); - // 释放virtual空间 + /* 释放virtual空间 */ OsalMemFree(virtual); - // 虚拟指针置空 + /* 虚拟指针置空 */ virtual = NULL; return ret; } @@ -253,7 +307,7 @@ DAC模块适配包含以下四个步骤: uint32_t rate; //【必要】采样率 }; - // DacDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + /* DacDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值。 */ struct DacDevice { const struct DacMethod *ops; OsalSpinlock spin; // 自旋锁 @@ -279,15 +333,15 @@ DAC模块适配包含以下四个步骤: ![](../public_sys-resources/icon-note.gif) **说明:**
DacDevice成员DacMethod的定义和成员说明见[接口说明](#接口说明)。 - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject这个是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 | 状态(值) | 问题描述 | | ---------------------- | ------------- | @@ -305,48 +359,48 @@ DAC模块适配包含以下四个步骤: ```c++ static int32_t VirtualDacParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) { - // 定义返回值参数 + /* 定义返回值参数 */ int32_t ret; - // DAC设备的结构体指针 + /* DAC设备的结构体指针 */ struct VirtualDacDevice *virtual = NULL; (void)device; - // 分配指定大小的内存 + /* 分配指定大小的内存 */ virtual = (struct VirtualDacDevice *)OsalMemCalloc(sizeof(*virtual)); if (virtual == NULL) { - // 分配内存失败 + /* 分配内存失败 */ HDF_LOGE("%s: Malloc virtual fail!", __func__); return HDF_ERR_MALLOC_FAIL; } - // 读取hcs中的node节点参数 + /* 读取hcs中的node节点参数,函数定义见下方 */ ret = VirtualDacReadDrs(virtual, node); if (ret != HDF_SUCCESS) { - // 读取节点失败 + /* 读取节点失败 */ HDF_LOGE("%s: Read drs fail! ret:%d", __func__, ret); goto __ERR__; } - // 初始化DAC设备指针 + /* 初始化DAC设备指针 */ VirtualDacDeviceInit(virtual); - // 节点数据传入私有数据 + /* 节点数据传入私有数据 */ virtual->device.priv = (void *)node; - // 传入设备号 + /* 传入设备号 */ virtual->device.devNum = virtual->deviceNum; - // 传入方法 + /* 传入方法 */ virtual->device.ops = &g_method; - // 添加DAC设备 + /* 添加DAC设备 */ ret = DacDeviceAdd(&virtual->device); if (ret != HDF_SUCCESS) { - // 添加DAC设备失败 + /* 添加DAC设备失败 */ HDF_LOGE("%s: add Dac controller failed! ret = %d", __func__, ret); goto __ERR__; } - // 成功添加DAC设备 + /* 成功添加DAC设备 */ return HDF_SUCCESS; __ERR__: - // 如果指针为空 + /* 如果指针为空 */ if (virtual != NULL) { - // 释放内存 + /* 释放内存 */ OsalMemFree(virtual); - // 指针置空 + /* 指针置空 */ virtual = NULL; } @@ -355,36 +409,62 @@ DAC模块适配包含以下四个步骤: static int32_t VirtualDacInit(struct HdfDeviceObject *device) { - // 定义返回值参数 + /* 定义返回值参数 */ int32_t ret; - // 设备结构体子节点 + /* 设备结构体子节点 */ const struct DeviceResourceNode *childNode = NULL; - // 入参指针进行判断 + /* 入参指针进行判断 */ if (device == NULL || device->property == NULL) { - // 入参指针为空 + /* 入参指针为空 */ HDF_LOGE("%s: device or property is NULL", __func__); return HDF_ERR_INVALID_OBJECT; } - // 入参指针不为空 + /* 入参指针不为空 */ ret = HDF_SUCCESS; DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { - // 解析子节点 + /* 解析子节点 */ ret = VirtualDacParseAndInit(device, childNode); if (ret != HDF_SUCCESS) { - // 解析失败 + /* 解析失败 */ break; } } - // 解析成功 + /* 解析成功 */ return ret; } + + static int32_t VirtualDacReadDrs(struct VirtualDacDevice *virtual, const struct DeviceResourceNode *node) + { + struct DeviceResourceIface *drsOps = NULL; + + /* 获取drsOps方法 */ + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetUint16 == NULL) { + HDF_LOGE("%s: Invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + /* 将配置参数依次读出,并填充至结构体中 */ + if (drsOps->GetUint32(node, "deviceNum", &virtual->deviceNum, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: Read deviceNum fail!", __func__); + return HDF_ERR_IO; + } + if (drsOps->GetUint32(node, "validChannel", &virtual->validChannel, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: Read validChannel fail!", __func__); + return HDF_ERR_IO; + } + if (drsOps->GetUint32(node, "rate", &virtual->rate, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: Read rate fail!", __func__); + return HDF_ERR_IO; + } + return HDF_SUCCESS; + } ``` - - Release函数参考 + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -400,41 +480,41 @@ DAC模块适配包含以下四个步骤: ```c++ static void VirtualDacRemoveByNode(const struct DeviceResourceNode *node) { - // 定义返回值参数 + /* 定义返回值参数 */ int32_t ret; - // 定义DAC设备号 + /* 定义DAC设备号 */ int16_t devNum; - // DAC设备结构体指针 + /* DAC设备结构体指针 */ struct DacDevice *device = NULL; - // DAC虚拟结构体指针 + /* DAC虚拟结构体指针 */ struct VirtualDacDevice *virtual = NULL; - // 设备资源接口结构体指针 + /* 设备资源接口结构体指针 */ struct DeviceResourceIface *drsOps = NULL; - // 通过实例入口获取设备资源 + /* 通过实例入口获取设备资源 */ drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); - // 入参指判空 + /* 入参指判空 */ if (drsOps == NULL || drsOps->GetUint32 == NULL) { - // 指针为空 + /* 指针为空 */ HDF_LOGE("%s: invalid drs ops fail!", __func__); return; } - // 获取devNum节点的数据 + /* 获取devNum节点的数据 */ ret = drsOps->GetUint16(node, "devNum", (uint16_t *)&devNum, 0); if (ret != HDF_SUCCESS) { - //获取失败 + /* 获取失败 */ HDF_LOGE("%s: read devNum fail!", __func__); return; } - // 获取DAC设备号 + /* 获取DAC设备号 */ device = DacDeviceGet(devNum); - // 判断DAC设备号以及数据是否为空 + /* 判断DAC设备号以及数据是否为空 */ if (device != NULL && device->priv == node) { - // 为空释放DAC设备号 + /* 为空释放DAC设备号 */ DacDevicePut(device); - // 移除DAC设备号 + /* 移除DAC设备号 */ DacDeviceRemove(device); virtual = (struct VirtualDacDevice *)device; - // 释放虚拟指针 + /* 释放虚拟指针 */ OsalMemFree(virtual); } return; @@ -442,17 +522,17 @@ DAC模块适配包含以下四个步骤: static void VirtualDacRelease(struct HdfDeviceObject *device) { - // 定义设备资源子节点结构体指针 + /* 定义设备资源子节点结构体指针 */ const struct DeviceResourceNode *childNode = NULL; - // 入参指针判空 + /* 入参指针判空 */ if (device == NULL || device->property == NULL) { - // 入参指针为空 + /* 入参指针为空 */ HDF_LOGE("%s: device or property is NULL", __func__); return; } DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { - // 通过节点移除DAC + /* 通过节点移除DAC */ VirtualDacRemoveByNode(childNode); } } diff --git a/zh-cn/device-dev/driver/driver-platform-gpio-des.md b/zh-cn/device-dev/driver/driver-platform-gpio-des.md index b3d99b7cf87f7a3e9f88f5ae77c6abde0baca7b0..b2d1db7482526a64656b2608848d2f599a10bcc0 100644 --- a/zh-cn/device-dev/driver/driver-platform-gpio-des.md +++ b/zh-cn/device-dev/driver/driver-platform-gpio-des.md @@ -1,256 +1,361 @@ # GPIO - ## 概述 +### 功能简介 + GPIO(General-purpose input/output)即通用型输入输出。通常,GPIO控制器通过分组的方式管理所有GPIO管脚,每组GPIO有一个或多个寄存器与之关联,通过读写寄存器完成对GPIO管脚的操作。 GPIO接口定义了操作GPIO管脚的标准方法集合,包括: -- 设置管脚方向:方向可以是输入或者输出(暂不支持高阻态) +- 设置管脚方向:方向可以是输入或者输出(暂不支持高阻态)。 +- 读写管脚电平值:电平值可以是低电平或高电平。 +- 设置管脚中断服务函数:设置一个管脚的中断响应函数,以及中断触发方式。 +- 使能和禁止管脚中断:禁止或使能管脚中断。 + +### 基本概念 + +GPIO又俗称为I/O口,I指的是输入(in),O指的是输出(out)。可以通过软件来控制其输入和输出,即I/O控制。 + +- GPIO输入 -- 读写管脚电平值:电平值可以是低电平或高电平 + 输入是检测各个引脚上的电平状态,高电平或者低电平状态。常见的输入模式有:模拟输入、浮空输入、上拉输入、下拉输入。 -- 设置管脚中断服务函数:设置一个管脚的中断响应函数,以及中断触发方式 +- GPIO输出 -- 使能和禁止管脚中断:禁止或使能管脚中断 + 输出是当需要控制引脚电平的高低时需要用到输出功能。常见的输出模式有:开漏输出、推挽输出、复用开漏输出、复用推挽输出。 +### 运作机制 -## 接口说明 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。GPIO模块接口适配模式采用统一服务模式(如图1所示)。 - **表1** GPIO驱动API接口功能介绍 +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 -| 功能分类 | 接口描述 | -| -------- | -------- | -| GPIO读写 | - GpioRead:读管脚电平值
- GpioWrite:写管脚电平值 | -| GPIO配置 | - GpioSetDir:设置管脚方向
- GpioGetDir:获取管脚方向 | -| GPIO中断设置 | - GpioSetIrq:设置管脚对应的中断服务函数
- GpioUnsetIrq:取消管脚对应的中断服务函数
- GpioEnableIrq:使能管脚中断
- GpioDisableIrq:禁止管脚中断 | +GPIO模块各分层作用: -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +- 接口层提供操作GPIO管脚的标准方法。 +- 核心层主要提供GPIO管脚资源匹配,GPIO管脚控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互,供芯片厂家快速接入HDF框架。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 +**图 1** GPIO统一服务模式结构图 + +![GPIO统一服务模式结构图](figures/统一服务模式结构图.png) ## 使用指导 +### 场景介绍 + +GPIO仅是一个软件层面的概念,主要工作是GPIO管脚资源管理。开发者可以使用提供的GPIO操作接口,实现对管脚控制。 + +### 接口说明 + +GPIO模块提供的主要接口如表1所示。 + +**表1** GPIO驱动API接口功能介绍 -### 使用流程 +| 接口名 | 描述 | +| ------------------------------------------------------------ | ------------------------------ | +| GpioGetByName(const char *gpioName) | 获取GPIO管脚ID | +| int32_t GpioRead(uint16_t gpio, uint16_t *val) | 读GPIO管脚电平值 | +| int32_t GpioWrite(uint16_t gpio, uint16_t val) | 写GPIO管脚电平值 | +| int32_t GpioGetDir(uint16_t gpio, uint16_t *dir) | 获取GPIO管脚方向 | +| int32_t GpioSetDir(uint16_t gpio, uint16_t dir) | 设置GPIO管脚方向 | +| int32_t GpioUnsetIrq(uint16_t gpio, void *arg); | 取消GPIO管脚对应的中断服务函数 | +| int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg) | 设置GPIO管脚对应的中断服务函数 | +| int32_t GpioEnableIrq(uint16_t gpio) | 使能GPIO管脚中断 | +| int32_t GpioDisableIrq(uint16_t gpio) | 禁止GPIO管脚中断 | + +>![](../public_sys-resources/icon-note.gif) **说明:**
+>本文涉及GPIO的所有接口,支持内核态及用户态使用。 + +### 开发步骤 GPIO标准API通过GPIO管脚号来操作指定管脚,使用GPIO的一般流程如下图所示。 - **图1** GPIO使用流程图 +**图1** GPIO使用流程图 - ![image](figures/GPIO使用流程图.png "GPIO使用流程图") +![image](figures/GPIO使用流程图.png "GPIO使用流程图") +#### 确定GPIO管脚号 -### 确定GPIO管脚号 +两种方式获取管脚号:根据SOC芯片规则进行计算、通过管脚别名获取 -不同SOC芯片由于其GPIO控制器型号、参数、以及控制器驱动的不同,GPIO管脚号的换算方式不一样。 +- 根据SOC芯片规则进行计算 -- Hi3516DV300 - 控制器管理12组GPIO管脚,每组8个。 + 不同SOC芯片由于其GPIO控制器型号、参数、以及控制器驱动的不同,GPIO管脚号的换算方式不一样。 - GPIO号 = GPIO组索引 (0~11) \* 每组GPIO管脚数(8) + 组内偏移 + - Hi3516DV300 - 举例:GPIO10_3的GPIO号 = 10 \* 8 + 3 = 83 + 控制器管理12组GPIO管脚,每组8个。 -- Hi3518EV300 - 控制器管理10组GPIO管脚,每组10个。 + GPIO号 = GPIO组索引 (0~11) \* 每组GPIO管脚数(8) + 组内偏移 - GPIO号 = GPIO组索引 (0~9) \* 每组GPIO管脚数(10) + 组内偏移 + 举例:GPIO10_3的GPIO号 = 10 \* 8 + 3 = 83 - 举例:GPIO7_3的GPIO管脚号 = 7 \* 10 + 3 = 73 + - Hi3518EV300 + 控制器管理10组GPIO管脚,每组10个。 -### 使用API操作GPIO管脚 + GPIO号 = GPIO组索引 (0~9) \* 每组GPIO管脚数(10) + 组内偏移 -- 设置GPIO管脚方向 - 在进行GPIO管脚读写前,需要先通过如下函数设置GPIO管脚方向: + 举例:GPIO7_3的GPIO管脚号 = 7 \* 10 + 3 = 73 - int32_t GpioSetDir(uint16_t gpio, uint16_t dir); +- 通过管脚别名获取 - **表2** GpioSetDir参数和返回值描述 - - | **参数**| **参数描述** | - | -------- | -------- | - | gpio | 待设置的GPIO管脚号 | - | dir | 待设置的方向值 | - | **返回值** | **返回值描述** | - | 0 | 设置成功 | - | 负数 | 设置失败 | + 调用接口GpioGetByName进行获取,入参是该管脚的别名,接口返回值是管脚的全局ID。 -- 读写GPIO管脚 + ```c + GpioGetByName(const char *gpioName); + ``` - 如果要读取一个GPIO管脚电平,通过以下函数完成: +#### 设置GPIO管脚方向 - int32_t GpioRead(uint16_t gpio, uint16_t \*val); +在进行GPIO管脚读写前,需要先通过如下函数设置GPIO管脚方向: - **表3** GpioRead参数和返回值描述 - - | **参数** | **参数描述** | - | -------- | -------- | - | gpio | 待读取的GPIO管脚号 | - | val | 接收读取电平值的指针 | - | **返回值** | **返回值描述** | - | 0 | 读取成功 | - | 负数 | 读取失败 | +```c +int32_t GpioSetDir(uint16_t gpio, uint16_t dir); +``` - 如果要向GPIO管脚写入电平值,通过以下函数完成: +**表2** GpioSetDir参数和返回值描述 - int32_t GpioWrite(uint16_t gpio, uint16_t val); +| **参数** | **参数描述** | +| ---------- | ------------------ | +| gpio | GPIO管脚号 | +| dir | 待设置的方向值 | +| **返回值** | **返回值描述** | +| 0 | 设置成功 | +| 负数 | 设置失败 | - **表4** GpioWrite参数和返回值描述 - - | **参数** | **参数描述** | - | -------- | -------- | - | gpio | 待写入的GPIO管脚号 | - | val | 待写入的电平值 | - | **返回值** | **返回值描述** | - | 0 | 写入成功 | - | 负数 | 写入失败 | +假设需要将GPIO管脚3的方向配置为输出,其使用示例如下: - 示例代码: +```c +int32_t ret; - - ``` - int32_t ret; - uint16_t val; - /* 将3号GPIO管脚配置为输出 */ - ret = GpioSetDir(3, GPIO_DIR_OUT); - if (ret != 0) { - HDF_LOGE("GpioSerDir: failed, ret %d\n", ret); - return; - } - /* 向3号GPIO管脚写入低电平GPIO_VAL_LOW */ - ret = GpioWrite(3, GPIO_VAL_LOW); - if (ret != 0) { - HDF_LOGE("GpioWrite: failed, ret %d\n", ret); - return; - } - /* 将6号GPIO管脚配置为输入 */ - ret = GpioSetDir(6, GPIO_DIR_IN); - if (ret != 0) { - HDF_LOGE("GpioSetDir: failed, ret %d\n", ret); - return; - } - /* 读取6号GPIO管脚的电平值 */ - ret = GpioRead(6, &val); - ``` +ret = GpioSetDir(3, GPIO_DIR_OUT); // 将3号GPIO管脚配置为输出 +if (ret != 0) { + HDF_LOGE("GpioSerDir: failed, ret %d\n", ret); + return ret; +} +``` -- 设置GPIO中断 +#### 获取GPIO管脚方向 - 如果要为一个GPIO管脚设置中断响应程序,使用如下函数: +可以通过如下函数获取GPIO管脚方向: - int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void \*arg); +```c +int32_t GpioGetDir(uint16_t gpio, uint16_t *dir); +``` - **表5** GpioSetIrq参数和返回值描述 - - | **参数** | **参数描述** | - | -------- | -------- | - | gpio | GPIO管脚号 | - | mode | 中断触发模式 | - | func | 中断服务程序 | - | arg | 传递给中断服务程序的入参 | - | **返回值** | **返回值描述** | - | 0 | 设置成功 | - | 负数 | 设置失败 | +**表2** GpioGetDir参数和返回值描述 - > ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:**
- > 同一时间,只能为某个GPIO管脚设置一个中断服务函数,如果重复调用GpioSetIrq函数,则之前设置的中断服务函数会被取代。 +| **参数** | **参数描述** | +| ---------- | ------------------ | +| gpio | GPIO管脚号 | +| dir | 待获取的方向值 | +| **返回值** | **返回值描述** | +| 0 | 设置成功 | +| 负数 | 设置失败 | - 当不再需要响应中断服务函数时,使用如下函数取消中断设置: +假设需要将GPIO管脚3的方向配置为输出,其使用示例如下: - int32_t GpioUnsetIrq(uint16_t gpio, void \*arg); +```c +int32_t ret; +uin16_t dir; - **表6** GpioUnsetIrq参数和返回值描述 - - | **参数** | **参数描述** | - | -------- | -------- | - | gpio | GPIO管脚号 | - | arg | GPIO中断数据 | - | **返回值** | **返回值描述** | - | 0 | 取消成功 | - | 负数 | 取消失败 | +ret = GpioGetDir(3, &dir); // 获取3号GPIO管脚方向 +if (ret != 0) { + HDF_LOGE("GpioGetDir: failed, ret %d\n", ret); + return ret; +} +``` - 在中断服务程序设置完成后,还需要先通过如下函数使能GPIO管脚的中断: +#### 读取GPIO管脚电平值 - int32_t GpioEnableIrq(uint16_t gpio); +如果要读取一个GPIO管脚电平,通过以下函数完成: - **表7** GpioEnableIrq参数和返回值描述 - - | **参数** | **参数描述** | - | -------- | -------- | - | gpio | GPIO管脚号 | - | **返回值** | **返回值描述** | - | 0 | 使能成功 | - | 负数 | 使能失败 | +```c +int32_t GpioRead(uint16_t gpio, uint16_t *val); +``` - > ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:**
- > 必须通过此函数使能管脚中断,之前设置的中断服务函数才能被正确响应。 +**表3** GpioRead参数和返回值描述 - 如果要临时屏蔽此中断,可以通过如下函数禁止GPIO管脚中断: +| **参数** | **参数描述** | +| ---------- | -------------------- | +| gpio | GPIO管脚号 | +| val | 接收读取电平值的指针 | +| **返回值** | **返回值描述** | +| 0 | 读取成功 | +| 负数 | 读取失败 | - int32_t GpioDisableIrq(uint16_t gpio); +假设需要读取GPIO管脚3的电平值,其使用示例如下: - **表8** GpioDisableIrq参数和返回值描述 - - | **参数** | **参数描述** | - | -------- | -------- | - | gpio | GPIO管脚号 | - | **返回值** | **返回值描述** | - | 0 | 禁止成功 | - | 负数 | 禁止失败 | +```c +int32_t ret; +uint16_t val; - 示例代码: +ret = GpioRead(3, &val); // 读取3号GPIO管脚电平值 +if (ret != 0) { + HDF_LOGE("GpioRead: failed, ret %d\n", ret); + return ret; +} +``` - - ``` - /* 中断服务函数*/ - int32_t MyCallBackFunc(uint16_t gpio, void *data) - { - HDF_LOGI("%s: gpio:%u interrupt service in! data=%p\n", __func__, gpio, data); - return 0; - } - - int32_t ret; - /* 设置中断服务程序为MyCallBackFunc,入参为NULL,中断触发模式为上升沿触发 */ - ret = GpioSetIrq(3, OSAL_IRQF_TRIGGER_RISING, MyCallBackFunc, NULL); - if (ret != 0) { - HDF_LOGE("GpioSetIrq: failed, ret %d\n", ret); - return; - } - - /* 使能3号GPIO管脚中断 */ - ret = GpioEnableIrq(3); - if (ret != 0) { - HDF_LOGE("GpioEnableIrq: failed, ret %d\n", ret); - return; - } - - /* 禁止3号GPIO管脚中断 */ - ret = GpioDisableIrq(3); - if (ret != 0) { - HDF_LOGE("GpioDisableIrq: failed, ret %d\n", ret); - return; - } - - /* 取消3号GPIO管脚中断服务程序 */ - ret = GpioUnsetIrq(3, NULL); - if (ret != 0) { - HDF_LOGE("GpioUnSetIrq: failed, ret %d\n", ret); - return; - } - ``` +#### 写入GPIO管脚电平值 + +如果要向GPIO管脚写入电平值,通过以下函数完成: + +```c +int32_t GpioWrite(uint16_t gpio, uint16_t val); +``` + +**表4** GpioWrite参数和返回值描述 + +| **参数** | **参数描述** | +| ---------- | ------------------ | +| gpio | GPIO管脚号 | +| val | 待写入的电平值 | +| **返回值** | **返回值描述** | +| 0 | 写入成功 | +| 负数 | 写入失败 | + +假设需要给GPIO管脚3写入低电平值,其使用示例如下: + +```c +int32_t ret; + +ret = GpioWrite(3, GPIO_VAL_LOW); // 给3号GPIO管脚写入低电平值 +if (ret != 0) { + HDF_LOGE("GpioRead: failed, ret %d\n", ret); + return ret; +} +``` + +#### 设置GPIO管脚中断 +如果要为一个GPIO管脚设置中断响应程序,使用如下函数: + +```c +int32_t GpioSetIrq(uint16_t gpio, uint16_t mode, GpioIrqFunc func, void *arg); +``` + +**表5** GpioSetIrq参数和返回值描述 + +| **参数** | **参数描述** | +| ---------- | ------------------------ | +| gpio | GPIO管脚号 | +| mode | 中断触发模式 | +| func | 中断服务程序 | +| arg | 传递给中断服务程序的入参 | +| **返回值** | **返回值描述** | +| 0 | 设置成功 | +| 负数 | 设置失败 | + +> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:**
+> 同一时间,只能为某个GPIO管脚设置一个中断服务函数,如果重复调用GpioSetIrq函数,则之前设置的中断服务函数会被取代。 + +#### 取消GPIO管脚中断 + +当不再需要响应中断服务函数时,使用如下函数取消中断设置: + +```c +int32_t GpioUnsetIrq(uint16_t gpio, void *arg); +``` + +**表6** GpioUnsetIrq参数和返回值描述 + +| **参数** | **参数描述** | +| ---------- | -------------- | +| gpio | GPIO管脚号 | +| arg | GPIO中断数据 | +| **返回值** | **返回值描述** | +| 0 | 取消成功 | +| 负数 | 取消失败 | + +#### 使能GPIO管脚中断 + +在中断服务程序设置完成后,还需要先通过如下函数使能GPIO管脚的中断: + +```c +int32_t GpioEnableIrq(uint16_t gpio); +``` + +**表7** GpioEnableIrq参数和返回值描述 + +| **参数** | **参数描述** | +| ---------- | -------------- | +| gpio | GPIO管脚号 | +| **返回值** | **返回值描述** | +| 0 | 使能成功 | +| 负数 | 使能失败 | + +> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:**
+> 必须通过此函数使能管脚中断,之前设置的中断服务函数才能被正确响应。 + +#### 禁止GPIO管脚中断 + +如果要临时屏蔽此中断,可以通过如下函数禁止GPIO管脚中断: + +```c +int32_t GpioDisableIrq(uint16_t gpio); +``` +**表8** GpioDisableIrq参数和返回值描述 + +| **参数** | **参数描述** | +| ---------- | -------------- | +| gpio | GPIO管脚号 | +| **返回值** | **返回值描述** | +| 0 | 禁止成功 | +| 负数 | 禁止失败 | + +中断相关操作示例: + +```c +/* 中断服务函数*/ +int32_t MyCallBackFunc(uint16_t gpio, void *data) +{ + HDF_LOGI("%s: gpio:%u interrupt service in data\n", __func__, gpio); + return 0; +} + +int32_t ret; +/* 设置中断服务程序为MyCallBackFunc,入参为NULL,中断触发模式为上升沿触发 */ +ret = GpioSetIrq(3, OSAL_IRQF_TRIGGER_RISING, MyCallBackFunc, NULL); +if (ret != 0) { + HDF_LOGE("GpioSetIrq: failed, ret %d\n", ret); + return ret; +} + +/* 使能3号GPIO管脚中断 */ +ret = GpioEnableIrq(3); +if (ret != 0) { + HDF_LOGE("GpioEnableIrq: failed, ret %d\n", ret); + return ret; +} + +/* 禁止3号GPIO管脚中断 */ +ret = GpioDisableIrq(3); +if (ret != 0) { + HDF_LOGE("GpioDisableIrq: failed, ret %d\n", ret); + return ret; +} + +/* 取消3号GPIO管脚中断服务程序 */ +ret = GpioUnsetIrq(3, NULL); +if (ret != 0) { + HDF_LOGE("GpioUnSetIrq: failed, ret %d\n", ret); + return ret; +} +``` ## 使用实例 本实例程序中,我们将测试一个GPIO管脚的中断触发:为管脚设置中断服务函数,触发方式为边沿触发,然后通过交替写高低电平到管脚,产生电平波动,制造触发条件,观察中断服务函数的执行。 -首先需要选取一个空闲的GPIO管脚,本例程基于Hi3516DV300某开发板,GPIO管脚选择GPIO10_3,换算成GPIO号为83。 +首先需要选取一个空闲的GPIO管脚,本例程基于Hi3516DV300开发板,GPIO管脚选择GPIO10_3,换算成GPIO号为83。 - 读者可以根据自己使用的开发板,参考其原理图,选择一个空闲的GPIO管脚即可。 - -``` +读者可以根据自己使用的开发板,参考其原理图,选择一个空闲的GPIO管脚即可。 + +```c #include "gpio_if.h" #include "hdf_log.h" #include "osal_irq.h" @@ -261,7 +366,7 @@ static uint32_t g_irqCnt; /* 中断服务函数*/ static int32_t TestCaseGpioIrqHandler(uint16_t gpio, void *data) { - HDF_LOGE("%s: irq triggered! on gpio:%u, data=%p", __func__, gpio, data); + HDF_LOGE("%s: irq triggered! on gpio:%u, in data", __func__, gpio); g_irqCnt++; /* 如果中断服务函数触发执行,则将全局中断计数加1 */ return GpioDisableIrq(gpio); } @@ -319,4 +424,4 @@ static int32_t TestCaseGpioIrqEdge(void) (void)GpioUnsetIrq(gpio, NULL); return (g_irqCnt > 0) ? HDF_SUCCESS : HDF_FAILURE; } -``` +``` \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-gpio-develop.md b/zh-cn/device-dev/driver/driver-platform-gpio-develop.md index a9336743edacb5668f27205239f7b8f328bd3878..7b15fc2935bfbde69ee7622b11ab9ad88d6f54f2 100755 --- a/zh-cn/device-dev/driver/driver-platform-gpio-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-gpio-develop.md @@ -1,269 +1,386 @@ # GPIO - ## 概述 -GPIO(General-purpose input/output)即通用型输入输出,在HDF框架中,GPIO的接口适配模式采用无服务模式,用于不需要在用户态提供API的设备类型,或者没有用户态和内核区分的OS系统,其关联方式是DevHandle直接指向设备对象内核态地址(DevHandle是一个void类型指针)。 +### 功能简介 - **图1** GPIO无服务模式结构图 +GPIO(General-purpose input/output)即通用型输入输出。通常,GPIO控制器通过分组的方式管理所有GPIO管脚,每组GPIO有一个或多个寄存器与之关联,通过读写寄存器完成对GPIO管脚的操作。 - ![](figures/无服务模式结构图.png "GPIO无服务模式结构图") +### 基本概念 +GPIO又俗称为I/O口,I指的是输入(in),O指的是输出(out)。可以通过软件来控制其输入和输出,即I/O控制。 -## 接口说明 +- GPIO输入 -GpioMethod定义: + 输入是检测各个引脚上的电平状态,高电平或者低电平状态。常见的输入模式有:模拟输入、浮空输入、上拉输入、下拉输入。 - -``` -struct GpioMethod { - int32_t (*request)(struct GpioCntlr *cntlr, uint16_t local);// 【预留】 - int32_t (*release)(struct GpioCntlr *cntlr, uint16_t local);// 【预留】 - int32_t (*write)(struct GpioCntlr *cntlr, uint16_t local, uint16_t val); - int32_t (*read)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *val); - int32_t (*setDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t dir); - int32_t (*getDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *dir); - int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq);// 【预留】 - int32_t (*setIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t mode, GpioIrqFunc func, void *arg); - int32_t (*unsetIrq)(struct GpioCntlr *cntlr, uint16_t local); - int32_t (*enableIrq)(struct GpioCntlr *cntlr, uint16_t local); - int32_t (*disableIrq)(struct GpioCntlr *cntlr, uint16_t local); -} -``` +- GPIO输出 - **表1** GpioMethod结构体成员的回调函数功能说明 + 输出是当需要控制引脚电平的高低时需要用到输出功能。常见的输出模式有:开漏输出、推挽输出、复用开漏输出、复用推挽输出。 -| 函数成员 | 入参 | 出参 | 返回值 | 功能 | -| -------- | -------- | -------- | -------- | -------- | -| write | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号
val:uint16_t,电平传入值 | 无 | HDF_STATUS相关状态 | GPIO引脚写入电平值 | -| read | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识 | val:uint16_t指针,用于传出电平值。 | HDF_STATUS相关状态 | GPIO引脚读取电平值 | -| setDir | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号
dir:uint16_t,管脚方向传入值 | 无 | HDF_STATUS相关状态 | 设置GPIO引脚输入/输出方向 | -| getDir | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号 | dir:uint16_t指针,用于传出管脚方向值 | HDF_STATUS相关状态 | 读GPIO引脚输入/输出方向 | -| setIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号
mode:uint16_t,表示触发模式(边沿或电平)
func:函数指针,中断服务程序;
arg:void指针,中断服务程序入参 | 无 | HDF_STATUS相关状态 | 将GPIO引脚设置为中断模式 | -| unsetIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号 | 无 | HDF_STATUS相关状态 | 取消GPIO中断设置 | -| enableIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号 | 无 | HDF_STATUS相关状态 | 使能GPIO管脚中断 | -| disableIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t,GPIO端口标识号 | 无 | HDF_STATUS相关状态 | 禁止GPIO管脚中断 | +### 运作机制 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。GPIO模块接口适配模式采用统一服务模式(如图1所示)。 -## 开发步骤 +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 -GPIO模块适配的三个必选环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +GPIO模块各分层作用: -GPIO控制器分组管理所有管脚,相关参数会在属性文件中有所体现;驱动入口和接口函数的实例化环节是厂商驱动接入HDF的核心环节。 +- 接口层提供操作GPIO管脚的标准方法。 +- 核心层主要提供GPIO管脚资源匹配,GPIO管脚控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互,供芯片厂家快速接入HDF框架。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 -1. 实例化驱动入口 - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 +**图 1** GPIO统一服务模式结构图 -2. 配置属性文件 - - 在device_info.hcs文件中添加deviceNode描述。 - - 【可选】添加gpio_config.hcs器件属性文件。 +![GPIO统一服务模式结构图](figures/统一服务模式结构图.png) -3. 实例化GPIO控制器对象 - - 初始化GpioCntlr成员。 - - 实例化GpioCntlr成员GpioMethod。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
- > 实例化GpioCntlr成员GpioMethod,详见[接口说明](#接口说明)。 +## 开发指导 -4. 驱动调试 +### 场景介绍 - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如GPIO控制状态,中断响应情况等。 +GPIO仅是一个软件层面的概念,主要工作是GPIO管脚资源管理。驱动开发者可以使用GPIO模块提供的操作接口,实现对管脚的控制。当驱动开发者需要将GPIO适配到OpenHarmony时,需要进行GPIO驱动适配。下文将介绍如何进行GPIO驱动适配。 +### 接口说明 -## 开发实例 +为了保证上层在调用GPIO接口时能够正确的操作GPIO管脚,核心层在//drivers/hdf_core/framework/support/platform/include/gpio/gpio_core.h中定义了以下钩子函数,驱动适配者需要在适配层实现这些函数的具体功能,并与钩子函数挂接,从而完成适配层与核心层的交互。 -下方将以gpio_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +GpioMethod定义: -1. 驱动开发首先需要实例化驱动入口。 +```c +struct GpioMethod { + int32_t (*request)(struct GpioCntlr *cntlr, uint16_t local); // 【预留】 + int32_t (*release)(struct GpioCntlr *cntlr, uint16_t local); // 【预留】 + int32_t (*write)(struct GpioCntlr *cntlr, uint16_t local, uint16_t val); + int32_t (*read)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *val); + int32_t (*setDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t dir); + int32_t (*getDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *dir); + int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq); // 【预留】 + int32_t (*setIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t mode, GpioIrqFunc func, void *arg); + int32_t (*unsetIrq)(struct GpioCntlr *cntlr, uint16_t local); + int32_t (*enableIrq)(struct GpioCntlr *cntlr, uint16_t local); + int32_t (*disableIrq)(struct GpioCntlr *cntlr, uint16_t local); +} +``` - 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +**表1** GpioMethod结构体成员的钩子函数功能说明 + +| 函数成员 | 入参 | 出参 | 返回值 | 功能 | +| -------- | -------- | -------- | -------- | -------- | +| write | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号
val:uint16_t类型,电平传入值 | 无 | HDF_STATUS相关状态 | GPIO引脚写入电平值 | +| read | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识 | val:uint16_t类型指针,用于传出电平值。 | HDF_STATUS相关状态 | GPIO引脚读取电平值 | +| setDir | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号
dir:uint16_t类型,管脚方向传入值 | 无 | HDF_STATUS相关状态 | 设置GPIO引脚输入/输出方向 | +| getDir | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号 | dir:uint16_t类型指针,用于传出管脚方向值 | HDF_STATUS相关状态 | 读GPIO引脚输入/输出方向 | +| setIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号
mode:uint16_t类型,表示触发模式(边沿或电平)
func:函数指针,中断服务程序;
arg:void指针,中断服务程序入参 | 无 | HDF_STATUS相关状态 | 将GPIO引脚设置为中断模式 | +| unsetIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号 | 无 | HDF_STATUS相关状态 | 取消GPIO中断设置 | +| enableIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号 | 无 | HDF_STATUS相关状态 | 使能GPIO管脚中断 | +| disableIrq | cntlr:结构体指针,核心层GPIO控制器
local:uint16_t类型,GPIO端口标识号 | 无 | HDF_STATUS相关状态 | 禁止GPIO管脚中断 | + +### 开发步骤 + +GPIO模块适配包含以下四个步骤: +- 实例化驱动入口。 +- 配置属性文件。 +- 实例化GPIO控制器对象。 +- 驱动调试。 + +### 开发实例 + +下方将基于Hi3516DV300开发板以//device_soc_hisilicon/common/platform/gpio/gpio_hi35xx.c驱动为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 + +1. 实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - GPIO 驱动入口参考: - - ``` + GPIO驱动入口开发参考: + + ```c struct HdfDriverEntry g_gpioDriverEntry = { - .moduleVersion = 1, - .Bind = Pl061GpioBind, // GPIO不需要实现Bind,本例是一个空实现,厂商可根据自身需要添加相关操作。 - .Init = Pl061GpioInit, // 见Init参考 - .Release = Pl061GpioRelease, // 见Release参考 - .moduleName = "hisi_pl061_driver",//【必要且需要与HCS文件中里面的moduleName匹配】 + .moduleVersion = 1, + .Bind = Pl061GpioBind, // GPIO不需要实现Bind,本例是一个空实现,驱动适配者可根据自身需要添加相关操作 + .Init = Pl061GpioInit, // 见Init参考 + .Release = Pl061GpioRelease, // 见Release参考 + .moduleName = "hisi_pl061_driver", // 【必要且需要与HCS文件中里面的moduleName匹配】 }; - // 调用HDF_INIT将驱动入口注册到HDF框架中 - HDF_INIT(g_gpioDriverEntry); + HDF_INIT(g_gpioDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在gpio_config.hcs中配置器件属性。 +2. 配置属性文件。 - deviceNode信息与驱动入口注册相关,器件属性值与核心层GpioCntlr成员的默认值或限制范围有密切关系。 + 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,deviceNode信息与驱动入口注册相关。本例以一个GPIO控制器为例,如有多个器件信息,则需要在device_info.hcs文件增加deviceNode信息。器件属性值与核心层GpioCntlr成员的默认值或限制范围有密切关系,需要在gpio_config.hcs中配置器件属性。 - 本例只有一个GPIO控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在gpio_config文件中增加对应的器件属性。 + - device_info.hcs 配置参考: - - device_info.hcs配置参考 - - ``` + 在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + + ```c root { - device_info { - platform :: host { - hostName = "platform_host"; - priority = 50; - device_gpio :: device { - device0 :: deviceNode { - policy = 0; // 等于0,不需要发布服务。 - priority = 10; // 驱动启动优先级。 - permission = 0644; // 驱动创建设备节点权限。 - moduleName = "hisi_pl061_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 - deviceMatchAttr = "hisilicon_hi35xx_pl061"; //【必要】用于配置控制器私有数据,要与gpio_config.hcs中 - // 对应控制器保持一致,其他控制器信息也在文件中。 + device_info { + platform :: host { + hostName = "platform_host"; + priority = 50; + device_gpio :: device { + device0 :: deviceNode { + policy = 0; // 等于0,不需要发布服务 + priority = 10; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "hisi_pl061_driver"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致 + deviceMatchAttr = "hisilicon_hi35xx_pl061"; // 【必要】用于配置控制器私有数据,要与gpio_config.hcs中 + // 对应控制器保持一致,其他控制器信息也在文件中 + } + } } } - } - } } ``` - - gpio_config.hcs配置参考 - - ``` + + - gpio_config.hcs配置参考: + + 在//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/gpio/gpio_config.hcs文件配置器件属性,其中配置参数如下: + + ```c root { - platform { - gpio_config { - controller_0x120d0000 { - match_attr = "hisilicon_hi35xx_pl061"; //【必要】必须和device_info.hcs中的deviceMatchAttr值一致。 - groupNum = 12; //【必要】GPIO组索引,需要根据设备情况填写。 - bitNum = 8; //【必要】每组GPIO管脚数 。 - regBase = 0x120d0000; //【必要】物理基地址。 - regStep = 0x1000; //【必要】寄存器偏移步进。 - irqStart = 48; //【必要】开启中断。 - irqShare = 0; //【必要】共享中断。 - } + platform { + gpio_config { + controller_0x120d0000 { + match_attr = "hisilicon_hi35xx_pl061"; // 【必要】必须和device_info.hcs中的deviceMatchAttr值一致 + groupNum = 12; // 【必要】GPIO组索引,需要根据设备情况填写 + bitNum = 8; // 【必要】每组GPIO管脚数 + regBase = 0x120d0000; // 【必要】物理基地址 + regStep = 0x1000; // 【必要】寄存器偏移步进 + irqStart = 48; // 【必要】开启中断 + irqShare = 0; // 【必要】共享中断 + } + ... + } } } - } ``` -3. 完成驱动入口注册之后,下一步就是以核心层GpioCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化GpioCntlr成员GpioMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + 需要注意的是,新增gpio_config.hcs配置文件后,必须在产品对应的hdf.hcs文件中将其包含如下语句所示,否则配置文件无法生效。 + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/gpio/gpio_config.hcs" // 配置文件相对路径 + ``` + +3. 实例化GPIO控制器对象。 + + 完成驱动入口注册之后,下一步就是以核心层GpioCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化GpioCntlr成员GpioMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 - - 自定义结构体参考。 + - 驱动适配者自定义结构体参考。 从驱动的角度看,自定义结构体是参数和数据的载体,而且gpio_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层GpioCntlr对象,例如索引、管脚数等。 - - ``` - struct Pl061GpioCntlr { - struct GpioCntlr cntlr; //【必要】是核心层控制对象,其成员定义见下面。 - volatile unsigned char *regBase; //【必要】寄存器基地址。 - uint32_t phyBase; //【必要】物理基址。 - uint32_t regStep; //【必要】寄存器偏移步进。 - uint32_t irqStart; //【必要】中断开启。 - uint16_t groupNum; //【必要】用于描述厂商的GPIO端口号的参数。 - uint16_t bitNum; //【必要】用于描述厂商的GPIO端口号的参数。 - uint8_t irqShare; //【必要】共享中断。 - struct Pl061GpioGroup *groups; //【可选】根据厂商需要设置。 + ```c + //GPIO分组信息定义 + struct Pl061GpioGroup { + struct GpioCntlr cntlr; // 【必要】是核心层控制对象,其成员定义见下面。 + volatile unsigned char *regBase; // 【必要】寄存器基地址。 + unsigned int index; + unsigned int irq; + OsalIRQHandle irqFunc; + OsalSpinlock lock; + uint32_t irqSave; + bool irqShare; + struct PlatformDumper *dumper; + char *dumperName; }; - struct Pl061GpioGroup { // 包括寄存器地址,中断号,中断函数和锁。 - volatile unsigned char *regBase; - unsigned int index; - unsigned int irq; - OsalIRQHandle irqFunc; - OsalSpinlock lock; + + struct Pl061GpioData { + volatile unsigned char *regBase; // 【必要】寄存器基地址。 + uint32_t phyBase; // 【必要】物理基址。 + uint32_t regStep; // 【必要】寄存器偏移步进。 + uint32_t irqStart; // 【必要】中断开启。 + uint16_t groupNum; // 【必要】用于描述厂商的GPIO端口号的参数。 + uint16_t bitNum; // 【必要】用于描述厂商的GPIO端口号的参数。 + uint8_t irqShare; // 【必要】共享中断。 + struct Pl061GpioGroup *groups; // 【可选】根据厂商需要设置。 + struct GpioInfo *gpioInfo; + void *priv; + }; + + struct GpioInfo { + struct GpioCntlr *cntlr; + char name[GPIO_NAME_LEN]; + OsalSpinlock spin; + uint32_t irqSave; + struct GpioIrqRecord *irqRecord; }; - // GpioCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct GpioCntlr { - struct IDeviceIoService service; - struct HdfDeviceObject *device; - struct GpioMethod *ops; - struct DListHead list; - OsalSpinlock spin; - uint16_t start; - uint16_t count; - struct GpioInfo *ginfos; - void *priv; + struct PlatformDevice device; + struct GpioMethod *ops; + uint16_t start; + uint16_t count; + struct GpioInfo *ginfos; + bool isAutoAlloced; + void *priv; }; ``` - - GpioCntlr成员回调函数结构体GpioMethod的实例化,其他成员在Init函数中初始化。 - - ``` - //GpioMethod结构体成员都是回调函数,厂商需要根据表1完成相应的函数功能。 + - GpioCntlr成员钩子函数结构体GpioMethod的实例化,其他成员在Init函数中初始化。 + + ```c + //GpioMethod结构体成员都是钩子函数,驱动适配者需要根据表1完成相应的函数功能。 static struct GpioMethod g_method = { .request = NULL, .release = NULL, - .write = Pl061GpioWrite, // 写管脚。 - .read = Pl061GpioRead, // 读管脚。 - .setDir = Pl061GpioSetDir, // 设置管脚方向。 - .getDir = Pl061GpioGetDir, // 获取管脚方向。 - .toIrq = NULL, - .setIrq = Pl061GpioSetIrq, // 设置管脚中断,如不具备此能力可忽略。 - .unsetIrq = Pl061GpioUnsetIrq, // 取消管脚中断设置,如不具备此能力可忽略。 - .enableIrq = Pl061GpioEnableIrq, // 使能管脚中断,如不具备此能力可忽略。 - .disableIrq = Pl061GpioDisableIrq,// 禁止管脚中断,如不具备此能力可忽略。 + .write = Pl061GpioWrite, // 写管脚 + .read = Pl061GpioRead, // 读管脚 + .setDir = Pl061GpioSetDir, // 设置管脚方向 + .getDir = Pl061GpioGetDir, // 获取管脚方向 + .toIrq = NULL, + .setIrq = Pl061GpioSetIrq, // 设置管脚中断,如不具备此能力可忽略 + .unsetIrq = Pl061GpioUnsetIrq, // 取消管脚中断设置,如不具备此能力可忽略 + .enableIrq = Pl061GpioEnableIrq, // 使能管脚中断,如不具备此能力可忽略 + .disableIrq = Pl061GpioDisableIrq, // 禁止管脚中断,如不具备此能力可忽略 }; ``` - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 - **表2** Init函数说明 - - | 状态(值) | 问题描述 | + **表2** Init函数说明 + + | 状态(值) | 问题描述 | | -------- | -------- | - | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_INVALID_PARAM | 参数非法 | - | HDF_ERR_IO | I/O 错误 | - | HDF_SUCCESS | 初始化成功 | - | HDF_FAILURE | 初始化失败 | + | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_INVALID_PARAM | 参数非法 | + | HDF_ERR_IO | I/O 错误 | + | HDF_SUCCESS | 初始化成功 | + | HDF_FAILURE | 初始化失败 | 函数说明: 初始化自定义结构体对象,初始化GpioCntlr成员,调用核心层GpioCntlrAdd函数,接入VFS(可选)。 - - ``` + ```c + static struct Pl061GpioData g_pl061 = { + .groups = NULL, + .groupNum = PL061_GROUP_MAX, + .bitNum = PL061_BIT_MAX, + }; + + static int32_t Pl061GpioInitGroups(struct Pl061GpioData *pl061) + { + int32_t ret; + uint16_t i; + struct Pl061GpioGroup *groups = NULL; + + if (pl061 == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + groups = (struct Pl061GpioGroup *)OsalMemCalloc(sizeof(*groups) * pl061->groupNum); + if (groups == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + pl061->groups = groups; + + for (i = 0; i < pl061->groupNum; i++) { + // 相关信息初始化 + groups[i].index = i; + groups[i].regBase = pl061->regBase + i * pl061->regStep; + groups[i].irq = pl061->irqStart + i; + groups[i].irqShare = pl061->irqShare; + groups[i].cntlr.start = i * pl061->bitNum; + groups[i].cntlr.count = pl061->bitNum; + groups[i].cntlr.ops = &g_method; + groups[i].cntlr.ginfos = &pl061->gpioInfo[i * pl061->bitNum]; + + if ((ret = OsalSpinInit(&groups[i].lock)) != HDF_SUCCESS) { + goto ERR_EXIT; + } + + ret = GpioCntlrAdd(&groups[i].cntlr); // 向HDF core中添加相关信息 + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: err add controller(%hu:%hu):%d", __func__, + groups[i].cntlr.start, groups[i].cntlr.count, ret); + (void)OsalSpinDestroy(&groups[i].lock); + goto ERR_EXIT; + } + } + return HDF_SUCCESS; + + ERR_EXIT: + while (i-- > 0) { + GpioCntlrRemove(&groups[i].cntlr); + (void)OsalSpinDestroy(&groups[i].lock); + } + pl061->groups = NULL; + OsalMemFree(groups); + return ret; + } + static int32_t Pl061GpioInit(struct HdfDeviceObject *device) { - ... - struct Pl061GpioCntlr *pl061 = &g_pl061;// 利用静态全局变量完成初始化 - // static struct Pl061GpioCntlr g_pl061 = { - // .groups = NULL, - // .groupNum = PL061_GROUP_MAX, - // .bitNum = PL061_BIT_MAX, - //}; - ret = Pl061GpioReadDrs(pl061, device->property);// 利用从gpio_config.HCS文件读取的属性值来初始化自定义结构体对象成员 - ... - pl061->regBase = OsalIoRemap(pl061->phyBase, pl061->groupNum * pl061->regStep);//地址映射 - ... - ret = Pl061GpioInitCntlrMem(pl061); // 内存分配 - ... - pl061->cntlr.count = pl061->groupNum * pl061->bitNum;//【必要】管脚数量计算 - pl061->cntlr.priv = (void *)device->property; //【必要】存储设备属性 - pl061->cntlr.ops = &g_method; //【必要】GpioMethod的实例化对象的挂载 - pl061->cntlr.device = device; //【必要】使HdfDeviceObject与GpioCntlr可以相互转化的前提 - ret = GpioCntlrAdd(&pl061->cntlr); //【必要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 - ... - Pl061GpioDebugCntlr(pl061); - #ifdef PL061_GPIO_USER_SUPPORT //【可选】若支持用户级的虚拟文件系统,则接入。 - if (GpioAddVfs(pl061->bitNum) != HDF_SUCCESS) { - HDF_LOGE("%s: add vfs fail!", __func__); - } - #endif - ... + int32_t ret; + struct Pl061GpioData *pl061 = &g_pl061; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("%s: device or property null!", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + pl061->gpioInfo = OsalMemCalloc(sizeof(struct GpioInfo) * GPIO_MAX_INFO_NUM); + if (pl061->gpioInfo == NULL) { + HDF_LOGE("%s: failed to calloc gpioInfo!", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + ret = Pl061GpioReadDrs(pl061, device->property); // 利用从gpio_config.HCS文件读取的属性值来初始化自定义结构体对象成员 + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: failed to read drs:%d", __func__, ret); + return ret; + } + + if (pl061->groupNum > PL061_GROUP_MAX || pl061->groupNum <= 0 || + pl061->bitNum > PL061_BIT_MAX || pl061->bitNum <= 0) { + HDF_LOGE("%s: err groupNum:%hu, bitNum:%hu", __func__, pl061->groupNum, pl061->bitNum); + return HDF_ERR_INVALID_PARAM; + } + + pl061->regBase = OsalIoRemap(pl061->phyBase, pl061->groupNum * pl061->regStep); //地址映射 + if (pl061->regBase == NULL) { + HDF_LOGE("%s: err remap phy:0x%x", __func__, pl061->phyBase); + return HDF_ERR_IO; + } + + ret = Pl061GpioInitGroups(pl061); //group信息初始化,并添加到HDF核心层 + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: err init groups:%d", __func__, ret); + OsalIoUnmap((void *)pl061->regBase); + pl061->regBase = NULL; + return ret; + } + pl061->priv = (void *)device->property; + device->priv = (void *)pl061; + Pl061GpioDebug(pl061); + + #ifdef PL061_GPIO_USER_SUPPORT + if (GpioAddVfs(pl061->bitNum) != HDF_SUCCESS) { + HDF_LOGE("%s: add vfs fail!", __func__); + } + #endif + HDF_LOGI("%s: dev service:%s init success!", __func__, HdfDeviceGetServiceName(device)); + return HDF_SUCCESS; } ``` - - Release函数参考 + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: @@ -276,23 +393,50 @@ GPIO控制器分组管理所有管脚,相关参数会在属性文件中有所 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 - - ``` + ```c + static void Pl061GpioUninitGroups(struct Pl061GpioData *pl061) + { + uint16_t i; + struct Pl061GpioGroup *group = NULL; + + for (i = 0; i < pl061->groupNum; i++) { + group = &pl061->groups[i]; + GpioDumperDestroy(&pl061->groups[i]); + GpioCntlrRemove(&group->cntlr); // 从HDF核心层删除 + } + + OsalMemFree(pl061->groups); + pl061->groups = NULL; + } + static void Pl061GpioRelease(struct HdfDeviceObject *device) { - struct GpioCntlr *cntlr = NULL; - struct Pl061GpioCntlr *pl061 = NULL; - ... - cntlr = GpioCntlrFromDevice(device);//【必要】通过强制转换获取核心层控制对象 - // return (device == NULL) ? NULL : (struct GpioCntlr *)device->service; - ... - #ifdef PL061_GPIO_USER_SUPPORT - GpioRemoveVfs();//与Init中GpioAddVfs相反 - #endif - GpioCntlrRemove(cntlr); //【必要】取消设备信息、服务等内容在核心层上的挂载 - pl061 = ToPl061GpioCntlr(cntlr); // return (struct Pl061GpioCntlr *)cntlr; - Pl061GpioRleaseCntlrMem(pl061); //【必要】锁和内存的释放 - OsalIoUnmap((void *)pl061->regBase);//【必要】解除地址映射 - pl061->regBase = NULL; + struct Pl061GpioData *pl061 = NULL; + + HDF_LOGI("%s: enter", __func__); + if (device == NULL) { + HDF_LOGE("%s: device is null!", __func__); + return; + } + + #ifdef PL061_GPIO_USER_SUPPORT + GpioRemoveVfs(); + #endif + + pl061 = (struct Pl061GpioData *)device->priv; + if (pl061 == NULL) { + HDF_LOGE("%s: device priv is null", __func__); + return; + } + + Pl061GpioUninitGroups(pl061); + OsalMemFree(pl061->gpioInfo); + pl061->gpioInfo = NULL; + OsalIoUnmap((void *)pl061->regBase); + pl061->regBase = NULL; } ``` + +4. 驱动调试。 + + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如GPIO控制状态,中断响应情况等。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-i2c-des.md b/zh-cn/device-dev/driver/driver-platform-i2c-des.md index c1bfaae6a2a00f42f61b313b03ca440f07039461..c4324343a044891d354a1f2cf1938034be16ebc1 100644 --- a/zh-cn/device-dev/driver/driver-platform-i2c-des.md +++ b/zh-cn/device-dev/driver/driver-platform-i2c-des.md @@ -3,9 +3,13 @@ ## 概述 -I2C(Inter Integrated Circuit)总线是由Philips公司开发的一种简单、双向二线制同步串行总线。 +### 功能简介 -I2C以主从方式工作,通常有一个主设备和一个或者多个从设备,主从设备通过SDA(SerialData)串行数据线以及SCL(SerialClock)串行时钟线两根线相连,如图1所示。 +I2C(Inter Integrated Circuit)总线是由Philips公司开发的一种简单、双向二线制同步串行总线。由于其硬件连接简单、成本低廉,因此被广泛应用于各种短距离通信的场景。 + +### 运作机制 + +I2C以主从方式工作,通常有一个主设备和一个或者多个从设备,主从设备通过SDA(SerialData)串行数据线以及SCL(SerialClock)串行时钟线两根线相连(如图1)。 I2C数据的传输必须以一个起始信号作为开始条件,以一个结束信号作为传输的停止条件。数据传输以字节为单位,高位在前,逐个bit进行传输。 @@ -19,37 +23,40 @@ I2C接口定义了完成I2C传输的通用方法集合,包括: ![image](figures/I2C物理连线示意图.png "I2C物理连线示意图") +## 使用指导 -## 接口说明 +### 场景介绍 - **表1** I2C驱动API接口功能介绍 +I2C通常用于与各类支持I2C协议的传感器、执行器或输入输出设备进行通信。 -| 功能分类 | 接口描述 | -| -------- | -------- | -| I2C控制器管理接口 | - I2cOpen:打开I2C控制器
- I2cClose:关闭I2C控制器 | -| I2C消息传输接口 | I2cTransfer:自定义传输 | +### 接口说明 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +I2C模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/i2c_if.h。 +**表1** I2C驱动API接口功能介绍 -## 使用指导 - +| 接口名 | 接口描述 | +| -------- | -------- | +| DevHandle I2cOpen(int16_t number) | 打开I2C控制器 | +| void I2cClose(DevHandle handle) | 关闭I2C控制器 | +| int32_t I2cTransfer(DevHandle handle, struct I2cMsg \*msgs, int16_t count) | 自定义传输 | ### 使用流程 使用I2C设备的一般流程如下图所示。 - **图2** I2C设备使用流程图 +**图2** I2C设备使用流程图 - ![image](figures/I2C设备使用流程图.png "I2C设备使用流程图") +![image](figures/I2C设备使用流程图.png "I2C设备使用流程图") -### 打开I2C控制器 +#### 打开I2C控制器 在进行I2C通信前,首先要调用I2cOpen打开I2C控制器。 +```c DevHandle I2cOpen(int16_t number); +``` **表2** I2cOpen参数和返回值描述 @@ -62,8 +69,7 @@ DevHandle I2cOpen(int16_t number); 假设系统中存在8个I2C控制器,编号从0到7,以下代码示例为获取3号控制器: - -``` +```c DevHandle i2cHandle = NULL; /* I2C控制器句柄 / /* 打开I2C控制器 */ @@ -75,11 +81,13 @@ if (i2cHandle == NULL) { ``` -### 进行I2C通信 +#### 进行I2C通信 消息传输 +```c int32_t I2cTransfer(DevHandle handle, struct I2cMsg \*msgs, int16_t count); +``` **表3** I2cTransfer参数和返回值描述 @@ -92,10 +100,10 @@ int32_t I2cTransfer(DevHandle handle, struct I2cMsg \*msgs, int16_t count); | 正整数 | 成功传输的消息结构体数目 | | 负数 | 执行失败 | -I2C传输消息类型为I2cMsg,每个传输消息结构体表示一次读或写,通过一个消息数组,可以执行若干次的读写组合操作。 +I2C传输消息类型为I2cMsg,每个传输消息结构体表示一次读或写,通过一个消息数组,可以执行若干次的读写组合操作。组合读写示例: -``` +```c int32_t ret; uint8_t wbuff[2] = { 0x12, 0x13 }; uint8_t rbuff[2] = { 0 }; @@ -126,11 +134,13 @@ if (ret != 2) { > - 本函数可能会引起系统休眠,不允许在中断上下文调用 -### 关闭I2C控制器 +#### 关闭I2C控制器 I2C通信完成之后,需要关闭I2C控制器,关闭函数如下所述: +```c void I2cClose(DevHandle handle); +``` **表4** I2cClose参数和返回值描述 @@ -138,23 +148,24 @@ void I2cClose(DevHandle handle); | -------- | -------- | | handle | I2C控制器设备句柄 | +关闭I2C控制器示例: -``` +```c I2cClose(i2cHandle); /* 关闭I2C控制器 */ ``` -## 使用示例 +### 使用示例 本例程以操作开发板上的I2C设备为例,详细展示I2C接口的完整使用流程。 -本例拟对Hi3516DV300某开发板上TouchPad设备进行简单的寄存器读写访问,基本硬件信息如下: +本例拟对Hi3516DV300开发板上TouchPad设备进行简单的寄存器读写访问,基本硬件信息如下: - SOC:hi3516dv300。 -- Touch IC:I2C地址为0x38, IC内部寄存器位宽为1字节。 +- Touch IC:I2C地址为0x38,IC内部寄存器位宽为1字节。 -- 原理图信息:TouchPad设备挂接在3号I2C控制器下;IC的复位管脚为3号GPIO。 +- 硬件连接:TouchPad设备挂接在3号I2C控制器下;IC的复位管脚为3号GPIO。 本例程首先对Touch IC进行复位操作(开发板上电默认会给TouchIC供电,本例程不考虑供电),然后对其内部寄存器进行随机读写,测试I2C通路是否正常。 @@ -163,8 +174,7 @@ I2cClose(i2cHandle); /* 关闭I2C控制器 */ 示例如下: - -``` +```c #include "i2c_if.h" /* I2C标准接口头文件 */ #include "gpio_if.h" /* GPIO标准接口头文件 */ #include "hdf_log.h" /* 标准日志打印头文件 */ diff --git a/zh-cn/device-dev/driver/driver-platform-i2c-develop.md b/zh-cn/device-dev/driver/driver-platform-i2c-develop.md index fd0a6269e01b6d32f273a2628c6c793d0d6219b4..cf8fdfa72c847a500739343cf7fb49bc4aefbc76 100755 --- a/zh-cn/device-dev/driver/driver-platform-i2c-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-i2c-develop.md @@ -1,38 +1,90 @@ # I2C - ## 概述 -I2C(Inter Integrated Circuit)总线是由Philips公司开发的一种简单、双向二线制同步串行总线。在HDF框架中,I2C模块接口适配模式采用统一服务模式,这需要一个设备服务来作为I2C模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如I2C可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 +### 功能简介 + +I2C(Inter Integrated Circuit)总线是由Philips公司开发的一种简单、双向二线制同步串行总线。由于其硬件连接简单、成本低廉,因此被广泛应用于各种短距离通信的场景。 + +### 运作机制 + +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型控制器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。I2C模块即采用统一服务模式(如图1)。 + +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 + +I2C模块各分层的作用为: - **图1** I2C统一服务模式结构图 +- 接口层:提供打开设备,数据传输以及关闭设备的能力。 +- 核心层:主要负责服务绑定、初始化以及释放管理器,并提供添加、删除以及获取控制器的能力。 +- 适配层:由驱动适配者实现与硬件相关的具体功能,如控制器的初始化等。 - ![image](figures/统一服务模式结构图.png "I2C统一服务模式结构图") +**图1** I2C统一服务模式结构图 +![image](figures/统一服务模式结构图.png "I2C统一服务模式结构图") +## 使用指导 -## 接口说明 +### 场景介绍 + +I2C通常用于与各类支持I2C协议的传感器、执行器或输入输出设备进行通信。当驱动开发者需要将I2C设备适配到OpenHarmony时,需要进行I2C驱动适配,下文将介绍如何进行I2C驱动适配。 + +### 接口说明 + +为了保证上层在调用I2C接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/i2c/i2c_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 I2cMethod和I2cLockMethod定义: - -``` +```c struct I2cMethod { -int32_t (*transfer)(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count); + int32_t (*transfer)(struct I2cCntlr *cntlr, struct I2cMsg *msgs, int16_t count); +}; + +struct I2cLockMethod { // 锁机制操作结构体 + int32_t (*lock)(struct I2cCntlr *cntlr); + void (*unlock)(struct I2cCntlr *cntlr); }; -struct I2cLockMethod {// 锁机制操作结构体 - int32_t (*lock)(struct I2cCntlr *cntlr);// 加锁 - void (*unlock)(struct I2cCntlr *cntlr); // 解锁 +``` + +在适配层中,I2cMethod必须被实现,I2cLockMethod可根据实际情况考虑是否实现。核心层提供了默认的I2cLockMethod,其中使用mutex作为保护临界区的锁: + +```c +static int32_t I2cCntlrLockDefault(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return HDF_ERR_INVALID_OBJECT; + } + return OsalMutexLock(&cntlr->lock); +} + +static void I2cCntlrUnlockDefault(struct I2cCntlr *cntlr) +{ + if (cntlr == NULL) { + return; + } + (void)OsalMutexUnlock(&cntlr->lock); +} + +static const struct I2cLockMethod g_i2cLockOpsDefault = { + .lock = I2cCntlrLockDefault, + .unlock = I2cCntlrUnlockDefault, }; ``` - **表1** I2cMethod结构体成员的回调函数功能说明 +若实际情况不允许使用mutex(例如使用者可能在中断上下文调用I2C接口,mutex可能导致休眠,而中断上下文不允许休眠)时,驱动适配者可以考虑使用其他类型的锁来实现一个自定义的I2cLockMethod。一旦实现了自定义的I2cLockMethod,默认的I2cLockMethod将被覆盖。 + + **表1** I2cMethod结构体成员函数功能说明 | 函数成员 | 入参 | 出参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -------- | | transfer | cntlr:结构体指针,核心层I2C控制器。
msgs:结构体指针,用户消息。
count:uint16_t,消息数量。 | 无 | HDF_STATUS相关状态 | 传递用户消息 | + **表2** I2cLockMethod结构体成员函数功能说明 + +| 函数成员 | 入参 | 出参 | 返回值 | 功能 | +| -------- | -------- | -------- | -------- | -------- | +| lock | cntlr:结构体指针,核心层I2C控制器。 | 无 | HDF_STATUS相关状态 | 获取临界区锁 | +| unlock | cntlr:结构体指针,核心层I2C控制器。 | 无 | HDF_STATUS相关状态 | 释放临界区锁 | -## 开发步骤 +### 开发步骤 I2C模块适配的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 @@ -57,10 +109,9 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,消息传输的成功与否等。 +### 开发实例 -## 开发实例 - -下方将以i2c_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +下方将以Hi3516DV300的驱动//device/soc/hisilicon/common/platform/i2c/i2c_hi35xx.c为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 1. 驱动开发首先需要实例化驱动入口。 @@ -68,131 +119,135 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - I2C驱动入口参考: + I2C驱动入口开发参考: I2C控制器会出现很多个设备挂接的情况,因而在HDF框架中首先会为此类型的设备创建一个管理器对象,并同时对外发布一个管理器服务来统一处理外部访问。这样,用户需要打开某个设备时,会先获取到管理器服务,然后管理器服务根据用户指定参数查找到指定设备。 - I2C管理器服务的驱动由核心层实现,厂商不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的I2cCntlrAdd函数,它会实现相应功能。 + I2C管理器服务的驱动由核心层实现,驱动适配者不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的I2cCntlrAdd函数,它会实现相应功能。 - - ``` - struct HdfDriverEntry g_i2cDriverEntry = { + ```c + struct HdfDriverEntry g_i2cDriverEntry = { .moduleVersion = 1, .Init = Hi35xxI2cInit, .Release = Hi35xxI2cRelease, - .moduleName = "hi35xx_i2c_driver", // 【必要且与config.hcs文件里面匹配】 - }; - HDF_INIT(g_i2cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 - - // 核心层i2c_core.c管理器服务的驱动入口 - struct HdfDriverEntry g_i2cManagerEntry = { + .moduleName = "hi35xx_i2c_driver", // 【必要且与config.hcs文件里面匹配】 + }; + HDF_INIT(g_i2cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + + /* 核心层i2c_core.c管理器服务的驱动入口 */ + struct HdfDriverEntry g_i2cManagerEntry = { .moduleVersion = 1, .Bind = I2cManagerBind, .Init = I2cManagerInit, .Release = I2cManagerRelease, - .moduleName = "HDF_PLATFORM_I2C_MANAGER", // 这与device_info文件中device0对应 - }; - HDF_INIT(g_i2cManagerEntry); - ``` + .moduleName = "HDF_PLATFORM_I2C_MANAGER", // 这与device_info.hcs文件中device0对应 + }; + HDF_INIT(g_i2cManagerEntry); + ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在i2c_config.hcs中配置器件属性。 +2. 完成驱动入口注册之后,下一步请在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode信息,并在i2c_config.hcs中配置器件属性。 - deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层I2cCntlr相关成员的默认值或限制范围有密切关系。 + deviceNode信息与驱动入口注册相关,器件属性值对于驱动适配者的驱动实现以及核心层I2cCntlr相关成员的默认值或限制范围有密切关系。 - 统一服务模式的特点是device_info文件中第一个设备节点必须为I2C管理器,其各项参数必须如表2设置: + 统一服务模式的特点是device_info.hcs文件中第一个设备节点必须为I2C管理器,其各项参数必须如表2设置: - **表2** 统一服务模式的特点 + **表3** 统一服务模式的特点 - | 成员名 | 值 | - | -------- | -------- | - | moduleName | 固定为HDF_PLATFORM_I2C_MANAGER | - | serviceName | 固定为HDF_PLATFORM_I2C_MANAGER | - | policy | 具体配置为1或2取决于是否对用户态可见 | - | deviceMatchAttr | 没有使用,可忽略 | + | 成员名 | 值 | + | -------- | -------- | + | moduleName | 固定为HDF_PLATFORM_I2C_MANAGER | + | serviceName | 固定为HDF_PLATFORM_I2C_MANAGER | + | policy | 具体配置为1或2取决于是否对用户态可见 | + | deviceMatchAttr | 没有使用,可忽略 | - 从第二个节点开始配置具体I2C控制器信息,此节点并不表示某一路I2C控制器,而是代表一个资源性质设备,用于描述一类I2C控制器的信息。多个控制器之间相互区分的参数是busID和reg_pbase,这在i2c_config文件中有所体现。 + 从第二个节点开始配置具体I2C控制器信息,此节点并不表示某一路I2C控制器,而是代表一个资源性质设备,用于描述一类I2C控制器的信息。多个控制器之间相互区分的参数是busId和reg_pbase,这在i2c_config.hcs文件中有所体现。 - device_info.hcs配置参考 - - - ``` - root { - device_info { - match_attr = "hdf_manager"; - device_i2c :: device { - device0 :: deviceNode { - policy = 2; - priority = 50; - permission = 0644; - moduleName = "HDF_PLATFORM_I2C_MANAGER"; - serviceName = "HDF_PLATFORM_I2C_MANAGER"; - deviceMatchAttr = "hdf_platform_i2c_manager"; - } - device1 :: deviceNode { - policy = 0; // 等于0,不需要发布服务。 - priority = 55; // 驱动启动优先级。 - permission = 0644; // 驱动创建设备节点权限。 - moduleName = "hi35xx_i2c_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 - serviceName = "HI35XX_I2C_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 - deviceMatchAttr = "hisilicon_hi35xx_i2c"; //【必要】用于配置控制器私有数据,要与i2c_config.hcs中对应控制器保持一致, - // 具体的控制器信息在 i2c_config.hcs中。 - } - } - } - } - ``` - - - i2c_config.hcs 配置参考 - - - ``` - root { - platform { - i2c_config { - match_attr = "hisilicon_hi35xx_i2c"; //【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - template i2c_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 - bus = 0; //【必要】i2c识别号 - reg_pbase = 0x120b0000; //【必要】物理基地址 - reg_size = 0xd1; //【必要】寄存器位宽 - irq = 0; //【可选】根据厂商需要来使用 - freq = 400000; //【可选】根据厂商需要来使用 - clk = 50000000; //【可选】根据厂商需要来使用 - } - controller_0x120b0000 :: i2c_controller { - bus = 0; - } - controller_0x120b1000 :: i2c_controller { - bus = 1; - reg_pbase = 0x120b1000; - } - ... - } - } - } - ``` - -3. 完成驱动入口注册之后,下一步就是以核心层I2cCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化I2cCntlr成员I2cMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + + ```c + root { + device_info { + match_attr = "hdf_manager"; + device_i2c :: device { + device0 :: deviceNode { + policy = 2; + priority = 50; + permission = 0644; + moduleName = "HDF_PLATFORM_I2C_MANAGER"; + serviceName = "HDF_PLATFORM_I2C_MANAGER"; + deviceMatchAttr = "hdf_platform_i2c_manager"; + } + device1 :: deviceNode { + policy = 0; // 等于0,不需要发布服务。 + priority = 55; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + moduleName = "hi35xx_i2c_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HI35XX_I2C_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_i2c"; //【必要】用于配置控制器私有数据,要与i2c_config.hcs中对应控制器保持一致, + // 具体的控制器信息在 i2c_config.hcs中。 + } + } + } + } + ``` + + - i2c_config.hcs配置参考 + + ```c + root { + platform { + i2c_config { + match_attr = "hisilicon_hi35xx_i2c"; //【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + template i2c_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 + bus = 0; //【必要】i2c识别号 + reg_pbase = 0x120b0000; //【必要】物理基地址 + reg_size = 0xd1; //【必要】寄存器位宽 + irq = 0; //【可选】中断号,由控制器的中断特性决定是否需要 + freq = 400000; //【可选】频率,初始化硬件控制器的可选参数 + clk = 50000000; //【可选】控制器时钟,由控制器时钟的初始化流程决定是否需要 + } + controller_0x120b0000 :: i2c_controller { + bus = 0; + } + controller_0x120b1000 :: i2c_controller { + bus = 1; + reg_pbase = 0x120b1000; + } + ... + } + } + } + ``` + + 需要注意的是,新增i2c_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中i2c_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/i2c/i2c_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/i2c/i2c_config.hcs" // 配置文件相对路径 + ``` + +3. 完成驱动入口注册之后,下一步就是以核心层I2cCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化I2cCntlr成员I2cMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 - 自定义结构体参考 从驱动的角度看,自定义结构体是参数和数据的载体,而且i2c_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层I2cCntlr对象,例如设备号、总线号等。 - - ``` - // 厂商自定义功能结构体 + ```c + /* 驱动适配者自定义结构体 */ struct Hi35xxI2cCntlr { struct I2cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面。 - OsalSpinlock spin; // 【必要】厂商需要基于此锁变量对各个i2c操作函数实现对应的加锁解锁。 + OsalSpinlock spin; // 【必要】驱动适配者需要基于此锁变量对各个i2c操作函数实现对应的加锁解锁。 volatile unsigned char *regBase; // 【必要】寄存器基地址 uint16_t regSize; // 【必要】寄存器位宽 int16_t bus; // 【必要】i2c_config.hcs文件中可读取具体值 - uint32_t clk; // 【可选】厂商自定义 - uint32_t freq; // 【可选】厂商自定义 - uint32_t irq; // 【可选】厂商自定义 + uint32_t clk; // 【可选】驱动适配者自定义 + uint32_t freq; // 【可选】驱动适配者自定义 + uint32_t irq; // 【可选】驱动适配者自定义 uint32_t regBasePhy; // 【必要】寄存器物理基地址 }; - // I2cCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + /* I2cCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。*/ struct I2cCntlr { struct OsalMutex lock; void *owner; @@ -202,31 +257,32 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 const struct I2cLockMethod *lockOps; }; ``` - - I2cCntlr成员回调函数结构体I2cMethod的实例化,和锁机制回调函数结构体I2cLockMethod实例化,其他成员在Init函数中初始化。 - - ``` - // i2c_hi35xx.c中的示例 + - I2cCntlr成员钩子函数结构体I2cMethod的实例化,和锁机制钩子函数结构体I2cLockMethod实例化,其他成员在Init函数中初始化。 + + ```c + /* i2c_hi35xx.c中的示例 */ static const struct I2cMethod g_method = { .transfer = Hi35xxI2cTransfer, }; static const struct I2cLockMethod g_lockOps = { - .lock = Hi35xxI2cLock, // 加锁函数 - .unlock = Hi35xxI2cUnlock,// 解锁函数 + .lock = Hi35xxI2cLock, // 加锁函数 + .unlock = Hi35xxI2cUnlock, // 解锁函数 }; ``` - - Init函数参考 + + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 - **表3** Init函数入参及返回值参考 + **表4** Init函数入参及返回值参考 | 状态(值) | 问题描述 | | -------- | -------- | @@ -241,12 +297,11 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 初始化自定义结构体对象,初始化I2cCntlr成员,调用核心层I2cCntlrAdd函数,接入VFS(可选)。 - - ``` + ```c static int32_t Hi35xxI2cInit(struct HdfDeviceObject *device) { ... - // 遍历、解析i2c_config.hcs中的所有配置节点,并分别进行初始化,需要调用Hi35xxI2cParseAndInit函数。 + /* 遍历、解析i2c_config.hcs中的所有配置节点,并分别进行初始化,需要调用Hi35xxI2cParseAndInit函数。*/ DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { ret = Hi35xxI2cParseAndInit(device, childNode);//函数定义见下 ... @@ -257,11 +312,11 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 static int32_t Hi35xxI2cParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) { struct Hi35xxI2cCntlr *hi35xx = NULL; - ... + ... // 入参判空 hi35xx = (struct Hi35xxI2cCntlr *)OsalMemCalloc(sizeof(*hi35xx)); // 内存分配 - ... + ... // 返回值校验 hi35xx->regBase = OsalIoRemap(hi35xx->regBasePhy, hi35xx->regSize); // 地址映射 - ... + ... // 返回值校验 Hi35xxI2cCntlrInit(hi35xx); // 【必要】i2c设备的初始化 hi35xx->cntlr.priv = (void *)node; // 【必要】存储设备属性 @@ -269,13 +324,13 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 hi35xx->cntlr.ops = &g_method; // 【必要】I2cMethod的实例化对象的挂载 hi35xx->cntlr.lockOps = &g_lockOps; // 【必要】I2cLockMethod的实例化对象的挂载 (void)OsalSpinInit(&hi35xx->spin); // 【必要】锁的初始化 - ret = I2cCntlrAdd(&hi35xx->cntlr); // 【必要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 + ret = I2cCntlrAdd(&hi35xx->cntlr); // 【必要】调用此函数将控制器对象添加至平台核心层,返回成功信号后驱动才完全接入平台核心层。 ... #ifdef USER_VFS_SUPPORT - (void)I2cAddVfsById(hi35xx->cntlr.busId);// 【可选】若支持用户级的虚拟文件系统,则接入。 + (void)I2cAddVfsById(hi35xx->cntlr.busId); // 【可选】若支持用户级的虚拟文件系统,则接入。 #endif return HDF_SUCCESS; - __ERR__: // 不成功的话,需要反向执行初始化相关函数。 + __ERR__: // 若不成功,需要回滚函数内已执行的操作(如取消IO映射、释放内存等),并返回错误码 if (hi35xx != NULL) { if (hi35xx->regBase != NULL) { OsalIoUnmap((void *)hi35xx->regBase); @@ -287,11 +342,12 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 return ret; } ``` - - Release函数参考 + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -301,26 +357,25 @@ I2C模块适配的三个必选环节是实例化驱动入口,配置属性文 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 - - ``` + ```c static void Hi35xxI2cRelease(struct HdfDeviceObject *device) { ... - // 与Hi35xxI2cInit一样,需要将对每个节点分别进行释放。 + /* 与Hi35xxI2cInit一样,需要将每个节点分别进行释放。*/ DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { - Hi35xxI2cRemoveByNode(childNode);// 函数定义见下 + Hi35xxI2cRemoveByNode(childNode); // 函数定义如下 } } static void Hi35xxI2cRemoveByNode(const struct DeviceResourceNode *node) { ... - // 【必要】可以调用I2cCntlrGet函数通过设备的busid获取I2cCntlr对象,以及调用I2cCntlrRemove函数来释放I2cCntlr对象的内容。 + /* 【必要】可以调用I2cCntlrGet函数通过设备的bus号获取I2cCntlr对象的指针,以及调用I2cCntlrRemove函数将I2cCntlr对象从平台核心层移除。*/ cntlr = I2cCntlrGet(bus); if (cntlr != NULL && cntlr->priv == node) { ... I2cCntlrRemove(cntlr); - // 【必要】解除地址映射,锁和内存的释放。 + /* 【必要】解除地址映射,释放锁和内存。*/ hi35xx = (struct Hi35xxI2cCntlr *)cntlr; OsalIoUnmap((void *)hi35xx->regBase); (void)OsalSpinDestroy(&hi35xx->spin); diff --git a/zh-cn/device-dev/driver/driver-platform-i3c-des.md b/zh-cn/device-dev/driver/driver-platform-i3c-des.md index 24d7f0bd02a15e1942680cd80a19556bbdc2d0f3..0926a9a2be4976b86ab3c107cf356480d5b3a88c 100755 --- a/zh-cn/device-dev/driver/driver-platform-i3c-des.md +++ b/zh-cn/device-dev/driver/driver-platform-i3c-des.md @@ -35,7 +35,7 @@ I3C接口定义了完成I3C传输的通用方法集合,包括: ### 运作机制 -在HDF框架中,I3C模块接口适配模式采用统一服务模式,这需要一个设备服务来作为I3C模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如I3C可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 +在HDF框架中,I3C模块接口适配模式采用统一服务模式,这需要一个设备服务来作为I3C模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如I3C可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。 相比于I2C,I3C总线拥有更高的速度、更低的功耗,支持带内中断、从设备热接入以及切换当前主设备,同时向后兼容I2C从设备。一路I3C总线上,可以连接多个设备,这些设备可以是I2C从设备、I3C从设备和I3C次级主设备,但只能同时存在一个主设备,一般为控制器本身。 @@ -44,38 +44,41 @@ I3C接口定义了完成I3C传输的通用方法集合,包括: ### 约束与限制 -I3C模块当前仅支持轻量和小型系统内核(LiteOS)。 +I3C模块当前仅支持轻量和小型系统内核(LiteOS-A),不支持在用户态使用。 ## 使用指导 ### 场景介绍 I3C可连接单个或多个I3C、I2C从器件,它主要用于: -1. 与传感器通信,如陀螺仪、气压计或支持I3C协议的图像传感器等; -2. 通过软件或硬件协议转换,与其他接口(如 UART 串口等)的设备进行通信。 + +- 与传感器通信,如陀螺仪、气压计或支持I3C协议的图像传感器等; +- 通过软件或硬件协议转换,与其他接口(如 UART 串口等)的设备进行通信。 ### 接口说明 +I3C模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/i3c_if.h。 + **表 1** I3C驱动API接口功能介绍 -| 接口名 | 描述 | +| 接口名 | 接口描述 | | ------------- | ----------------- | -| I3cOpen | 打开I3C控制器 | -| I3cClose | 关闭I3C控制器 | -| I3cTransfer | 自定义传输 | -| I3cSetConfig | 配置I3C控制器 | -| I3cGetConfig | 获取I3C控制器配置 | -| I3cRequestIbi | 请求带内中断 | -| I3cFreeIbi | 释放带内中断 | +| DevHandle I3cOpen(int16_t number) | 打开I3C控制器 | +| void I3cClose(DevHandle handle) | 关闭I3C控制器 | +| int32_t I3cTransfer(DevHandle handle, struct I3cMsg \*msg, int16_t count, enum TransMode mode) | 自定义传输 | +| int32_t I3cSetConfig(DevHandle handle, struct I3cConfig \*config) | 配置I3C控制器 | +| int32_t I3cGetConfig(DevHandle handle, struct I3cConfig \*config) | 获取I3C控制器配置 | +| int32_t I3cRequestIbi(DevHandle handle, uint16_t addr, I3cIbiFunc func, uint32_t payload) | 请求带内中断 | +| int32_t I3cFreeIbi(DevHandle handle, uint16_t addr) | 释放带内中断 | >![](../public_sys-resources/icon-note.gif) **说明:**
>本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 ### 开发步骤 -I3C的使用流程如[图2](#fig2)所示。 +I3C的使用流程如图2所示。 **图 2** I3C使用流程图 ![](figures/I3C使用流程图.png "I3C使用流程图") @@ -111,65 +114,15 @@ if (i3cHandle == NULL) { } ``` -#### 进行I3C通信 - -消息传输 -```c -int32_t I3cTransfer(DevHandle handle, struct I3cMsg *msgs, int16_t count, enum TransMode mode); -``` - -**表 3** I3cTransfer参数和返回值描述 - - - -| 参数 | 参数描述 | -| ---------- | -------------------------------------------- | -| handle | I3C控制器句柄 | -| msgs | 待传输数据的消息结构体数组 | -| count | 消息数组长度 | -| mode | 传输模式,0:I2C模式;1:I3C模式;2:发送CCC | -| **返回值** | **返回值描述** | -| 正整数 | 成功传输的消息结构体数目 | -| 负数 | 执行失败 | - -I3C传输消息类型为I3cMsg,每个传输消息结构体表示一次读或写,通过一个消息数组,可以执行若干次的读写组合操作。 - -```c -int32_t ret; -uint8_t wbuff[2] = { 0x12, 0x13 }; -uint8_t rbuff[2] = { 0 }; -struct I3cMsg msgs[2]; /* 自定义传输的消息结构体数组 */ -msgs[0].buf = wbuff; /* 写入的数据 */ -msgs[0].len = 2; /* 写入数据长度为2 */ -msgs[0].addr = 0x3F; /* 写入设备地址为0x3F */ -msgs[0].flags = 0; /* 传输标记为0,默认为写 */ -msgs[1].buf = rbuff; /* 要读取的数据 */ -msgs[1].len = 2; /* 读取数据长度为2 */ -msgs[1].addr = 0x3F; /* 读取设备地址为0x3F */ -msgs[1].flags = I3C_FLAG_READ /* I3C_FLAG_READ置位 */ -/* 进行一次I2C模式自定义传输,传输的消息个数为2 */ -ret = I3cTransfer(i3cHandle, msgs, 2, I2C_MODE); -if (ret != 2) { - HDF_LOGE("I3cTransfer: failed, ret %d\n", ret); - return; -} -``` - ->![](../public_sys-resources/icon-caution.gif) **注意:** ->- I3cMsg结构体中的设备地址不包含读写标志位,读写信息由flags成员变量的读写控制位传递。 ->- 本函数不对消息结构体个数做限制,其最大个数度由具体I3C控制器决定。 ->- 本函数不对每个消息结构体中的数据长度做限制,同样由具体I3C控制器决定。 ->- 本函数可能会引起系统休眠,禁止在中断上下文调用。 - #### 获取I3C控制器配置 ```c int32_t I3cGetConfig(DevHandle handle, struct I3cConfig *config); ``` -**表 4** I3cGetConfig参数和返回值描述 +**表 3** I3cGetConfig参数和返回值描述 - + | 参数 | 参数描述 | | ---------- | -------------- | @@ -197,9 +150,9 @@ if (ret != HDF_SUCCESS) { int32_t I3cSetConfig(DevHandle handle, struct I3cConfig *config); ``` -**表 5** I3cSetConfig参数和返回值描述 +**表 4** I3cSetConfig参数和返回值描述 - + | 参数 | 参数描述 | | ---------- | -------------- | @@ -223,6 +176,56 @@ if (ret != HDF_SUCCESS) { } ``` +#### 进行I3C通信 + +消息传输 +```c +int32_t I3cTransfer(DevHandle handle, struct I3cMsg *msgs, int16_t count, enum TransMode mode); +``` + +**表 5** I3cTransfer参数和返回值描述 + + + +| 参数 | 参数描述 | +| ---------- | -------------------------------------------- | +| handle | I3C控制器句柄 | +| msgs | 待传输数据的消息结构体数组 | +| count | 消息数组长度 | +| mode | 传输模式,0:I2C模式;1:I3C模式;2:发送CCC | +| **返回值** | **返回值描述** | +| 正整数 | 成功传输的消息结构体数目 | +| 负数 | 执行失败 | + +I3C传输消息类型为I3cMsg,每个传输消息结构体表示一次读或写,通过一个消息数组,可以执行若干次的读写组合操作。 + +```c +int32_t ret; +uint8_t wbuff[2] = { 0x12, 0x13 }; +uint8_t rbuff[2] = { 0 }; +struct I3cMsg msgs[2]; /* 自定义传输的消息结构体数组 */ +msgs[0].buf = wbuff; /* 写入的数据 */ +msgs[0].len = 2; /* 写入数据长度为2 */ +msgs[0].addr = 0x3F; /* 写入设备地址为0x3F */ +msgs[0].flags = 0; /* 传输标记为0,默认为写 */ +msgs[1].buf = rbuff; /* 要读取的数据 */ +msgs[1].len = 2; /* 读取数据长度为2 */ +msgs[1].addr = 0x3F; /* 读取设备地址为0x3F */ +msgs[1].flags = I3C_FLAG_READ /* I3C_FLAG_READ置位 */ +/* 进行一次I2C模式自定义传输,传输的消息个数为2 */ +ret = I3cTransfer(i3cHandle, msgs, 2, I2C_MODE); +if (ret != 2) { + HDF_LOGE("I3cTransfer: failed, ret %d\n", ret); + return; +} +``` + +>![](../public_sys-resources/icon-caution.gif) **注意:** +>- I3cMsg结构体中的设备地址不包含读写标志位,读写信息由flags成员变量的读写控制位传递。 +>- 本函数不对消息结构体个数做限制,其最大个数度由具体I3C控制器决定。 +>- 本函数不对每个消息结构体中的数据长度做限制,同样由具体I3C控制器决定。 +>- 本函数可能会引起系统休眠,禁止在中断上下文调用。 + #### 请求IBI(带内中断) ```c @@ -310,9 +313,9 @@ I3C通信完成之后,需要关闭I3C控制器,关闭函数如下所示: void I3cClose(DevHandle handle); ``` -**表 4** I3cClose参数和返回值描述 +**表 8** I3cClose参数和返回值描述 - + | 参数 | 参数描述 | | ---------- | -------------- | @@ -326,15 +329,13 @@ I3cClose(i3cHandle); /* 关闭I3C控制器 */ ## 使用实例 -本例程以操作开发板上的I3C设备为例,详细展示I3C接口的完整使用流程。 - -由于Hi3516DV300系列SOC没有I3C控制器,本例拟在Hi3516DV300某开发板上对虚拟驱动进行简单的传输操作,基本硬件信息如下: +本例程以操作Hi3516DV300开发板上的I3C虚拟设备为例,详细展示I3C接口的完整使用流程,基本硬件信息如下。 - SOC:hi3516dv300。 -- 虚拟:I3C地址为0x3f, 寄存器位宽为1字节。 +- 虚拟I3C设备:I3C地址为0x3f, 寄存器位宽为1字节。 -- 原理图信息:虚拟I3C设备挂接在18号和19号I3C控制器下。 +- 硬件连接:虚拟I3C设备挂接在18号和19号I3C控制器下。 本例程进行简单的I3C传输,测试I3C通路是否正常。 diff --git a/zh-cn/device-dev/driver/driver-platform-i3c-develop.md b/zh-cn/device-dev/driver/driver-platform-i3c-develop.md index cb91d218e6ce2baa475efed246cf8d2d1d2f1725..125f67535d37a6a4ae9bbbf8303a69155fde5b0a 100755 --- a/zh-cn/device-dev/driver/driver-platform-i3c-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-i3c-develop.md @@ -6,7 +6,7 @@ I3C(Improved Inter Integrated Circuit)总线是由MIPI Alliance开发的一种简单、低成本的双向二线制同步串行总线。 -I3C是两线双向串行总线,针对多个传感器从设备进行了优化,并且一次只能由一个I3C主设备控制。 相比于I2C,I3C总线拥有更高的速度、更低的功耗,支持带内中断、从设备热接入以及切换当前主设备,同时向后兼容I2C从设备。 +I3C是两线双向串行总线,针对多个传感器从设备进行了优化,并且一次只能由一个I3C主设备控制。相比于I2C,I3C总线拥有更高的速度、更低的功耗,支持带内中断、从设备热接入以及切换当前主设备,同时向后兼容I2C从设备。I3C增加了带内中断(In-Bind Interrupt)功能,支持I3C设备进行热接入操作,弥补了I2C总线需要额外增加中断线来完成中断的不足。I3C总线上允许同时存在I2C设备、I3C从设备和I3C次级主设备。 ### 基本概念 @@ -16,11 +16,11 @@ I3C是两线双向串行总线,针对多个传感器从设备进行了优化 - DAA(Dynamic Address Assignment):动态地址分配。 - I3C支持对从设备地址进行动态分配从而避免地址冲突。在分配动态地址之前,连接到I3C总线上的每个I3C设备都应以两种方式之一来唯一标识: + I3C支持对从设备地址进行动态分配从而避免地址冲突。在分配动态地址之前,连接到I3C总线上的每个I3C/I2C设备都应以两种方式之一来唯一标识: - 设备可能有一个符合I2C规范的静态地址,主机可以使用此静态地址。 - - 在任何情况下,设备均应具有48位的临时ID。除非设备具有静态地址且主机使用静态地址,否则主机应使用此48位临时ID。 + - 在任何情况下,I3C设备均应具有48位的临时ID。除非设备具有静态地址且主机使用静态地址,否则主机应使用此48位临时ID。 - CCC(Common Command Code):通用命令代码。 @@ -37,31 +37,39 @@ I3C是两线双向串行总线,针对多个传感器从设备进行了优化 ### 运作机制 -在HDF框架中,同类型控制器对象较多时(可能同时存在十几个同类型控制器),如果采用独立服务模式则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。I3C模块接口适配模式采用统一服务模式(如图1所示)。 +在HDF框架中,同类型控制器对象较多时(可能同时存在十几个同类型控制器),如果采用独立服务模式则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。I3C模块采用统一服务模式(如图1)。 I3C模块各分层的作用为: -- 接口层提供打开控制器、传输消息、获取和设置控制器参数以及关闭控制器的接口。 -- 核心层主要提供绑定设备、初始化设备以及释放设备的能力。 -- 适配层实现其他具体的功能。 - **图 1** I3C统一服务模式 +- 接口层:提供打开设备,写入数据,关闭设备的能力。 +- 核心层:主要负责服务绑定、初始化以及释放管理器,并提供添加、删除以及获取控制器的能力。由于框架需要统一管理I3C总线上挂载的所有设备,因此还提供了添加、删除以及获取设备的能力,以及中断回调函数。 +- 适配层:由驱动适配者实现与硬件相关的具体功能,如控制器的初始化等。 + +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 + + **图 1** I3C统一服务模式结构图 ![image1](figures/统一服务模式结构图.png) ### 约束与限制 -I3C模块当前仅支持轻量和小型系统内核(LiteOS) 。 +I3C模块当前仅支持轻量和小型系统内核(LiteOS-A) 。 ## 开发指导 ### 场景介绍 I3C可连接单个或多个I3C、I2C从器件,它主要用于: + - 与传感器通信,如陀螺仪、气压计或支持I3C协议的图像传感器等。 - 通过软件或硬件协议转换,与其他通信接口(如UART串口等)的设备进行通信。 +当驱动开发者需要将I3C设备适配到OpenHarmony时,需要进行I3C驱动适配,下文将介绍如何进行I3C驱动适配。 + ### 接口说明 +为了保证上层在调用I3C接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/i3c/i3c_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 + I3cMethod定义: ```c struct I3cMethod { @@ -75,7 +83,7 @@ struct I3cMethod { }; ``` -**表1** I3cMethod结构体成员的回调函数功能说明 +**表1** I3cMethod结构体成员的钩子函数功能说明 |函数成员|入参|出参|返回值|功能| |-|-|-|-|-| |sendCccCmd| **cntlr**:结构体指针,核心层I3C控制器
**ccc**:传入的通用命令代码结构体指针 | **ccc**:传出的通用命令代码结构体指针 | HDF_STATUS相关状态|发送CCC(Common command Code,即通用命令代码)| @@ -98,54 +106,53 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加i3c_config.hcs器件属性文件。 - + - 实例化I3C控制器对象: - 初始化I3cCntlr成员。 - 实例化I3cCntlr成员I3cMethod方法集合,其定义和成员函数说明见下文。 - + - 注册中断处理子程序: 为控制器注册中断处理程序,实现设备热接入和IBI(带内中断)功能。 1. 实例化驱动入口 - 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 - + 驱动入口必须为HdfDriverEntry(在//drivers/hdf_core/framework/include/core/hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - + I3C驱动入口参考: - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> I3C控制器会出现很多个控制器挂接的情况,因而在HDF框架中首先会为此类型的控制器创建一个管理器对象,并同时对外发布一个管理器服务来统一处理外部访问。这样,用户需要打开某个控制器时,会先获取到管理器服务,然后管理器服务根据用户指定参数查找到指定控制器。 > - > I3C管理器服务的驱动由核心层实现,厂商不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的I3cCntlrAdd函数,它会实现相应功能。 + > I3C管理器服务的驱动由核心层实现,驱动适配者不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的I3cCntlrAdd函数,它会实现相应功能。 ```c static struct HdfDriverEntry g_virtualI3cDriverEntry = { .moduleVersion = 1, .Init = VirtualI3cInit, .Release = VirtualI3cRelease, - .moduleName = "virtual_i3c_driver", // 【必要且与hcs文件中的名字匹配】 + .moduleName = "virtual_i3c_driver", // 【必要且与hcs文件中的名字匹配】 }; - HDF_INIT(g_virtualI3cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_virtualI3cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 /* 核心层i3c_core.c管理器服务的驱动入口 */ struct HdfDriverEntry g_i3cManagerEntry = { .moduleVersion = 1, .Init = I3cManagerInit, .Release = I3cManagerRelease, - .moduleName = "HDF_PLATFORM_I3C_MANAGER",// 这与device_info文件中device0对应 + .moduleName = "HDF_PLATFORM_I3C_MANAGER", // 这与device_info.hcs文件中device0对应 }; HDF_INIT(g_i3cManagerEntry); ``` 2. 配置属性文件 - 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在i3c_config.hcs中配置器件属性。 + 完成驱动入口注册之后,下一步请在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode信息,并在i3c_config.hcs中配置器件属性。 - deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层I3cCntlr相关成员的默认值或限制范围有密切关系。 + deviceNode信息与驱动入口注册相关,器件属性值对于驱动适配者的驱动实现以及核心层I3cCntlr相关成员的默认值或限制范围有密切关系。 - 统一服务模式的特点是device_info文件中第一个设备节点必须为I3C管理器,其各项参数必须如下设置: + 统一服务模式的特点是device_info.hcs文件中第一个设备节点必须为I3C管理器,其各项参数必须如下设置: |成员名|值| |-|-| @@ -154,7 +161,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 |policy|0| |cntlrMatchAttr| 无(预留)| - 从第二个节点开始配置具体I3C控制器信息,此节点并不表示某一路I3C控制器,而是代表一个资源性质设备,用于描述一类I3C控制器的信息。本例只有一个I3C控制器,如有多个控制器,则需要在device_info文件增加deviceNode信息,以及在i3c_config文件中增加对应的器件属性。 + 从第二个节点开始配置具体I3C控制器信息,此节点并不表示某一路I3C控制器,而是代表一个资源性质设备,用于描述一类I3C控制器的信息。本例只有一个I3C控制器,如有多个控制器,则需要在device_info.hcs文件增加deviceNode信息,以及在i3c_config文件中增加对应的器件属性。 - device_info.hcs配置参考 @@ -207,13 +214,21 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 } ``` + 需要注意的是,新增i3c_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中i3c_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/i3c/i3c_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/i3c/i3c_config.hcs" // 配置文件相对路径 + ``` + 3. 实例化I3C控制器对象 - 配置属性文件完成后,要以核心层I3cCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化I3cCntlr成员I3cMethod(让用户可以通过接口来调用驱动底层函数)。 + 配置属性文件完成后,要以核心层I3cCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化I3cCntlr成员I3cMethod(让用户可以通过接口来调用驱动底层函数)。 此步骤需要通过实现HdfDriverEntry成员函数(Bind,Init,Release)来完成。 - I3cCntlr成员回调函数结构体I3cMethod的实例化,I3cLockMethod回调函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 + I3cCntlr成员钩子函数结构体I3cMethod的实例化,I3cLockMethod钩子函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 - 自定义结构体参考 @@ -222,11 +237,11 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 ```c struct VirtualI3cCntlr { - struct I3cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面。 - volatile unsigned char *regBase;// 【必要】寄存器基地址 - uint32_t regBasePhy; // 【必要】寄存器物理基地址 - uint32_t regSize; // 【必要】寄存器位宽 - uint16_t busId; // 【必要】设备号 + struct I3cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面。 + volatile unsigned char *regBase; // 【必要】寄存器基地址 + uint32_t regBasePhy; // 【必要】寄存器物理基地址 + uint32_t regSize; // 【必要】寄存器位宽 + uint16_t busId; // 【必要】设备号 uint16_t busMode; uint16_t IrqNum; uint32_t i3cMaxRate; @@ -249,17 +264,15 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 }; ``` - - - - Init函数参考 + - Init函数开发参考 **入参:** - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 **返回值:** - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 |状态(值)|问题描述| @@ -279,7 +292,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 static int32_t VirtualI3cParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) { int32_t ret; - struct VirtualI3cCntlr *virtual = NULL; // 【必要】自定义结构体对象 + struct VirtualI3cCntlr *virtual = NULL; // 【必要】自定义结构体对象 (void)device; virtual = (struct VirtualI3cCntlr *)OsalMemCalloc(sizeof(*virtual)); // 【必要】内存分配 @@ -288,7 +301,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 return HDF_ERR_MALLOC_FAIL; } - ret = VirtualI3cReadDrs(virtual, node); // 【必要】将i3c_config文件的默认值填充到结构体中 + ret = VirtualI3cReadDrs(virtual, node); // 【必要】将i3c_config文件的默认值填充到结构体中,函数定义见下方 if (ret != HDF_SUCCESS) { HDF_LOGE("%s: Read drs fail! ret:%d", __func__, ret); goto __ERR__; @@ -342,13 +355,40 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 return ret; } + + static int32_t VirtualI3cReadDrs(struct VirtualI3cCntlr *virtual, const struct DeviceResourceNode *node) + { + struct DeviceResourceIface *drsOps = NULL; + + /* 获取drsOps方法 */ + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetUint16 == NULL) { + HDF_LOGE("%s: Invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + /* 将配置参数依次读出,并填充至结构体中 */ + if (drsOps->GetUint16(node, "busId", &virtual->busId, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: Read busId fail!", __func__); + return HDF_ERR_IO; + } + if (drsOps->GetUint16(node, "busMode", &virtual->busMode, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: Read busMode fail!", __func__); + return HDF_ERR_IO; + } + if (drsOps->GetUint16(node, "IrqNum", &virtual->IrqNum, 0) != HDF_SUCCESS) { + HDF_LOGE("%s: Read IrqNum fail!", __func__); + return HDF_ERR_IO; + } + ··· + return HDF_SUCCESS; + } ``` - - Release函数参考 + - Release函数开发参考 **入参:** - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 **返回值:** @@ -386,8 +426,8 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 cntlr = I3cCntlrGet(busId); if (cntlr != NULL && cntlr->priv == node) { I3cCntlrPut(cntlr); - I3cCntlrRemove(cntlr); // 【必要】主要是从管理器驱动那边移除I3cCntlr对象 - virtual = (struct VirtualI3cCntlr *)cntlr;// 【必要】通过强制转换获取自定义的对象并进行release操作 + I3cCntlrRemove(cntlr); // 【必要】主要是从管理器驱动那边移除I3cCntlr对象 + virtual = (struct VirtualI3cCntlr *)cntlr; // 【必要】通过强制转换获取自定义的对象并进行release操作 (void)OsalSpinDestroy(&virtual->spin); OsalMemFree(virtual); } @@ -405,7 +445,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 return; } ... - // 遍历、解析i3c_config.hcs中的所有配置节点,并分别进行release操作 + /* 遍历、解析i3c_config.hcs中的所有配置节点,并分别进行release操作 */ DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { VirtualI3cRemoveByNode(childNode); //函数定义如上 } @@ -438,12 +478,10 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 HDF_LOGD("%s: Reserved address which is not supported!", __func__); break; } - + return HDF_SUCCESS; } - ``` - - ```c + static int32_t I3cIbiHandle(uint32_t irq, void *data) { struct VirtualI3cCntlr *virtual = NULL; diff --git a/zh-cn/device-dev/driver/driver-platform-mipicsi-des.md b/zh-cn/device-dev/driver/driver-platform-mipicsi-des.md index 7fb0abc67f48187518dc435dbcff153f92bf9a3c..31aad8035c3f0b6eafdfafbc93a93b5dcb3a61a1 100755 --- a/zh-cn/device-dev/driver/driver-platform-mipicsi-des.md +++ b/zh-cn/device-dev/driver/driver-platform-mipicsi-des.md @@ -1,7 +1,8 @@ -# MIPI CSI +# MIPI CSI +## 概述 -## 概述 +### 功能简介 CSI(Camera Serial Interface)是由MIPI联盟下Camera工作组指定的接口标准。CSI-2是MIPI CSI第二版,主要由应用层、协议层、物理层组成,最大支持4通道数据传输、单线传输速度高达1Gb/s。 @@ -9,12 +10,62 @@ CSI(Camera Serial Interface)是由MIPI联盟下Camera工作组指定的接 图1显示了简化的CSI接口。D-PHY采用1对源同步的差分时钟和1~4对差分数据线来进行数据传输。数据传输采用DDR方式,即在时钟的上下边沿都有数据传输。 - **图 1** CSI发送、接收接口 - ![](figures/CSI发送-接收接口.png) +**图1** CSI发送、接收接口 +![](figures/CSI发送-接收接口.png) -### ComboDevAttr结构体 +MIPI CSI标准分为应用层、协议层与物理层,协议层又细分为像素字节转换层、低级协议层、Lane管理层。 -**表** **1** ComboDevAttr结构体介绍 +- 物理层(PHY Layer) + + PHY层指定了传输媒介,在电气层面从串行bit流中捕捉“0”与“1”,同时生成SoT与EoT等信号。 + +- 协议层(Protocol Layer) + + 协议层由三个子层组成,每个子层有不同的职责。CSI-2协议能够在host侧处理器上用一个单独的接口处理多条数据流。协议层规定了多条数据流该如何标记和交织起来,以便每条数据流能够被正确地恢复出来。 + + - 像素字节转换层(Pixel/Byte Packing/Unpacking Layer) + + CSI-2规范支持多种不同像素格式的图像应用。在发送方中,本层在发送数据到Low Level Protocol层之前,将来自应用层的像素封包为字节数据。在接收方中,本层在发送数据到应用层之前,将来自Low Level Protocol层的字节数据解包为像素。8位的像素数据在本层中传输时保持不变。 + + - 低级协议层(Low Level Protocol) + + LLP主要包含了在SoT和EoT事件之间的bit和byte级别的同步方法,以及和下一层传递数据的方法。LLP最小数据粒度是1个字节。LLP也包含了一个字节内的bit值解析,即Endian(大小端里的Endian的意思)的处理。 + + - Lane管理层(Lane Management) + + CSI-2的Lane是可扩展的。具体的数据Lane的数量规范并没有给出限制,具体根据应用的带宽需求而定。发送侧分发(distributor功能)来自出口方向数据流的字节到1条或多条Lane上。接收侧则从一条或多条Lane中收集字节并合并(merge功能)到一个数据流上,复原出原始流的字节顺序。对于C-PHY物理层来说,本层专门分发字节对(16 bits)到数据Lane或从数据Lane中收集字节对。基于每Lane的扰码功能是可选特性。 + + 协议层的数据组织形式是包(packet)。接口的发送侧会增加包头(header)和错误校验(error-checking)信息到即将被LLP发送的数据上。接收侧在LLP将包头剥掉,包头会被接收器中对应的逻辑所解析。错误校验信息可以用来做入口数据的完整性检查。 + +- 应用层(Application Layer) + + 本层描述了更高层级的应用对于数据中的数据的处理,规范并不涵盖应用层。CSI-2规范只给出了像素值和字节的映射关系。 + +### 运作机制 + +MIPI CSI模块各分层的作用为:接口层提供打开设备、写入数据和关闭设备的接口。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其它具体的功能。 + +![](../public_sys-resources/icon-note.gif) **说明:**
核心层可以调用接口层的函数,核心层通过钩子函数调用适配层函数,从而适配层可以间接的调用接口层函数,但是不可逆转接口层调用适配层函数。 + +**图2**CSI无服务模式结构图 + +![image](figures/无服务模式结构图.png "CSI无服务模式结构图") + +### 约束与限制 + +由于使用无服务模式,MIPI_CSI接口暂不支持用户态使用。 + +## 使用指导 + +### 场景介绍 + +MIPI CSI主要用于连接摄像头组件。 + +### 接口说明 + +MIPI CSI模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/mipi_csi_if.h。 + +**表1** ComboDevAttr结构体介绍 @@ -27,47 +78,51 @@ CSI(Camera Serial Interface)是由MIPI联盟下Camera工作组指定的接 | MIPIAttr | Mipi设备属性 | | lvdsAttr | LVDS/SubLVDS/HiSPi设备属性 | -### ExtDataType结构体 - -**表** **2** ExtDataType结构体介绍 +**表2** ExtDataType结构体介绍 | 名称 | 描述 | | --------------- | ------------------------------- | | devno | 设备号 | -| num | sensor号 | +| num | Sensor号 | | extDataBitWidth | 图片的位深 | | extDataType | 定义YUV和原始数据格式以及位深度 | -### 接口说明 - -**表 3** MIPI CSI API接口功能介绍 +**表3** MIPI CSI API接口功能介绍 - | 功能分类 | 接口名 | +| 接口名 | 接口描述 | | -------- | -------- | -| 获取/释放MIPI CSI控制器操作句柄 | MipiCsiOpen:获取MIPI CSI控制器操作句柄
MipiCsiClose:释放MIPI CSI控制器操作句柄 | -| MIPI CSI相应配置 | MipiCsiSetComboDevAttr:设置MIPI,CMOS或者LVDS相机的参数给控制器,参数包括工作模式,图像区域,图像深度,数据速率和物理通道等
MipiCsiSetExtDataType(可选):设置YUV和RAW数据格式和位深
MipiCsiSetHsMode:设置MIPI RX的Lane分布。根据硬件连接的形式选择具体的mode
MipiCsiSetPhyCmvmode:设置共模电压模式 | -| 复位/撤销复位Sensor | MipiCsiResetSensor:复位Sensor
MipiCsiUnresetSensor:撤销复位Sensor | -| 复位/撤销复位MIPI RX | MipiCsiResetRx:复位MIPI RX。不同的s32WorkingViNum有不同的enSnsType
MipiCsiUnresetRx:撤销复位MIPI RX | -| 使能/关闭MIPI的时钟 | MipiCsiEnableClock:使能MIPI的时钟。根据上层函数电泳传递的enSnsType参数决定是用MIPI还是LVDS
MipiCsiDisableClock:关闭MIPI设备的时钟 | -| 使能/禁用MIPI上的Sensor时钟 | MipiCsiEnableSensorClock:使能MIPI上的Sensor时钟
MipiCsiDisableSensorClock:关闭Sensor的时钟 | +| DevHandle MipiCsiOpen(uint8_t id) | 获取MIPI_CSI控制器操作句柄 | +| void MipiCsiClose(DevHandle handle) | 释放MIPI_CSI控制器操作句柄 | +| int32_t MipiCsiSetComboDevAttr(DevHandle handle, ComboDevAttr \*pAttr) | 设置MIPI,CMOS或者LVDS相机的参数给控制器,参数包括工作模式,图像区域,图像深度,数据速率和物理通道等 | +| int32_t MipiCsiSetExtDataType(DevHandle handle, ExtDataType \*dataType) | 设置YUV和RAW数据格式和位深(可选) | +| int32_t MipiCsiSetHsMode(DevHandle handle, LaneDivideMode laneDivideMode) | 设置MIPI RX的Lane分布。根据硬件连接的形式选择具体的mode | +| int32_t MipiCsiSetPhyCmvmode(DevHandle handle, uint8_t devno, PhyCmvMode cmvMode) | 设置共模电压模式 | +| int32_t MipiCsiResetSensor(DevHandle handle, uint8_t snsResetSource) | 复位Sensor | +| int32_t MipiCsiUnresetSensor(DevHandle handle, uint8_t snsResetSource) | 撤销复位Sensor | +| int32_t MipiCsiResetRx(DevHandle handle, uint8_t comboDev) | 复位MIPI RX。不同的s32WorkingViNum有不同的enSnsType | +| int32_t MipiCsiUnresetRx(DevHandle handle, uint8_t comboDev) | 撤销复位MIPI RX | +| int32_t MipiCsiEnableClock(DevHandle handle, uint8_t comboDev) | 使能MIPI的时钟。根据上层函数电泳传递的enSnsType参数决定是用MIPI还是LVDS | +| int32_t MipiCsiDisableClock(DevHandle handle, uint8_t comboDev) | 关闭MIPI设备的时钟 | +| int32_t MipiCsiEnableSensorClock(DevHandle handle, uint8_t snsClkSource) | 使能MIPI上的Sensor时钟 | +| int32_t MipiCsiDisableSensorClock(DevHandle handle, uint8_t snsClkSource) | 关闭Sensor的时钟 | -## 使用指导 +## 开发步骤 -### 使用流程 +#### 使用流程 -使用MIPI CSI的一般流程如图2所示。 +使用MIPI CSI的一般流程如图3所示。 -**图 2** MIPI CSI使用流程图 +**图3** MIPI CSI使用流程图 ![](figures/MIPI-CSI使用流程图.png) -### 获取MIPI CSI控制器操作句柄 +#### 获取MIPI CSI控制器操作句柄 在进行MIPI CSI进行通信前,首先要调用MipiCsiOpen获取控制器操作句柄,该函数会返回指定通道ID的控制器操作句柄。 @@ -75,9 +130,7 @@ CSI(Camera Serial Interface)是由MIPI联盟下Camera工作组指定的接 DevHandle MipiCsiOpen(uint8_t id); ``` -**表 4** MipiCsiOpen的参数和返回值描述 - - +**表4** MipiCsiOpen的参数和返回值描述 | 参数 | 参数描述 | | ---------- | ----------------------------------------------- | @@ -100,7 +153,7 @@ if (MipiCsiHandle == NULL) { } ``` -### MIPI CSI相应配置 +#### 进行MIPI CSI相应配置 - 写入MIPI CSI配置 @@ -108,7 +161,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiSetComboDevAttr(DevHandle handle, ComboDevAttr *pAttr); ``` - **表 5** MipiCsiSetComboDevAttr的参数和返回值描述 + **表5** MipiCsiSetComboDevAttr的参数和返回值描述 @@ -147,7 +200,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiSetExtDataType(DevHandle handle, ExtDataType* dataType); ``` - **表 6** MipiCsiSetExtDataType的参数和返回值描述 + **表6** MipiCsiSetExtDataType的参数和返回值描述 @@ -165,7 +218,7 @@ if (MipiCsiHandle == NULL) { /* 配置YUV和RAW数据格式和位深参数 */ dataType.devno = 0; /* 设备0 */ - dataType.num = 0; /* sensor 0 */ + dataType.num = 0; /* Sensor 0 */ dataType.extDataBitWidth[0] = 12; /* 位深数组元素0 */ dataType.extDataBitWidth[1] = 12; /* 位深数组元素1 */ dataType.extDataBitWidth[2] = 12; /* 位深数组元素2 */ @@ -187,23 +240,21 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiSetHsMode(DevHandle handle, LaneDivideMode laneDivideMode); ``` - **表 7** MipiCsiSetHsMode的参数和返回值描述 - - + **表7** MipiCsiSetHsMode的参数和返回值描述 | 参数 | 参数描述 | | -------------- | -------------- | | handle | 控制器操作句柄 | - | laneDivideMode | lane模式参数 | + | laneDivideMode | Lane模式参数 | | **返回值** | **返回值描述** | | 0 | 设置成功 | | 负数 | 设置失败 | - + ```c int32_t ret; enum LaneDivideMode mode; - - /* lane模式参数为0 */ + + /* Lane模式参数为0 */ mode = LANE_DIVIDE_MODE_0; /* 设置MIPI RX的 Lane分布 */ ret = MipiCsiSetHsMode(MipiCsiHandle, mode); @@ -212,16 +263,14 @@ if (MipiCsiHandle == NULL) { return -1; } ``` - + - 设置共模电压模式 ```c int32_t MipiCsiSetPhyCmvmode(DevHandle handle, uint8_t devno, PhyCmvMode cmvMode); ``` - **表 8** MipiCsiSetPhyCmvmode的参数和返回值描述 - - + **表8** MipiCsiSetPhyCmvmode的参数和返回值描述 | 参数 | 参数描述 | | ---------- | ---------------- | @@ -231,7 +280,7 @@ if (MipiCsiHandle == NULL) { | **返回值** | **返回值描述** | | 0 | 设置成功 | | 负数 | 设置失败 | - + ```c int32_t ret; enum PhyCmvMode mode; @@ -249,7 +298,7 @@ if (MipiCsiHandle == NULL) { } ``` -### 复位/撤销复位Sensor +#### 复位/撤销复位Sensor - 复位Sensor @@ -257,9 +306,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiResetSensor(DevHandle handle, uint8_t snsResetSource); ``` - **表 9** MipiCsiResetSensor的参数和返回值描述 - - + **表9** MipiCsiResetSensor的参数和返回值描述 | 参数 | 参数描述 | | -------------- | ------------------------------------------------ | @@ -268,30 +315,28 @@ if (MipiCsiHandle == NULL) { | **返回值** | **返回值描述** | | 0 | 复位成功 | | 负数 | 复位失败 | - + ```c int32_t ret; uint8_t snsResetSource; - + /* 传感器复位信号线号为0 */ snsResetSource = 0; - /* 复位sensor */ + /* 复位Sensor */ ret = MipiCsiResetSensor(MipiCsiHandle, snsResetSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiResetSensor fail! ret=%d\n", __func__, ret); return -1; } ``` - + - 撤销复位Sensor ```c int32_t MipiCsiUnresetSensor(DevHandle handle, uint8_t snsResetSource); ``` - **表 10** MipiCsiUnresetSensor的参数和返回值描述 - - + **表10** MipiCsiUnresetSensor的参数和返回值描述 | 参数 | 参数描述 | | -------------- | ------------------------------------------------ | @@ -300,14 +345,14 @@ if (MipiCsiHandle == NULL) { | **返回值** | **返回值描述** | | 0 | 撤销复位成功 | | 负数 | 撤销复位失败 | - + ```c int32_t ret; uint8_t snsResetSource; - + /* 传感器撤销复位信号线号为0 */ snsResetSource = 0; - /* 撤销复位sensor */ + /* 撤销复位Sensor */ ret = MipiCsiUnresetSensor(MipiCsiHandle, snsResetSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiUnresetSensor fail! ret=%d\n", __func__, ret); @@ -315,7 +360,7 @@ if (MipiCsiHandle == NULL) { } ``` -### 复位/撤销复位MIPI RX +#### 复位/撤销复位MIPI RX - 复位MIPI RX @@ -323,9 +368,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiResetRx(DevHandle handle, uint8_t comboDev); ``` - **表 11** MipiCsiResetRx的参数和返回值描述 - - + **表11** MipiCsiResetRx的参数和返回值描述 | 参数 | 参数描述 | | ---------- | --------------------- | @@ -334,11 +377,11 @@ if (MipiCsiHandle == NULL) { | **返回值** | **返回值描述** | | 0 | 复位成功 | | 负数 | 复位失败 | - + ```c int32_t ret; uint8_t comboDev; - + /* 通路序号为0 */ comboDev = 0; /* 复位MIPI RX */ @@ -348,16 +391,14 @@ if (MipiCsiHandle == NULL) { return -1; } ``` - + - 撤销复位MIPI RX ```c int32_t MipiCsiUnresetRx(DevHandle handle, uint8_t comboDev); ``` - **表 12** MipiCsiUnresetRx的参数和返回值描述 - - + **表12** MipiCsiUnresetRx的参数和返回值描述 | 参数 | 参数描述 | | ---------- | --------------------- | @@ -366,11 +407,11 @@ if (MipiCsiHandle == NULL) { | **返回值** | **返回值描述** | | 0 | 撤销复位成功 | | 负数 | 撤销复位失败 | - + ```c int32_t ret; uint8_t comboDev; - + /* 通路序号为0 */ comboDev = 0; /* 撤销复位MIPI RX */ @@ -381,7 +422,7 @@ if (MipiCsiHandle == NULL) { } ``` -### 使能/关闭MIPI的时钟 +#### 使能/关闭MIPI的时钟 - 使能MIPI的时钟 @@ -389,7 +430,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiEnableClock(DevHandle handle, uint8_t comboDev); ``` - **表 13** MipiCsiEnableClock的参数和返回值描述 + **表13** MipiCsiEnableClock的参数和返回值描述 @@ -421,7 +462,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiDisableClock(DevHandle handle, uint8_t comboDev); ``` - **表 14** MipiCsiDisableClock的参数和返回值描述 + **表14** MipiCsiDisableClock的参数和返回值描述 @@ -436,7 +477,7 @@ if (MipiCsiHandle == NULL) { ```c int32_t ret; uint8_t comboDev; - + /* 通路序号为0 */ comboDev = 0; /* 关闭MIPI的时钟 */ @@ -447,7 +488,7 @@ if (MipiCsiHandle == NULL) { } ``` -### 使能/关闭MIPI上的Sensor时钟 +#### 使能/关闭MIPI上的Sensor时钟 - 使能MIPI上的Sensor时钟 @@ -455,7 +496,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiEnableSensorClock(DevHandle handle, uint8_t snsClkSource); ``` - **表 15** MipiCsiEnableSensorClock的参数和返回值描述 + **表15** MipiCsiEnableSensorClock的参数和返回值描述 @@ -473,7 +514,7 @@ if (MipiCsiHandle == NULL) { /* 传感器的时钟信号线号为0 */ snsClkSource = 0; - /* 使能MIPI上的sensor时钟 */ + /* 使能MIPI上的Sensor时钟 */ ret = MipiCsiEnableSensorClock(MipiCsiHandle, snsClkSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiEnableSensorClock fail! ret=%d\n", __func__, ret); @@ -487,7 +528,7 @@ if (MipiCsiHandle == NULL) { int32_t MipiCsiDisableSensorClock(DevHandle handle, uint8_t snsClkSource); ``` - **表 16** MipiCsiDisableSensorClock的参数和返回值描述 + **表16** MipiCsiDisableSensorClock的参数和返回值描述 @@ -502,7 +543,7 @@ if (MipiCsiHandle == NULL) { ```c int32_t ret; uint8_t snsClkSource; - + /* 传感器的时钟信号线号为0 */ snsClkSource = 0; /* 关闭MIPI上的Sensor时钟 */ @@ -513,7 +554,7 @@ if (MipiCsiHandle == NULL) { } ``` -### 释放MIPI CSI控制器操作句柄 +#### 释放MIPI CSI控制器操作句柄 MIPI CSI使用完成之后,需要释放控制器操作句柄,释放句柄的函数如下所示: @@ -523,13 +564,13 @@ void MipiCsiClose(DevHandle handle); 该函数会释放掉由MipiCsiOpen申请的资源。 -**表 17** MipiCsiClose的参数和返回值描述 +**表17** MipiCsiClose的参数和返回值描述 - | 参数 | 参数描述 | - | ------------ | ------------------------------------------------ | - | handle | MIPI CSI控制器操作句柄 | +| 参数 | 参数描述 | +| ------------ | ------------------------------------------------ | +| handle | MIPI CSI控制器操作句柄 | ```c MipiCsiClose(MIPIHandle); /* 释放掉MIPI CSI控制器操作句柄 */ @@ -537,6 +578,8 @@ MipiCsiClose(MIPIHandle); /* 释放掉MIPI CSI控制器操作句柄 */ ## 使用实例 +本例拟对Hi3516DV300开发板上MIPI CSI设备进行操作。 + MIPI CSI完整的使用示例如下所示: ```c @@ -565,7 +608,7 @@ void PalMipiCsiTestSample(void) return; } - /* lane模式参数为0 */ + /* Lane模式参数为0 */ mode = LANE_DIVIDE_MODE_0; /* 设置MIPI RX的Lane分布 */ ret = MipiCsiSetHsMode(MipiCsiHandle, mode); @@ -592,14 +635,14 @@ void PalMipiCsiTestSample(void) /* 传感器的时钟信号线号为0 */ snsClkSource = 0; - /* 使能MIPI上的sensor时钟 */ + /* 使能MIPI上的Sensor时钟 */ ret = MipiCsiEnableSensorClock(MipiCsiHandle, snsClkSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiEnableSensorClock fail! ret=%d\n", __func__, ret); return; } - /* 复位sensor */ + /* 复位Sensor */ ret = MipiCsiResetSensor(MipiCsiHandle, snsResetSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiResetSensor fail! ret=%d\n", __func__, ret); @@ -651,14 +694,14 @@ void PalMipiCsiTestSample(void) /* 传感器撤销复位信号线号为0 */ snsResetSource = 0; - /* 撤销复位sensor */ + /* 撤销复位Sensor */ ret = MipiCsiUnresetSensor(MipiCsiHandle, snsResetSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiUnresetSensor fail! ret=%d\n", __func__, ret); return; } - /* 关闭MIPI上的sensor时钟 */ + /* 关闭MIPI上的Sensor时钟 */ ret = MipiCsiDisableSensorClock(MipiCsiHandle, snsClkSource); if (ret != 0) { HDF_LOGE("%s: MipiCsiDisableSensorClock fail! ret=%d\n", __func__, ret); diff --git a/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md b/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md index 0134b7f8096875b6a83cb38d88e5938c13a491b4..fd4c6675b305cb91851a01c5e38fc9618fd9f369 100755 --- a/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md @@ -2,13 +2,66 @@ ## 概述 -CSI(Camera Serial Interface)是由MIPI(Mobile Industry Processor Interface)联盟下Camera工作组指定的接口标准。在HDF框架中,MIPI CSI的接口适配模式采用无服务模式,用于不需要在用户态提供API的设备类型,或者没有用户态和内核区分的OS系统,MIPI CSI的接口关联方式是DevHandle直接指向设备对象内核态地址(DevHandle是一个void类型指针)。 +### 功能简介 -图 1 无服务模式结构图 +CSI(Camera Serial Interface)是由MIPI联盟下Camera工作组指定的接口标准。CSI-2是MIPI CSI第二版,主要由应用层、协议层、物理层组成,最大支持4通道数据传输、单线传输速度高达1Gb/s。 + +物理层支持HS(High Speed)和LP(Low Speed)两种工作模式。HS模式下采用低压差分信号,功耗较大,但数据传输速率可以很高(数据速率为80M~1Gbps);LP模式下采用单端信号,数据速率很低(<10Mbps),但是相应的功耗也很低。两种模式的结合保证了MIPI总线在需要传输大量数据(如图像)时可以高速传输,而在不需要传输大数据量时又能够减少功耗。 + +图1显示了简化的CSI接口。D-PHY采用1对源同步的差分时钟和1~4对差分数据线来进行数据传输。数据传输采用DDR方式,即在时钟的上下边沿都有数据传输。 + + **图 1** CSI发送、接收接口 +![](figures/CSI发送-接收接口.png) + +MIPI CSI标准分为应用层、协议层与物理层,协议层又细分为像素字节转换层、低级协议层、Lane管理层。 + +- 物理层(PHY Layer) + + PHY层指定了传输媒介,在电气层面从串行bit流中捕捉“0”与“1”,同时生成SoT与EoT等信号。 + +- 协议层(Protocol Layer) + + 协议层由三个子层组成,每个子层有不同的职责。CSI-2协议能够在host侧处理器上用一个单独的接口处理多条数据流。协议层规定了多条数据流该如何标记和交织起来,以便每条数据流能够被正确地恢复出来。 + + - 像素字节转换层(Pixel/Byte Packing/Unpacking Layer) + + CSI-2规范支持多种不同像素格式的图像应用。在发送方中,本层在发送数据到Low Level Protocol层之前,将来自应用层的像素封包为字节数据。在接收方中,本层在发送数据到应用层之前,将来自Low Level Protocol层的字节数据解包为像素。8位的像素数据在本层中传输时保持不变。 + + - 低级协议层(Low Level Protocol) + + LLP主要包含了在SoT和EoT事件之间的bit和byte级别的同步方法,以及和下一层传递数据的方法。LLP最小数据粒度是1个字节。LLP也包含了一个字节内的bit值解析,即Endian(大小端里的Endian的意思)的处理。 + + - Lane管理层(Lane Management) + + CSI-2的Lane是可扩展的。具体的数据Lane的数量规范并没有给出限制,具体根据应用的带宽需求而定。发送侧分发(distributor功能)来自出口方向数据流的字节到1条或多条Lane上。接收侧则从一条或多条Lane中收集字节并合并(merge功能)到一个数据流上,复原出原始流的字节顺序。对于C-PHY物理层来说,本层专门分发字节对(16 bits)到数据Lane或从数据Lane中收集字节对。基于每Lane的扰码功能是可选特性。 + + 协议层的数据组织形式是包(packet)。接口的发送侧会增加包头(header)和错误校验(error-checking)信息到即将被LLP发送的数据上。接收侧在LLP将包头剥掉,包头会被接收器中对应的逻辑所解析。错误校验信息可以用来做入口数据的完整性检查。 + +- 应用层(Application Layer) + + 本层描述了更高层级的应用对于数据中的数据的处理,规范并不涵盖应用层。CSI-2规范只给出了像素值和字节的映射关系。 + +### 运作机制 + +MIPI CSI模块各分层的作用为: + +- 接口层提供打开设备、写入数据和关闭设备的接口。 +- 核心层主要提供绑定设备、初始化设备以及释放设备的能力。 +- 适配层实现其它具体的功能。 + +![](../public_sys-resources/icon-note.gif) **说明:**
核心层可以调用接口层的函数,核心层通过钩子函数调用适配层函数,从而适配层可以间接的调用接口层函数,但是不可逆转接口层调用适配层函数。 ![image1](figures/无服务模式结构图.png) -## 接口说明 +## 开发指导 + +### 场景介绍 + +MIPI CSI仅是一个软件层面的概念,主要工作是CSI资源管理。开发者可以通过使用提供的CSI操作接口,实现对CSI资源管理。当驱动开发者需要将MIPI CSI设备适配到OpenHarmony时,需要进行MIPI CSI驱动适配,下文将介绍如何进行MIPI CSI驱动适配。 + +### 接口说明 + +为了保证上层在调用MIPI CSI接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/mipi/mipi_csi_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 MipiCsiCntlrMethod定义: @@ -28,13 +81,13 @@ struct MipiCsiCntlrMethod { int32_t (*unresetSensor)(struct MipiCsiCntlr *cntlr, uint8_t snsResetSource); }; ``` -表1 MipiCsiCntlrMethod成员的回调函数功能说明 +**表1** MipiCsiCntlrMethod成员的钩子函数功能说明 | 成员函数 | 入参 | 出参 | 返回状态 | 功能 | | ------------------ | ------------------------------------------------------------ | ---- | ------------------ | -------------------------- | | setComboDevAttr | **cntlr**:结构体指针,MipiCsi控制器 ;
**pAttr**:结构体指针,MIPI CSI相应配置结构体指针 | 无 | HDF_STATUS相关状态 | 写入MIPI CSI配置 | | setPhyCmvmode | **cntlr**:结构体指针,MipiCsi控制器 ;
**devno**:uint8_t,设备编号;
**cmvMode**:枚举类型,共模电压模式参数 | 无 | HDF_STATUS相关状态 | 设置共模电压模式 | | setExtDataType | **cntlr**:结构体指针,MipiCsi控制器 ;
**dataType**:结构体指针,定义YUV和原始数据格式以及位深度 | 无 | HDF_STATUS相关状态 | 设置YUV和RAW数据格式和位深 | -| setHsMode | **cntlr**:结构体指针,MipiCsi控制器 ;
**laneDivideMode**:枚举类型,lane模式参数 | 无 | HDF_STATUS相关状态 | 设置MIPI RX的Lane分布 | +| setHsMode | **cntlr**:结构体指针,MipiCsi控制器 ;
**laneDivideMode**:枚举类型,Lane模式参数 | 无 | HDF_STATUS相关状态 | 设置MIPI RX的Lane分布 | | enableClock | **cntlr**:结构体指针,MipiCsi控制器 ;
**comboDev**:uint8_t,通路序号 | 无 | HDF_STATUS相关状态 | 使能MIPI的时钟 | | disableClock | **cntlr**:结构体指针,MipiCsi控制器 ;
**comboDev**:uint8_t,通路序号 | 无 | HDF_STATUS相关状态 | 关闭MIPI的时钟 | | resetRx | **cntlr**:结构体指针,MipiCsi控制器 ;
**comboDev**:uint8_t,通路序号 | 无 | HDF_STATUS相关状态 | 复位MIPI RX | @@ -44,7 +97,7 @@ struct MipiCsiCntlrMethod { | resetSensor | **cntlr**:结构体指针,MipiCsi控制器 ;
**snsClkSource**:uint8_t,传感器的时钟信号线号 | 无 | HDF_STATUS相关状态 | 复位Sensor | | unresetSensor | **cntlr**:结构体指针,MipiCsi控制器 ;
**snsClkSource**:uint8_t,传感器的时钟信号线号 | 无 | HDF_STATUS相关状态 | 撤销复位Sensor | -## 开发步骤 +### 开发步骤 MIPI CSI模块适配的三个必选环节是配置属性文件、实例化驱动入口、以及实例化核心层接口函数。 @@ -70,269 +123,264 @@ MIPI CSI模块适配的三个必选环节是配置属性文件、实例化驱动 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 -## 开发实例 +### 开发实例 下方将以mipi_rx_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 一般来说,驱动开发首先需要在busxx_config.hcs中配置器件属性,并在device_info.hcs文件中添加deviceNode描述。 +1. 一般来说,驱动开发首先需要新增mipicsi_config.hcs配置文件,在其中配置器件属性,并在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。deviceNode与配置属性的对应关系是依靠deviceMatchAttr字段来完成的。只有当deviceNode下的deviceMatchAttr字段与配置属性文件中的match_attr字段完全相同时,驱动才能正确读取配置数据。 器件属性值与核心层MipiCsiCntlr 成员的默认值或限制范围有密切关系,deviceNode信息与驱动入口注册相关。 - >![](../public_sys-resources/icon-note.gif) **说明:**
- >本例中MIPI控制器自身属性在源文件文件中,如有厂商需要,则在device_info文件的deviceNode增加deviceMatchAttr信息,相应增加mipicsi_config.hcs文件。 - - -- device_info.hcs 配置参考 - - ```c - root { - device_info { - match_attr = "hdf_manager"; - platform :: host { - hostName = "platform_host"; - priority = 50; - device_mipi_csi:: device { - device0 :: deviceNode { - policy = 0; - priority = 160; - permission = 0644; - moduleName = "HDF_MIPI_RX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 - serviceName = "HDF_MIPI_RX"; // 【必要且唯一】驱动对外发布服务的名称 - } - } - } - } - } - ``` + >![icon-note.gif](../public_sys-resources/icon-note.gif) **说明:**
+ >本例中MIPI控制器配置属性在源文件中,没有新增配置文件,驱动适配者如有需要,可在device_info.hcs文件的deviceNode增加deviceMatchAttr字段,同时新增mipicsi_config.hcs文件,并使其match_attr字段与之相同。 + + device_info.hcs配置参考 + + ```c + root { + device_info { + match_attr = "hdf_manager"; + platform :: host { + hostName = "platform_host"; + priority = 50; + device_mipi_csi:: device { + device0 :: deviceNode { + policy = 0; + priority = 160; + permission = 0644; + moduleName = "HDF_MIPI_RX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HDF_MIPI_RX"; // 【必要且唯一】驱动对外发布服务的名称 + } + } + } + } + } + ``` 2. 完成器件属性文件的配置之后,下一步请实例化驱动入口。 - 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员会被厂商操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员需要被驱动适配者操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 一般在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 -- MIPI CSI驱动入口参考 - - ```c - struct HdfDriverEntry g_mipiCsiDriverEntry = { - .moduleVersion = 1, - .Init = Hi35xxMipiCsiInit, // 见Init参考 - .Release = Hi35xxMipiCsiRelease, // 见Release参考 - .moduleName = "HDF_MIPI_RX", // 【必要】需要与device_info.hcs 中保持一致 - }; - HDF_INIT(g_mipiCsiDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 - ``` - -3. 完成驱动入口注册之后,最后一步就是以核心层MipiCsiCntlr对象的初始化为核心,实现HdfDriverEntry成员函数(Bind,Init,Release)。 - - MipiCsiCntlr对象的初始化包括厂商自定义结构体(用于传递参数和数据)和实例化MipiCsiCntlr成员MipiCsiCntlrMethod(让用户可以通过接口来调用驱动底层函数)。 - -- 自定义结构体参考 - - 从驱动的角度看,自定义结构体是参数和数据的载体,一般来说,config文件中的数值也会用来初始化结构体成员,本例的mipicsi器件属性在源文件中,故基本成员结构与MipiCsiCntlr无太大差异。 - - ```c - typedef struct { - /** 数据类型:8/10/12/14/16位 */ - DataType inputDataType; - /** MIPI波分复用模式 */ - MipiWdrMode wdrMode; - /** laneId: -1 - 禁用 */ - short laneId[MIPI_LANE_NUM]; - - union { - /** 用于 HI_MIPI_WDR_MODE_DT */ - short dataType[WDR_VC_NUM]; + MIPI CSI驱动入口参考 + + ```c + struct HdfDriverEntry g_mipiCsiDriverEntry = { + .moduleVersion = 1, + .Init = Hi35xxMipiCsiInit, // 见Init开发参考 + .Release = Hi35xxMipiCsiRelease, // 见Release开发参考 + .moduleName = "HDF_MIPI_RX", // 【必要】需要与device_info.hcs 中保持一致 + }; + HDF_INIT(g_mipiCsiDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + ``` + +3. 完成驱动入口注册之后,最后一步就是以核心层MipiCsiCntlr对象的初始化为核心,实现HdfDriverEntry成员函数(Bind,Init,Release)。 + + MipiCsiCntlr对象的初始化包括驱动适配者自定义结构体(用于传递参数和数据)和实例化MipiCsiCntlr成员MipiCsiCntlrMethod(让用户可以通过接口来调用驱动底层函数)。 + + - 自定义结构体参考 + + 从驱动的角度看,自定义结构体是参数和数据的载体,一般来说,config文件中的数值也会用来初始化结构体成员,本例的mipicsi器件属性在源文件中,故基本成员结构与MipiCsiCntlr无太大差异。 + + ```c + typedef struct { + /** 数据类型:8/10/12/14/16位 */ + DataType inputDataType; + /** MIPI波分复用模式 */ + MipiWdrMode wdrMode; + /** laneId: -1 - 禁用 */ + short laneId[MIPI_LANE_NUM]; + + union { + /** 用于 HI_MIPI_WDR_MODE_DT */ + short dataType[WDR_VC_NUM]; + }; + } MipiDevAttr; + + typedef struct { + /** 设备号 */ + uint8_t devno; + /** 输入模式: MIPI/LVDS/SUBLVDS/HISPI/DC */ + InputMode inputMode; + MipiDataRate dataRate; + /** MIPI Rx设备裁剪区域(与原始传感器输入图像大小相对应) */ + ImgRect imgRect; + + union { + MipiDevAttr mipiAttr; + LvdsDevAttr lvdsAttr; + }; + } ComboDevAttr; + + /* MipiCsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 */ + struct MipiCsiCntlr { + /** 当驱动程序绑定到HDF框架时,将发送此控制器提供的服务。 */ + struct IDeviceIoService service; + /** 当驱动程序绑定到HDF框架时,将传入设备端指针。 */ + struct HdfDeviceObject *device; + /** 设备号 */ + unsigned int devNo; + /** 控制器提供的所有接口 */ + struct MipiCsiCntlrMethod *ops; + /** 对于控制器调试的所有接口,如果未实现驱动程序,则需要null。 */ + struct MipiCsiCntlrDebugMethod *debugs; + /** 控制器上下文参数变量 */ + MipiDevCtx ctx; + /** 访问控制器上下文参数变量时锁定 */ + OsalSpinlock ctxLock; + /** 操作控制器时锁定方法 */ + struct OsalMutex lock; + /** 匿名数据指针,用于存储csi设备结构。 */ + void *priv; }; - } MipiDevAttr; - - typedef struct { - /** 设备号 */ - uint8_t devno; - /** 输入模式: MIPI/LVDS/SUBLVDS/HISPI/DC */ - InputMode inputMode; - MipiDataRate dataRate; - /** MIPI Rx设备裁剪区域(与原始传感器输入图像大小相对应) */ - ImgRect imgRect; - - union { - MipiDevAttr mipiAttr; - LvdsDevAttr lvdsAttr; + ``` + + - MipiCsiCntlr成员钩子函数结构体MipiCsiCntlrMethod的实例化 + + >![](../public_sys-resources/icon-note.gif) **说明:**
+ >其他成员在Init函数中初始化。 + + ```c + static struct MipiCsiCntlrMethod g_method = { + .setComboDevAttr = Hi35xxSetComboDevAttr, + .setPhyCmvmode = Hi35xxSetPhyCmvmode, + .setExtDataType = Hi35xxSetExtDataType, + .setHsMode = Hi35xxSetHsMode, + .enableClock = Hi35xxEnableClock, + .disableClock = Hi35xxDisableClock, + .resetRx = Hi35xxResetRx, + .unresetRx = Hi35xxUnresetRx, + .enableSensorClock = Hi35xxEnableSensorClock, + .disableSensorClock = Hi35xxDisableSensorClock, + .resetSensor = Hi35xxResetSensor, + .unresetSensor = Hi35xxUnresetSensor }; - } ComboDevAttr; - - // MipiCsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 - struct MipiCsiCntlr { - /** 当驱动程序绑定到HDF框架时,将发送此控制器提供的服务。 */ - struct IDeviceIoService service; - /** 当驱动程序绑定到HDF框架时,将传入设备端指针。 */ - struct HdfDeviceObject *device; - /** 设备号 */ - unsigned int devNo; - /** 控制器提供的所有接口 */ - struct MipiCsiCntlrMethod *ops; - /** 对于控制器调试的所有接口,如果未实现驱动程序,则需要null。 */ - struct MipiCsiCntlrDebugMethod *debugs; - /** 控制器上下文参数变量 */ - MipiDevCtx ctx; - /** 访问控制器上下文参数变量时锁定 */ - OsalSpinlock ctxLock; - /** 操作控制器时锁定方法 */ - struct OsalMutex lock; - /** 匿名数据指针,用于存储csi设备结构。 */ - void *priv; - }; - ``` - - -- MipiCsiCntlr成员回调函数结构体MipiCsiCntlrMethod的实例化 - - >![](../public_sys-resources/icon-note.gif) **说明:**
- >其他成员在Init函数中初始化。 - - - ```c - static struct MipiCsiCntlrMethod g_method = { - .setComboDevAttr = Hi35xxSetComboDevAttr, - .setPhyCmvmode = Hi35xxSetPhyCmvmode, - .setExtDataType = Hi35xxSetExtDataType, - .setHsMode = Hi35xxSetHsMode, - .enableClock = Hi35xxEnableClock, - .disableClock = Hi35xxDisableClock, - .resetRx = Hi35xxResetRx, - .unresetRx = Hi35xxUnresetRx, - .enableSensorClock = Hi35xxEnableSensorClock, - .disableSensorClock = Hi35xxDisableSensorClock, - .resetSensor = Hi35xxResetSensor, - .unresetSensor = Hi35xxUnresetSensor - }; - ``` - -- **Init函数参考** - - **入参:** - - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 - - **返回值:** - - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 - - - | 状态(值) | 问题描述 | - | :--------------------- | :----------: | - | HDF_ERR_INVALID_OBJECT | 无效对象 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_INVALID_PARAM | 无效参数 | - | HDF_ERR_IO | I/O 错误 | - | HDF_SUCCESS | 执行成功 | - | HDF_FAILURE | 执行失败 | - - **函数说明:** - - MipiCsiCntlrMethod的实例化对象的挂载,调用MipiCsiRegisterCntlr,以及其他厂商自定义初始化操作。 - - - ```c - static int32_t Hi35xxMipiCsiInit(struct HdfDeviceObject *device) - { - int32_t ret; - - HDF_LOGI("%s: enter!", __func__); - g_mipiCsi.priv = NULL; // g_mipiTx是定义的全局变量 - // static struct MipiCsiCntlr g_mipiCsi = { - // .devNo = 0 - //}; - g_mipiCsi.ops = &g_method; //MipiCsiCntlrMethod的实例化对象的挂载 - #ifdef CONFIG_HI_PROC_SHOW_SUPPORT - g_mipiCsi.debugs = &g_debugMethod; - #endif - ret = MipiCsiRegisterCntlr(&g_mipiCsi, device); // 【必要】调用核心层函数和g_mipiTx初始化核心层全局变量 - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: [MipiCsiRegisterCntlr] failed!", __func__); - return ret; - } - - ret = MipiRxDrvInit(); // 【必要】厂商对设备的初始化,形式不限。 - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: [MipiRxDrvInit] failed.", __func__); - return ret; - } - #ifdef MIPICSI_VFS_SUPPORT - ret = MipiCsiDevModuleInit(g_mipiCsi.devNo); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: [MipiCsiDevModuleInit] failed!", __func__); + ``` + + - Init函数开发参考 + + 入参: + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + + 返回值: + + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + + **表2** HDF_STATUS返回值描述 + + | 状态(值) | 问题描述 | + | :--------------------- | :----------: | + | HDF_ERR_INVALID_OBJECT | 无效对象 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_INVALID_PARAM | 无效参数 | + | HDF_ERR_IO | I/O 错误 | + | HDF_SUCCESS | 执行成功 | + | HDF_FAILURE | 执行失败 | + + 函数说明: + + MipiCsiCntlrMethod的实例化对象的挂载,调用MipiCsiRegisterCntlr,以及其他驱动适配者自定义初始化操作。 + + ```c + static int32_t Hi35xxMipiCsiInit(struct HdfDeviceObject *device) + { + int32_t ret; + + HDF_LOGI("%s: enter!", __func__); + g_mipiCsi.priv = NULL; // g_mipiTx是定义的全局变量 + // static struct MipiCsiCntlr g_mipiCsi = { + // .devNo = 0 + // }; + g_mipiCsi.ops = &g_method; // MipiCsiCntlrMethod的实例化对象的挂载 + #ifdef CONFIG_HI_PROC_SHOW_SUPPORT + g_mipiCsi.debugs = &g_debugMethod; + #endif + ret = MipiCsiRegisterCntlr(&g_mipiCsi, device); // 【必要】调用核心层函数和g_mipiTx初始化核心层全局变量 + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: [MipiCsiRegisterCntlr] failed!", __func__); + return ret; + } + + ret = MipiRxDrvInit(); // 【必要】驱动适配者对设备的初始化,形式不限。 + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: [MipiRxDrvInit] failed.", __func__); + return ret; + } + #ifdef MIPICSI_VFS_SUPPORT + ret = MipiCsiDevModuleInit(g_mipiCsi.devNo); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: [MipiCsiDevModuleInit] failed!", __func__); + return ret; + } + #endif + + OsalSpinInit(&g_mipiCsi.ctxLock); + HDF_LOGI("%s: load mipi csi driver success!", __func__); + return ret; } - #endif - - OsalSpinInit(&g_mipiCsi.ctxLock); - HDF_LOGI("%s: load mipi csi driver success!", __func__); - - return ret; - } - - // mipi_csi_core.c核心层 - int32_t MipiCsiRegisterCntlr(struct MipiCsiCntlr *cntlr, struct HdfDeviceObject *device) - { - ... - // 定义的全局变量:static struct MipiCsiHandle g_mipiCsihandle[MAX_CNTLR_CNT]; - if (g_mipiCsihandle[cntlr->devNo].cntlr == NULL) { - (void)OsalMutexInit(&g_mipiCsihandle[cntlr->devNo].lock); - (void)OsalMutexInit(&(cntlr->lock)); - - g_mipiCsihandle[cntlr->devNo].cntlr = cntlr; // 初始化MipiCsiHandle成员 - g_mipiCsihandle[cntlr->devNo].priv = NULL; - cntlr->device = device; // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 - device->service = &(cntlr->service); // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 - cntlr->priv = NULL; - HDF_LOGI("%s: success.", __func__); - - return HDF_SUCCESS; + + /* mipi_csi_core.c核心层 */ + int32_t MipiCsiRegisterCntlr(struct MipiCsiCntlr *cntlr, struct HdfDeviceObject *device) + { + ... + /* 定义的全局变量:static struct MipiCsiHandle g_mipiCsihandle[MAX_CNTLR_CNT]; */ + if (g_mipiCsihandle[cntlr->devNo].cntlr == NULL) { + (void)OsalMutexInit(&g_mipiCsihandle[cntlr->devNo].lock); + (void)OsalMutexInit(&(cntlr->lock)); + + g_mipiCsihandle[cntlr->devNo].cntlr = cntlr; // 初始化MipiCsiHandle成员 + g_mipiCsihandle[cntlr->devNo].priv = NULL; + cntlr->device = device; // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 + device->service = &(cntlr->service); // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 + cntlr->priv = NULL; + HDF_LOGI("%s: success.", __func__); + + return HDF_SUCCESS; + } + + HDF_LOGE("%s: cntlr already exists.", __func__); + return HDF_FAILURE; } - - HDF_LOGE("%s: cntlr already exists.", __func__); - return HDF_FAILURE; - } - ``` - -- **Release函数参考** - - **入参:** - - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 - - **返回值:** - - 无 - - **函数说明:** - - 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。 - - >![](../public_sys-resources/icon-note.gif) **说明:**
- >所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 - - - ```c - static void Hi35xxMipiCsiRelease(struct HdfDeviceObject *device) - { - struct MipiCsiCntlr *cntlr = NULL; - ... - cntlr = MipiCsiCntlrFromDevice(device); // 这里有HdfDeviceObject到MipiCsiCntlr的强制转化 - // return (device == NULL) ? NULL : (struct MipiCsiCntlr *)device->service; - ... - - OsalSpinDestroy(&cntlr->ctxLock); - #ifdef MIPICSI_VFS_SUPPORT - MipiCsiDevModuleExit(cntlr->devNo); - #endif - MipiRxDrvExit(); // 【必要】对厂商设备所占资源的释放 - MipiCsiUnregisterCntlr(&g_mipiCsi); // 空函数 - g_mipiCsi.priv = NULL; - - HDF_LOGI("%s: unload mipi csi driver success!", __func__); - } - ``` + ``` + + - Release函数开发参考 + + 入参: + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + + 返回值: + 无 + + 函数说明: + + 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。 + + >![icon-note.gif](../public_sys-resources/icon-note.gif) **说明:**
+ >所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + + ```c + static void Hi35xxMipiCsiRelease(struct HdfDeviceObject *device) + { + struct MipiCsiCntlr *cntlr = NULL; + ... + cntlr = MipiCsiCntlrFromDevice(device); // 这里有HdfDeviceObject到MipiCsiCntlr的强制转化 + // return (device == NULL) ? NULL : (struct MipiCsiCntlr *)device->service; + ... + + OsalSpinDestroy(&cntlr->ctxLock); + #ifdef MIPICSI_VFS_SUPPORT + MipiCsiDevModuleExit(cntlr->devNo); + #endif + MipiRxDrvExit(); // 【必要】对设备所占资源的释放 + MipiCsiUnregisterCntlr(&g_mipiCsi); // 空函数 + g_mipiCsi.priv = NULL; + + HDF_LOGI("%s: unload mipi csi driver success!", __func__); + } + ``` diff --git a/zh-cn/device-dev/driver/driver-platform-mipidsi-des.md b/zh-cn/device-dev/driver/driver-platform-mipidsi-des.md index 5d3b48a232838a6aad9c30379454759d86153f5c..73b158b58f3380dc511e95cff958e58959b3af01 100644 --- a/zh-cn/device-dev/driver/driver-platform-mipidsi-des.md +++ b/zh-cn/device-dev/driver/driver-platform-mipidsi-des.md @@ -1,52 +1,93 @@ # MIPI DSI - ## 概述 +### 功能简介 + DSI(Display Serial Interface)是由移动行业处理器接口联盟(Mobile Industry Processor Interface (MIPI) Alliance)制定的规范,旨在降低移动设备中显示控制器的成本。它以串行的方式发送像素数据或指令给外设(通常是LCD或者类似的显示设备),或从外设中读取状态信息或像素信息;它定义了主机、图像数据源和目标设备之间的串行总线和通信协议。 MIPI DSI具备高速模式和低速模式两种工作模式,全部数据通道都可以用于单向的高速传输,但只有第一个数据通道才可用于低速双向传输,从属端的状态信息、像素等是通过该数据通道返回。时钟通道专用于在高速传输数据的过程中传输同步时钟信号。 图1显示了简化的DSI接口。从概念上看,符合DSI的接口与基于DBI-2和DPI-2标准的接口具有相同的功能。它向外围设备传输像素或命令数据,并且可以从外围设备读取状态或像素信息。主要区别在于,DSI对所有像素数据、命令和事件进行序列化,而在传统接口中,这些像素数据、命令和事件通常需要附加控制信号才能在并行数据总线上传输。 - **图1** DSI发送、接收接口 +**图1** DSI发送、接收接口 - ![image](figures/DSI发送-接收接口.png "DSI发送-接收接口") +![image](figures/DSI发送-接收接口.png "DSI发送-接收接口") +DSI标准对应D-PHY、DSI、DCS规范,可分为四层: -## 接口说明 +- PHY Layer - **表1** MIPI DSI API接口功能介绍 + 定义了传输媒介,输入/输出电路和和时钟和信号机制。PHY层指定传输介质(电导体)、输入/输出电路和从串行比特流中捕获“1”和“0”的时钟机制。这一部分的规范记录了传输介质的特性、信号的电气参数以及时钟与数据通道之间的时序关系。在DSI链路的发送端,并行数据、信号事件和命令按照包组织在协议层转换为包。协议层附加包协议信息和报头,然后通过Lane Management层向PHY发送完整的字节。数据由PHY进行序列化,并通过串行链路发送。DSI链路的接收端执行与发送端相反的操作,将数据包分解为并行的数据、信号事件和命令。如果有多个Lane, Lane管理层将字节分配给单独的物理层,每个Lane一个PHY。 -| 功能分类 | 接口名 | -| -------- | -------- | -| 设置/获取当前MIPI DSI相关配置 | - MipiDsiSetCfg:设置MIPI DSI相关配置
- MipiDsiGetCfg:获取当前MIPI DSI相关配置 | -| 获取/释放MIPI DSI操作句柄 | - MipiDsiOpen:获取MIPI DSI操作句柄
- MipiDsiClose:释放MIPI DSI操作句柄 | -| 设置MIPI DSI进入Low power模式/High speed模式 | - MipiDsiSetLpMode:设置MIPI DSI进入Low power模式
- MipiDsiSetHsMode:设置MIPI DSI进入High speed模式 | -| MIPI DSI发送/回读指令 | - MipiDsiTx:MIPI DSI发送相应指令的接口
- MipiDsiRx:MIPI DSI按期望长度回读的接口 | +- Lane Management层 + + 负责发送和收集数据流到每条Lane。数据Lane的三种操作模式 :espace mode,High-Speed(Burst) mode,Control mode。 + +- Low Level Protocol层 + + 定义了如何组帧和解析以及错误检测等。 + +- Application层 + + 描述高层编码和解析数据流。这一层描述了数据流中包含的数据的更高级的编码和解释。根据显示子系统架构的不同,它可能由具有指定格式的像素或编码的位流组成,或者由显示模块内的显示控制器解释的命令组成。DSI规范描述了像素值、位流、命令和命令参数到包集合中的字节的映射。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +### 运作机制 +MIPI DSI软件模块各分层的作用为: + +- 接口层:提供打开设备、写入数据和关闭设备的接口。 +- 核心层:主要提供绑定设备、初始化设备以及释放设备的能力。 +- 适配层:实现其它具体的功能。 + +![](../public_sys-resources/icon-note.gif) **说明:**
核心层可以调用接口层的函数,核心层通过钩子函数调用适配层函数,从而适配层可以间接的调用接口层函数,但是不可逆转接口层调用适配层函数。 + +**图2** DSI无服务模式结构图 + +![image](figures/无服务模式结构图.png "DSI无服务模式结构图") + +### 约束与限制 + +由于使用无服务模式,MIPI_DSI接口暂不支持用户态使用。 ## 使用指导 +### 场景介绍 + +MIPI DSI主要用于连接显示屏。 -### 使用流程 +### 接口说明 + +MIPI DSI模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/mipi_dsi_if.h。 + +**表1** MIPI DSI API接口功能介绍 + +| 功能分类 | 接口名 | +| -------- | -------- | +| DevHandle MipiDsiOpen(uint8_t id) | 获取MIPI DSI操作句柄 | +| void MipiDsiClose(DevHandle handle) | 释放MIPI DSI操作句柄 | +| int32_t MipiDsiSetCfg(DevHandle handle, struct MipiCfg \*cfg) | 设置MIPI DSI相关配置 | +| int32_t MipiDsiGetCfg(DevHandle handle, struct MipiCfg \*cfg) | 获取当前MIPI DSI相关配置 | +| void MipiDsiSetLpMode(DevHandle handle) | 设置MIPI DSI进入Low power模式 | +| void MipiDsiSetHsMode(DevHandle handle) | 设置MIPI DSI进入High speed模式 | +| int32_t MipiDsiTx(DevHandle handle, struct DsiCmdDesc \*cmd) | DSI发送指令 | +| int32_t MipiDsiRx(DevHandle handle, struct DsiCmdDesc \*cmd, int32_t readLen, uint8_t \*out) | MIPI DSI按期望长度回读数据 | + +### 开发步骤 使用MIPI DSI的一般流程如下图所示。 - **图2** MIPI DSI使用流程图 +**图3** MIPI DSI使用流程图 - ![image](figures/MIPI-DSI使用流程图.png "MIPI-DSI使用流程图") +![image](figures/MIPI-DSI使用流程图.png "MIPI-DSI使用流程图") -### 获取MIPI DSI操作句柄 +#### 获取MIPI DSI操作句柄 在进行MIPI DSI进行通信前,首先要调用MipiDsiOpen获取操作句柄,该函数会返回指定通道ID的操作句柄。 - -``` + +```c DevHandle MipiDsiOpen(uint8_t id); ``` @@ -61,8 +102,8 @@ DevHandle MipiDsiOpen(uint8_t id); 假设系统中的MIPI DSI通道为0,获取该通道操作句柄的示例如下: - -``` + +```c DevHandle mipiDsiHandle = NULL; /* 设备句柄 */ chnId = 0; /* MIPI DSI通道ID */ @@ -75,11 +116,11 @@ if (mipiDsiHandle == NULL) { ``` -### MIPI DSI相应配置 +#### MIPI DSI相应配置 - 写入MIPI DSI配置 - - ``` + + ```c int32_t MipiDsiSetCfg(DevHandle handle, struct MipiCfg *cfg); ``` @@ -93,8 +134,8 @@ if (mipiDsiHandle == NULL) { | 0 | 设置成功 | | 负数 | 设置失败 | - - ``` + + ```c int32_t ret; struct MipiCfg cfg = {0}; @@ -122,8 +163,8 @@ if (mipiDsiHandle == NULL) { ``` - 获取当前MIPI DSI的配置 - - ``` + + ```c int32_t MipiDsiGetCfg(DevHandle handle, struct MipiCfg *cfg); ``` @@ -137,8 +178,8 @@ if (mipiDsiHandle == NULL) { | 0 | 获取成功 | | 负数 | 获取失败 | - - ``` + + ```c int32_t ret; struct MipiCfg cfg; memset(&cfg, 0, sizeof(struct MipiCfg)); @@ -150,11 +191,11 @@ if (mipiDsiHandle == NULL) { ``` -### 发送/回读控制指令 +#### 发送/回读控制指令 - 发送指令 - - ``` + + ```c int32_t MipiDsiTx(PalHandle handle, struct DsiCmdDesc *cmd); ``` @@ -168,8 +209,8 @@ if (mipiDsiHandle == NULL) { | 0 | 发送成功 | | 负数 | 发送失败 | - - ``` + + ```c int32_t ret; struct DsiCmdDesc *cmd = OsalMemCalloc(sizeof(struct DsiCmdDesc)); if (cmd == NULL) { @@ -197,8 +238,8 @@ if (mipiDsiHandle == NULL) { ``` - 回读指令 - - ``` + + ```c int32_t MipiDsiRx(DevHandle handle, struct DsiCmdDesc *cmd, uint32_t readLen, uint8_t *out); ``` @@ -214,8 +255,8 @@ if (mipiDsiHandle == NULL) { | 0 | 获取成功 | | 负数 | 获取失败 | - - ``` + + ```c int32_t ret; uint8_t readVal = 0; @@ -245,12 +286,11 @@ if (mipiDsiHandle == NULL) { ``` -### 释放MIPI DSI操作句柄 +#### 释放MIPI DSI操作句柄 MIPI DSI使用完成之后,需要释放操作句柄,释放句柄的函数如下所示: - -``` +```c void MipiDsiClose(DevHandle handle); ``` @@ -262,18 +302,18 @@ void MipiDsiClose(DevHandle handle); | -------- | -------- | | handle | MIPI DSI操作句柄 | - -``` +```c MipiDsiClose(mipiHandle); /* 释放掉MIPI DSI操作句柄 */ ``` ## 使用实例 +本例拟对Hi3516DV300开发板上MIPI DSI设备进行操作。 + MIPI DSI完整的使用示例如下所示: - -``` +```c #include "hdf.h" #include "mipi_dsi_if.h" diff --git a/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md b/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md index dd819669cac4eb97072375ed70622840d4c2e44e..a83b5de1313a6454aafbd089ee54b4fc80086d57 100755 --- a/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md @@ -1,35 +1,79 @@ # MIPI DSI - ## 概述 -DSI(Display Serial Interface)是由移动行业处理器接口联盟(Mobile Industry Processor Interface (MIPI) Alliance)制定的规范。在HDF框架中,MIPI DSI的接口适配模式采用无服务模式,用于不需要在用户态提供API的设备类型,或者没有用户态和内核区分的OS系统,其关联方式是DevHandle直接指向设备对象内核态地址(DevHandle是一个void类型指针)。 +### 功能简介 + +DSI(Display Serial Interface)是由移动行业处理器接口联盟(Mobile Industry Processor Interface (MIPI) Alliance)制定的规范,旨在降低移动设备中显示控制器的成本。它以串行的方式发送像素数据或指令给外设(通常是LCD或者类似的显示设备),或从外设中读取状态信息或像素信息;它定义了主机、图像数据源和目标设备之间的串行总线和通信协议。 + +MIPI DSI具备高速模式和低速模式两种工作模式,全部数据通道都可以用于单向的高速传输,但只有第一个数据通道才可用于低速双向传输,从属端的状态信息、像素等是通过该数据通道返回。时钟通道专用于在高速传输数据的过程中传输同步时钟信号。 + +图1显示了简化的DSI接口。从概念上看,符合DSI的接口与基于DBI-2和DPI-2标准的接口具有相同的功能。它向外围设备传输像素或命令数据,并且可以从外围设备读取状态或像素信息。主要区别在于,DSI对所有像素数据、命令和事件进行序列化,而在传统接口中,这些像素数据、命令和事件通常需要附加控制信号才能在并行数据总线上传输。 + +**图1** DSI发送、接收接口 + +![image](figures/DSI发送-接收接口.png "DSI发送-接收接口") + +DSI标准对应D-PHY、DSI、DCS规范,可分为四层: + +- PHY Layer + + 定义了传输媒介,输入/输出电路和和时钟和信号机制。PHY层指定传输介质(电导体)、输入/输出电路和从串行比特流中捕获“1”和“0”的时钟机制。这一部分的规范记录了传输介质的特性、信号的电气参数以及时钟与数据通道之间的时序关系。在DSI链路的发送端,并行数据、信号事件和命令按照包组织在协议层转换为包。协议层附加包协议信息和报头,然后通过Lane Management层向PHY发送完整的字节。数据由PHY进行序列化,并通过串行链路发送。DSI链路的接收端执行与发送端相反的操作,将数据包分解为并行的数据、信号事件和命令。如果有多个Lane, Lane管理层将字节分配给单独的物理层,每个Lane一个PHY。 + +- Lane Management层 + + 负责发送和收集数据流到每条Lane。数据Lane的三种操作模式 :espace mode, High-Speed(Burst) mode, Control mode 。 + +- Low Level Protocol层 - **图1** DSI无服务模式结构图 + 定义了如何组帧和解析以及错误检测等。 + +- Application层 + + 描述高层编码和解析数据流。这一层描述了数据流中包含的数据的更高级的编码和解释。根据显示子系统架构的不同,它可能由具有指定格式的像素或编码的位流组成,或者由显示模块内的显示控制器解释的命令组成。DSI规范描述了像素值、位流、命令和命令参数到包集合中的字节的映射。 + +### 运作机制 + +MIPI DSI软件模块各分层的作用为: + +- 接口层:提供打开设备、写入数据和关闭设备的接口。 +- 核心层:主要提供绑定设备、初始化设备以及释放设备的能力。 +- 适配层:实现其它具体的功能。 + +![](../public_sys-resources/icon-note.gif) **说明:**
核心层可以调用接口层的函数,核心层通过钩子函数调用适配层函数,从而适配层可以间接的调用接口层函数,但是不可逆转接口层调用适配层函数。 + + + **图2** DSI无服务模式结构图 ![image](figures/无服务模式结构图.png "DSI无服务模式结构图") +## 开发指导 + + ### 场景介绍 -## 接口说明 +MIPI DSI仅是一个软件层面的概念,主要工作是MIPI DSI资源管理。开发者可以通过使用提供的提供的操作接口,实现DSI资源管理。当驱动开发者需要将MIPI DSI设备适配到OpenHarmony时,需要进行MIPI DSI驱动适配,下文将介绍如何进行MIPI DSI驱动适配。 + +### 接口说明 + +为了保证上层在调用MIPI DSI接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/mipi/mipi_dsi_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 MipiDsiCntlrMethod定义: - -``` +```c struct MipiDsiCntlrMethod { // 核心层结构体的成员函数 int32_t (*setCntlrCfg)(struct MipiDsiCntlr *cntlr); int32_t (*setCmd)(struct MipiDsiCntlr *cntlr, struct DsiCmdDesc *cmd); int32_t (*getCmd)(struct MipiDsiCntlr *cntlr, struct DsiCmdDesc *cmd, uint32_t readLen, uint8_t *out); void (*toHs)(struct MipiDsiCntlr *cntlr); void (*toLp)(struct MipiDsiCntlr *cntlr); - void (*enterUlps)(struct MipiDsiCntlr *cntlr); //【可选】进入超低功耗模式 - void (*exitUlps)(struct MipiDsiCntlr *cntlr); //【可选】退出超低功耗模式 - int32_t (*powerControl)(struct MipiDsiCntlr *cntlr, uint8_t enable);//【可选】使能/去使能功耗控制 - int32_t (*attach)(struct MipiDsiCntlr *cntlr); //【可选】将一个DSI设备连接上host + void (*enterUlps)(struct MipiDsiCntlr *cntlr); //【可选】进入超低功耗模式 + void (*exitUlps)(struct MipiDsiCntlr *cntlr); //【可选】退出超低功耗模式 + int32_t (*powerControl)(struct MipiDsiCntlr *cntlr, uint8_t enable); //【可选】使能/去使能功耗控制 + int32_t (*attach)(struct MipiDsiCntlr *cntlr); //【可选】将一个DSI设备连接上host }; ``` - **表1** MipiDsiCntlrMethod成员的回调函数功能说明 + **表1** MipiDsiCntlrMethod成员的钩子函数功能说明 | 成员函数 | 入参 | 出参 | 返回状态 | 功能 | | -------- | -------- | -------- | -------- | -------- | @@ -40,7 +84,7 @@ struct MipiDsiCntlrMethod { // 核心层结构体的成员函数 | toLp | cntlr:结构体指针,MipiDsi控制器 | 无 | HDF_STATUS相关状态 | 设置为低电模式 | -## 开发步骤 +### 开发步骤 MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 @@ -63,91 +107,91 @@ MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 -## 开发实例 +### 开发实例 -下方将以mipi_tx_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +下方将以mipi_tx_hi35xx.c为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 -1. 一般来说,驱动开发首先需要在xx_config.hcs中配置器件属性,并在device_info.hcs文件中添加deviceNode描述。 +1. 一般来说,驱动开发首先需要mipicsi_config.hcs配置文件,在其中配置器件属性,并在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。deviceNode与配置属性的对应关系是依靠deviceMatchAttr字段来完成的。只有当deviceNode下的deviceMatchAttr字段与配置属性文件中的match_attr字段完全相同时,驱动才能正确读取配置数据。 器件属性值与核心层MipiDsiCntlr成员的默认值或限制范围有密切关系,deviceNode信息与驱动入口注册相关。 - 但本例中MIPI控制器无需配置额外属性,如有厂商需要,则需要在device_info文件的deviceNode增加deviceMatchAttr信息,以及增加mipidsi_config文件。 + 但本例中MIPI控制器无需配置额外属性,驱动适配者如有需要,则需要在device_info.hcs文件的deviceNode增加deviceMatchAttr信息,以及增加mipidsi_config.hcs文件。 - device_info.hcs 配置参考: - - ``` + device_info.hcs 配置参考: + + ```c root { - device_info { - match_attr = "hdf_manager"; - platform :: host { - hostName = "platform_host"; - priority = 50; - device_mipi_dsi:: device { - device0 :: deviceNode { - policy = 0; - priority = 150; - permission = 0644; - moduleName = "HDF_MIPI_TX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 - serviceName = "HDF_MIPI_TX"; // 【必要且唯一】驱动对外发布服务的名称。 + device_info { + match_attr = "hdf_manager"; + platform :: host { + hostName = "platform_host"; + priority = 50; + device_mipi_dsi:: device { + device0 :: deviceNode { + policy = 0; + priority = 150; + permission = 0644; + moduleName = "HDF_MIPI_TX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HDF_MIPI_TX"; // 【必要且唯一】驱动对外发布服务的名称。 + } + } } } - } - } } ``` 2. 完成器件属性文件的配置之后,下一步请实例化驱动入口。 - 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员会被厂商操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员需要被驱动适配者操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 一般在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 MIPI DSI驱动入口参考: - ``` + ```c struct HdfDriverEntry g_mipiTxDriverEntry = { - .moduleVersion = 1, - .Init = Hi35xxMipiTxInit, // 见Init参考 - .Release = Hi35xxMipiTxRelease,// 见Release参考 - .moduleName = "HDF_MIPI_TX", // 【必要】需要与device_info.hcs 中保持一致。 + .moduleVersion = 1, + .Init = Hi35xxMipiTxInit, // 见Init开发参考 + .Release = Hi35xxMipiTxRelease, // 见Release开发参考 + .moduleName = "HDF_MIPI_TX", // 【必要】需要与device_info.hcs 中保持一致。 }; - HDF_INIT(g_mipiTxDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_mipiTxDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -3. 完成驱动入口注册之后,下一步就是以核心层MipiDsiCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化MipiDsiCntlr成员MipiDsiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层MipiDsiCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化MipiDsiCntlr成员MipiDsiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - 自定义结构体参考 从驱动的角度看,自定义结构体是参数和数据的载体,一般来说,config文件中的数值也会用来初始化结构体成员,但本例的mipidsi无器件属性文件,故基本成员结构与MipiDsiCntlr无太大差异。 - - ``` + + ```c typedef struct { - unsigned int devno; // 设备号 - short laneId[LANE_MAX_NUM]; // lane号 - OutPutModeTag outputMode; // 输出模式选择:刷新模式,命令行模式或视频流模式 - VideoModeTag videoMode; // 显示设备的同步模式 - OutputFormatTag outputFormat; // 输出DSI图像数据格式:RGB或YUV - SyncInfoTag syncInfo; // 时序相关的设置 - unsigned int phyDataRate; // 数据速率,单位Mbps - unsigned int pixelClk; // 时钟,单位KHz + unsigned int devno; // 设备号 + short laneId[LANE_MAX_NUM]; // Lane号 + OutPutModeTag outputMode; // 输出模式选择:刷新模式,命令行模式或视频流模式 + VideoModeTag videoMode; // 显示设备的同步模式 + OutputFormatTag outputFormat; // 输出DSI图像数据格式:RGB或YUV + SyncInfoTag syncInfo; // 时序相关的设置 + unsigned int phyDataRate; // 数据速率,单位Mbps + unsigned int pixelClk; // 时钟,单位KHz } ComboDevCfgTag; - // MipiDsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + /* MipiDsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 */ struct MipiDsiCntlr { - struct IDeviceIoService service; - struct HdfDeviceObject *device; - unsigned int devNo; // 设备号 - struct MipiCfg cfg; - struct MipiDsiCntlrMethod *ops; - struct OsalMutex lock; - void *priv; + struct IDeviceIoService service; + struct HdfDeviceObject *device; + unsigned int devNo; // 设备号 + struct MipiCfg cfg; + struct MipiDsiCntlrMethod *ops; + struct OsalMutex lock; + void *priv; }; ``` - - MipiDsiCntlr成员回调函数结构体MipiDsiCntlrMethod的实例化,其他成员在Init函数中初始化。 + - MipiDsiCntlr成员钩子函数结构体MipiDsiCntlrMethod的实例化,其他成员在Init函数中初始化。 - - ``` + + ```c static struct MipiDsiCntlrMethod g_method = { .setCntlrCfg = Hi35xxSetCntlrCfg, .setCmd = Hi35xxSetCmd, @@ -156,7 +200,7 @@ MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动 .toLp = Hi35xxToLp, }; ``` - - Init函数参考 + - Init函数开发参考 入参: @@ -164,8 +208,9 @@ MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + **表2** HDF_STATUS返回值描述 | 状态(值) | 问题描述 | | -------- | -------- | @@ -178,45 +223,45 @@ MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动 函数说明: - MipiDsiCntlrMethod的实例化对象的挂载,调用MipiDsiRegisterCntlr,以及其他厂商自定义初始化操作。 + MipiDsiCntlrMethod的实例化对象的挂载,调用MipiDsiRegisterCntlr,以及其他驱动适配者自定义初始化操作。 - - ``` + + ```c static int32_t Hi35xxMipiTxInit(struct HdfDeviceObject *device) { - int32_t ret; - g_mipiTx.priv = NULL; // g_mipiTx是定义的全局变量 - // static struct MipiDsiCntlr g_mipiTx { - // .devNo=0 - //}; - g_mipiTx.ops = &g_method; // MipiDsiCntlrMethod的实例化对象的挂载 - ret = MipiDsiRegisterCntlr(&g_mipiTx, device);// 【必要】调用核心层函数和g_mipiTx初始化核心层全局变量 - ... - return MipiTxDrvInit(0); // 【必要】厂商对设备的初始化,形式不限 + int32_t ret; + g_mipiTx.priv = NULL; // g_mipiTx是定义的全局变量 + // static struct MipiDsiCntlr g_mipiTx { + // .devNo=0 + //}; + g_mipiTx.ops = &g_method; // MipiDsiCntlrMethod的实例化对象的挂载 + ret = MipiDsiRegisterCntlr(&g_mipiTx, device); // 【必要】调用核心层函数和g_mipiTx初始化核心层全局变量 + ... + return MipiTxDrvInit(0); // 【必要】驱动适配者对设备的初始化,形式不限 } - // mipi_dsi_core.c核心层 + /* mipi_dsi_core.c核心层 */ int32_t MipiDsiRegisterCntlr(struct MipiDsiCntlr *cntlr, struct HdfDeviceObject *device) { - ... - // 定义的全局变量:static struct MipiDsiHandle g_mipiDsihandle[MAX_CNTLR_CNT]; - if (g_mipiDsihandle[cntlr->devNo].cntlr == NULL) { - (void)OsalMutexInit(&g_mipiDsihandle[cntlr->devNo].lock); - (void)OsalMutexInit(&(cntlr->lock)); - - g_mipiDsihandle[cntlr->devNo].cntlr = cntlr;// 初始化MipiDsiHandle成员 - g_mipiDsihandle[cntlr->devNo].priv = NULL; - cntlr->device = device; // 使HdfDeviceObject与MipiDsiHandle可以相互转化的前提 - device->service = &(cntlr->service); // 使HdfDeviceObject与MipiDsiHandle可以相互转化的前提 - cntlr->priv = NULL; ... - return HDF_SUCCESS; - } - ... - return HDF_FAILURE; + /* 定义的全局变量:static struct MipiDsiHandle g_mipiDsihandle[MAX_CNTLR_CNT]; */ + if (g_mipiDsihandle[cntlr->devNo].cntlr == NULL) { + (void)OsalMutexInit(&g_mipiDsihandle[cntlr->devNo].lock); + (void)OsalMutexInit(&(cntlr->lock)); + + g_mipiDsihandle[cntlr->devNo].cntlr = cntlr; // 初始化MipiDsiHandle成员 + g_mipiDsihandle[cntlr->devNo].priv = NULL; + cntlr->device = device; // 使HdfDeviceObject与MipiDsiHandle可以相互转化的前提 + device->service = &(cntlr->service); // 使HdfDeviceObject与MipiDsiHandle可以相互转化的前提 + cntlr->priv = NULL; + ... + return HDF_SUCCESS; + } + ... + return HDF_FAILURE; } ``` - - Release函数参考 + - Release函数开发参考 入参: @@ -232,18 +277,18 @@ MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 - - ``` + + ```c static void Hi35xxMipiTxRelease(struct HdfDeviceObject *device) { - struct MipiDsiCntlr *cntlr = NULL; - ... - cntlr = MipiDsiCntlrFromDevice(device);// 这里有HdfDeviceObject到MipiDsiCntlr的强制转化 - // return (device == NULL) ? NULL : (struct MipiDsiCntlr *)device->service; - ... - MipiTxDrvExit(); // 【必要】对厂商设备所占资源的释放 - MipiDsiUnregisterCntlr(&g_mipiTx); // 空函数 - g_mipiTx.priv = NULL; - HDF_LOGI("%s: unload mipi_tx driver 1212!", __func__); - } + struct MipiDsiCntlr *cntlr = NULL; + ... + cntlr = MipiDsiCntlrFromDevice(device); // 这里有HdfDeviceObject到MipiDsiCntlr的强制转化 + // return (device == NULL) ? NULL : (struct MipiDsiCntlr *)device->service; + ... + MipiTxDrvExit(); // 【必要】对设备所占资源的释放 + MipiDsiUnregisterCntlr(&g_mipiTx); // 空函数 + g_mipiTx.priv = NULL; + HDF_LOGI("%s: unload mipi_tx driver 1212!", __func__); + } ``` diff --git a/zh-cn/device-dev/driver/driver-platform-mmc-develop.md b/zh-cn/device-dev/driver/driver-platform-mmc-develop.md index 73e1f9bba87c5ad88940132eeb284e5c2fc0fe5a..956b94fdedb0126b0d2261a004a714f1d6c0f9aa 100755 --- a/zh-cn/device-dev/driver/driver-platform-mmc-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-mmc-develop.md @@ -1,221 +1,248 @@ # MMC - ## 概述 -MMC(MultiMedia Card)即多媒体卡。在HDF框架中,MMC的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 + +MMC(MultiMedia Card)即多媒体卡,是一种用于固态非易失性存储的小体积大容量的快闪存储卡。 + +MMC后续泛指一个接口协定(一种卡式),能符合这种接口的内存器都可称作MMC储存体。主要包括几个部分:MMC控制器、MMC总线、存储卡(包括MMC卡、SD卡、SDIO卡、TF卡)。 + +MMC、SD、SDIO总线,其总线规范类似,都是从MMC总线规范演化而来的。MMC强调的是多媒体存储;SD强调的是安全和数据保护;SDIO是从SD演化出来的,强调的是接口,不再关注另一端的具体形态(可以是WIFI设备、Bluetooth设备、GPS等等)。 + +### 基本概念 + +- SD卡(Secure Digital Memory Card) + + SD卡即安全数码卡。它是在MMC的基础上发展而来,SD卡强调数据的安全安全,可以设定存储内容的使用权限,防止数据被他人复制。在数据传输和物理规范上,SD卡(24mm\*32mm\*2.1mm,比MMC卡更厚一点),向前兼容了MMC卡。所有支持SD卡的设备也支持MMC卡。 + +- SDIO(Secure Digital Input and Output) + + 即安全数字输入输出接口。SDIO是在SD规范的标准上定义的一种外设接口,它相较于SD规范增加了低速标准,可以用最小的硬件开销支持低速I/O。SDIO接口兼容以前的SD内存卡,也可以连接SDIO接口的设备。 + +### 运作机制 + +在HDF框架中,MMC的接口适配模式采用独立服务模式(如图1所示)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 + +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 - **图1** MMC独立服务模式结构图 +MMC模块各分层作用: - ![zh-cn_image_0000001176603968](figures/独立服务模式结构图.png "MMC独立服务模式结构图") +- 接口层提供打开MMC设备、检查MMC控制器是否存在设备、关闭MMC设备的接口。 +- 核心层主要提供MMC控制器、移除和管理的能力,还有公共控制器业务。通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 +**图1** MMC独立服务模式结构图 -## 接口说明 +![img1](figures/独立服务模式结构图.png "MMC独立服务模式结构图") + +## 开发指导 + +### 场景介绍 + +MMC用于多媒体文件的存储,当驱动开发者需要将MMC设备适配到OpenHarmony时,需要进行MMC驱动适配。下文将介绍如何进行MMC驱动适配。 + +### 接口说明 + +为了保证上层在调用MMC接口时能够正确的操作MMC控制器,核心层在//drivers/hdf_core/framework/model/storage/include/mmc/mmc_corex.h中定义了以下钩子函数,驱动适配者需要在适配层实现这些函数的具体功能,并与钩子函数挂接,从而完成适配层与核心层的交互。 MmcCntlrOps定义: - -``` +```c struct MmcCntlrOps { - int32_t (*request)(struct MmcCntlr *cntlr, struct MmcCmd *cmd); - int32_t (*setClock)(struct MmcCntlr *cntlr, uint32_t clock); - int32_t (*setPowerMode)(struct MmcCntlr *cntlr, enum MmcPowerMode mode); - int32_t (*setBusWidth)(struct MmcCntlr *cntlr, enum MmcBusWidth width); - int32_t (*setBusTiming)(struct MmcCntlr *cntlr, enum MmcBusTiming timing); - int32_t (*setSdioIrq)(struct MmcCntlr *cntlr, bool enable); - int32_t (*hardwareReset)(struct MmcCntlr *cntlr); - int32_t (*systemInit)(struct MmcCntlr *cntlr); - int32_t (*setEnhanceStrobe)(struct MmcCntlr *cntlr, bool enable); - int32_t (*switchVoltage)(struct MmcCntlr *cntlr, enum MmcVolt volt); - bool (*devReadOnly)(struct MmcCntlr *cntlr); - bool (*devPlugged)(struct MmcCntlr *cntlr); - bool (*devBusy)(struct MmcCntlr *cntlr); - int32_t (*tune)(struct MmcCntlr *cntlr, uint32_t cmdCode); - int32_t (*rescanSdioDev)(struct MmcCntlr *cntlr); + int32_t (*request)(struct MmcCntlr *cntlr, struct MmcCmd *cmd); + int32_t (*setClock)(struct MmcCntlr *cntlr, uint32_t clock); + int32_t (*setPowerMode)(struct MmcCntlr *cntlr, enum MmcPowerMode mode); + int32_t (*setBusWidth)(struct MmcCntlr *cntlr, enum MmcBusWidth width); + int32_t (*setBusTiming)(struct MmcCntlr *cntlr, enum MmcBusTiming timing); + int32_t (*setSdioIrq)(struct MmcCntlr *cntlr, bool enable); + int32_t (*hardwareReset)(struct MmcCntlr *cntlr); + int32_t (*systemInit)(struct MmcCntlr *cntlr); + int32_t (*setEnhanceStrobe)(struct MmcCntlr *cntlr, bool enable); + int32_t (*switchVoltage)(struct MmcCntlr *cntlr, enum MmcVolt volt); + bool (*devReadOnly)(struct MmcCntlr *cntlr); + bool (*devPlugged)(struct MmcCntlr *cntlr); + bool (*devBusy)(struct MmcCntlr *cntlr); + int32_t (*tune)(struct MmcCntlr *cntlr, uint32_t cmdCode); + int32_t (*rescanSdioDev)(struct MmcCntlr *cntlr); }; ``` - **表1** MmcCntlrOps结构体成员的回调函数功能说明 +**表1** MmcCntlrOps结构体成员的钩子函数功能说明 -| 成员函数 | 入参 | 返回值 | 功能 | +| 成员函数 | 入参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -| doRequest | cntlr:核心层结构体指针,MMC控制器
cmd:结构体指针,传入命令值 | HDF_STATUS相关状态 | request相应处理 | -| setClock | cntlr:核心层结构体指针,MMC控制器
clock:时钟传入值 | HDF_STATUS相关状态 | 设置时钟频率 | -| setPowerMode | cntlr:核心层结构体指针,MMC控制器
mode:枚举值(见MmcPowerMode定义),功耗模式 | HDF_STATUS相关状态 | 设置功耗模式 | -| setBusWidth | cntlr:核心层结构体指针,MMC控制器
width:枚举值(见MmcBusWidth定义),总线带宽 | HDF_STATUS相关状态 | 设置总线带宽 | -| setBusTiming | cntlr:核心层结构体指针,MMC控制器
timing:枚举值(见MmcBusTiming定义),总线时序 | HDF_STATUS相关状态 | 设置总线时序 | -| setSdioIrq | cntlr:核心层结构体指针,MMC控制器
enable:布尔值,控制中断 | HDF_STATUS相关状态 | 使能/去使能SDIO中断 | -| hardwareReset | cntlr:核心层结构体指针,MMC控制器 | HDF_STATUS相关状态 | 复位硬件 | -| systemInit | cntlr:核心层结构体指针,MMC控制器 | HDF_STATUS相关状态 | 系统初始化 | -| setEnhanceStrobe | cntlr:核心层结构体指针,MMC控制器
enable:布尔值,设置功能 | HDF_STATUS相关状态 | 设置增强选通 | -| switchVoltage | cntlr:核心层结构体指针,MMC控制器
volt:枚举值,电压值(3.3,1.8,1.2V) | HDF_STATUS相关状态 | 设置电压值 | -| devReadOnly | cntlr:核心层结构体指针,MMC控制器 | 布尔值 | 检验设备是否只读 | -| cardPlugged | cntlr:核心层结构体指针,MMC控制器 | 布尔值 | 检验设备是否拔出 | -| devBusy | cntlr:核心层结构体指针,MMC控制器 | 布尔值 | 检验设备是否忙碌 | -| tune | cntlr:核心层结构体指针,MMC控制器
cmdCode:uint32_t,命令代码 | HDF_STATUS相关状态 | 调谐 | -| rescanSdioDev | cntlr:核心层结构体指针,MMC控制器 | HDF_STATUS相关状态 | 扫描并添加SDIO设备 | - - -## 开发步骤 - -MMC模块适配的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 - -1. 实例化驱动入口 - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 - -2. 配置属性文件 - - 在device_info.hcs文件中添加deviceNode描述。 - - 【可选】添加mmc_config.hcs器件属性文件。 - -3. 实例化MMC控制器对象 - - 初始化MmcCntlr成员。 - - 实例化MmcCntlr成员MmcCntlrOps。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
- > 实例化MmcCntlr成员MmcCntlrOps,其定义和成员说明见[接口说明](#接口说明)。 +| doRequest | cntlr:结构体指针,核心层MMC控制器
cmd:结构体指针,传入命令值 | HDF_STATUS相关状态 | request相应处理 | +| setClock | cntlr:结构体指针,核心层MMC控制器
clock:时钟传入值 | HDF_STATUS相关状态 | 设置时钟频率 | +| setPowerMode | cntlr:结构体指针,核心层MMC控制器
mode:枚举值(见MmcPowerMode定义),功耗模式 | HDF_STATUS相关状态 | 设置功耗模式 | +| setBusWidth | cntlr:核心层结构体指针,核心层MMMC控制器
width:枚举值(见MmcBusWidth定义),总线带宽 | HDF_STATUS相关状态 | 设置总线带宽 | +| setBusTiming | cntlr:结构体指针,核心层MMC控制器
timing:枚举值(见MmcBusTiming定义),总线时序 | HDF_STATUS相关状态 | 设置总线时序 | +| setSdioIrq | cntlr:结构体指针,核心层MMC控制器
enable:布尔值,控制中断 | HDF_STATUS相关状态 | 使能/去使能SDIO中断 | +| hardwareReset | cntlr:结构体指针,核心层MMC控制器 | HDF_STATUS相关状态 | 复位硬件 | +| systemInit | cntlr:结构体指针,核心层MMC控制器 | HDF_STATUS相关状态 | 系统初始化 | +| setEnhanceStrobe | cntlr:结构体指针,核心层MMC控制器
enable:布尔值,设置功能 | HDF_STATUS相关状态 | 设置增强选通 | +| switchVoltage | cntlr:结构体指针,核心层MMC控制器
volt:枚举值,电压值(3.3,1.8,1.2V) | HDF_STATUS相关状态 | 设置电压值 | +| devReadOnly | cntlr:结构体指针,核心层MMC控制器 | 布尔值 | 检验设备是否只读 | +| cardPlugged | cntlr:结构体指针,核心层MMC控制器 | 布尔值 | 检验设备是否拔出 | +| devBusy | cntlr:结构体指针,核心层MMC控制器 | 布尔值 | 检验设备是否忙碌 | +| tune | cntlr:结构体指针,核心层MMC控制器
cmdCode:uint32_t类型,命令代码 | HDF_STATUS相关状态 | 调谐 | +| rescanSdioDev | cntlr:结构体指针,核心层MMC控制器 | HDF_STATUS相关状态 | 扫描并添加SDIO设备 | -4. 驱动调试 +### 开发步骤 - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,设备启动是否成功等。 +MMC模块适配包含以下四个步骤: +- 实例化驱动入口。 +- 配置属性文件。 +- 实例化MMC控制器对象。 +- 驱动调试。 -## 开发实例 +### 开发实例 -下方将以himci.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +下方将基于Hi3516DV300开发板以//device_soc_hisilicon/common/platform/mmc/himci_v200/himci.c驱动为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口。 +1. 实例化驱动入口。 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 - 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - MMC驱动入口参考: - - ``` + MMC驱动入口开发参考: + + ```c struct HdfDriverEntry g_mmcDriverEntry = { .moduleVersion = 1, - .Bind = HimciMmcBind, // 见Bind参考 - .Init = HimciMmcInit, // 见Init参考 - .Release = HimciMmcRelease, // 见Release参考 - .moduleName = "hi3516_mmc_driver",// 【必要且与HCS文件中里面的moduleName匹配】 + .Bind = HimciMmcBind, // 见Bind参考 + .Init = HimciMmcInit, // 见Init参考 + .Release = HimciMmcRelease, // 见Release参考 + .moduleName = "hi3516_mmc_driver", // 【必要且与HCS文件中里面的moduleName匹配】 }; - HDF_INIT(g_mmcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_mmcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在mmc_config.hcs中配置器件属性。 - - deviceNode信息与驱动入口注册相关,器件属性值与核心层MmcCntlr成员的默认值或限制范围有密切关系。 - - 如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在mmc_config文件中增加对应的器件属性。 - - - device_info.hcs 配置参考 - - - ``` - root { - device_info { - match_attr = "hdf_manager"; - platform :: host { - hostName = "platform_host"; - priority = 50; - device_mmc:: device { - device0 :: deviceNode { - policy = 2; - priority = 10; - permission = 0644; - moduleName = "hi3516_mmc_driver"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 - serviceName = "HDF_PLATFORM_MMC_0"; // 【必要】驱动对外发布服务的名称,必须唯一。 - deviceMatchAttr = "hi3516_mmc_emmc";// 【必要】用于配置控制器私有数据,要与mmc_config.hcs中对应控制器保持一致。 - } - device1 :: deviceNode { - policy = 1; - priority = 20; - permission = 0644; - moduleName = "hi3516_mmc_driver"; - serviceName = "HDF_PLATFORM_MMC_1"; - deviceMatchAttr = "hi3516_mmc_sd"; // SD类型 - } - device2 :: deviceNode { - policy = 1; - priority = 30; - permission = 0644; - moduleName = "hi3516_mmc_driver"; - serviceName = "HDF_PLATFORM_MMC_2"; - deviceMatchAttr = "hi3516_mmc_sdio";// SDIO类型 - } - } - } - } - } - ``` - - - mmc_config.hcs配置参考 - - - ``` - root { - platform { - mmc_config { - template mmc_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 - match_attr = ""; - voltDef = 0; // 3.3V - freqMin = 50000; // 【必要】最小频率值 - freqMax = 100000000; // 【必要】最大频率值 - freqDef = 400000; // 【必要】默认频率值 - maxBlkNum = 2048; // 【必要】最大的block号 - maxBlkSize = 512; // 【必要】最大的block个数 - ocrDef = 0x300000; // 【必要】工作电压设置相关 - caps2 = 0; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps2定义。 - regSize = 0x118; // 【必要】寄存器位宽 - hostId = 0; // 【必要】主机号 - regBasePhy = 0x10020000;// 【必要】寄存器物理基地址 - irqNum = 63; // 【必要】中断号 - devType = 2; // 【必要】模式选择:emmc、SD、SDIO、COMBO - caps = 0x0001e045; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps 定义。 - } - controller_0x10100000 :: mmc_controller { - match_attr = "hi3516_mmc_emmc";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - hostId = 0; - regBasePhy = 0x10100000; - irqNum = 96; - devType = 0; // emmc类型 - caps = 0xd001e045; - caps2 = 0x60; - } - controller_0x100f0000 :: mmc_controller { - match_attr = "hi3516_mmc_sd"; - hostId = 1; - regBasePhy = 0x100f0000; - irqNum = 62; - devType = 1; // SD类型 - caps = 0xd001e005; - } - controller_0x10020000 :: mmc_controller { - match_attr = "hi3516_mmc_sdio"; - hostId = 2; - regBasePhy = 0x10020000; - irqNum = 63; - devType = 2; // SDIO类型 - caps = 0x0001e04d; - } - } - } - } - ``` - -3. 完成驱动入口注册之后,下一步就是以核心层MmcCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化MmcCntlr成员MmcCntlrOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - - - 自定义结构体参考 +2. 配置属性文件。 + + 完成驱动入口注册之后,需要在device_info.hcs文件中添加deviceNode信息,deviceNode信息与驱动入口注册相关。本例以三个MMC控制器为例,如有多个器件信息,则需要在device_info.hcs文件增加对应的deviceNode信息。器件属性值与核心层MmcCntlr成员的默认值或限制范围有密切关系,需要在mmc_config.hcs中配置器件属性。 + + - device_info.hcs 配置参考: + + 在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + + ```c + root { + device_info { + match_attr = "hdf_manager"; + platform :: host { + hostName = "platform_host"; + priority = 50; + device_mmc:: device { + device0 :: deviceNode { // 驱动的DeviceNode节点 + policy = 2; // policy字段是驱动服务发布的策略,如果需要面向用户态,则为2 + priority = 10; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "hi3516_mmc_driver"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_MMC_0"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hi3516_mmc_emmc"; // 【必要】用于配置控制器私有数据,要与mmc_config.hcs中对应控制器保持一致。 + } + device1 :: deviceNode { + policy = 1; + priority = 20; + permission = 0644; + moduleName = "hi3516_mmc_driver"; + serviceName = "HDF_PLATFORM_MMC_1"; + deviceMatchAttr = "hi3516_mmc_sd"; // SD类型 + } + device2 :: deviceNode { + policy = 1; + priority = 30; + permission = 0644; + moduleName = "hi3516_mmc_driver"; + serviceName = "HDF_PLATFORM_MMC_2"; + deviceMatchAttr = "hi3516_mmc_sdio"; // SDIO类型 + } + ... + } + } + } + } + ``` + + - mmc_config.hcs配置参考: + + 在//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/mmc/mmc_config.hcs文件配置器件属性,其中配置参数如下: + + ```c + root { + platform { + mmc_config { + template mmc_controller { // 配置模板,如果下面节点使用时继承该模板,则节点中未声明的字段会使用该模板中的默认值。 + match_attr = ""; + voltDef = 0; // MMC默认电压,0代表3.3V,1代表1.8V,2代表1.2V + freqMin = 50000; // 【必要】最小频率值 + freqMax = 100000000; // 【必要】最大频率值 + freqDef = 400000; // 【必要】默认频率值 + maxBlkNum = 2048; // 【必要】最大的block号 + maxBlkSize = 512; // 【必要】最大的block个数 + ocrDef = 0x300000; // 【必要】工作电压设置相关 + caps2 = 0; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps2定义。 + regSize = 0x118; // 【必要】寄存器位宽 + hostId = 0; // 【必要】主机号 + regBasePhy = 0x10020000; // 【必要】寄存器物理基地址 + irqNum = 63; // 【必要】中断号 + devType = 2; // 【必要】模式选择:EMMC、SD、SDIO、COMBO + caps = 0x0001e045; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps定义。 + } + controller_0x10100000 :: mmc_controller { + match_attr = "hi3516_mmc_emmc"; // 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + hostId = 0; + regBasePhy = 0x10100000; + irqNum = 96; + devType = 0; // eMMC类型 + caps = 0xd001e045; + caps2 = 0x60; + } + controller_0x100f0000 :: mmc_controller { + match_attr = "hi3516_mmc_sd"; + hostId = 1; + regBasePhy = 0x100f0000; + irqNum = 62; + devType = 1; // SD类型 + caps = 0xd001e005; + } + controller_0x10020000 :: mmc_controller { + match_attr = "hi3516_mmc_sdio"; + hostId = 2; + regBasePhy = 0x10020000; + irqNum = 63; + devType = 2; // SDIO类型 + caps = 0x0001e04d; + } + } + } + } + ``` - 从驱动的角度看,自定义结构体是参数和数据的载体,而且mmc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 + 需要注意的是,新增mmc_config.hcs配置文件后,必须在产品对应的hdf.hcs文件中将其包含如下语句所示,否则配置文件无法生效。 - + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/mmc/mmc_config.hcs" // 配置文件相对路径 ``` + +3. 实例化MMC控制器对象。 + + 完成配置属性文件之后,下一步就是以核心层MmcCntlr对象的初始化为核心,包括驱动适配自定义结构体(传递参数和数据),实例化MmcCntlr成员MmcCntlrOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + + - 驱动适配者自定义结构体参考 + + 从驱动的角度看,自定义结构体是参数和数据的载体,而且mmc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 + + ```c struct HimciHost { - struct MmcCntlr *mmc;// 【必要】核心层结构体 - struct MmcCmd *cmd; // 【必要】核心层结构体,传递命令的,相关命令见枚举量MmcCmdCode。 - // 【可选】根据厂商驱动需要添加 - void *base; + struct MmcCntlr *mmc; // 【必要】核心层控制对象 + struct MmcCmd *cmd; // 【必要】核心层结构体,传递命令,相关命令见枚举量MmcCmdCode + void *base; // 地址映射需要,寄存器基地址 enum HimciPowerStatus powerStatus; uint8_t *alignedBuff; uint32_t buffLen; @@ -260,53 +287,54 @@ MMC模块适配的三个必选环节是实例化驱动入口,配置属性文 }; ``` - - MmcCntlr成员回调函数结构体MmcCntlrOps的实例化,其他成员在Bind函数中初始化。 + - MmcCntlr成员钩子函数结构体MmcCntlrOps的实例化,其他成员在Bind函数中初始化。 - - ``` + ```c static struct MmcCntlrOps g_himciHostOps = { - .request = HimciDoRequest, - .setClock = HimciSetClock, - .setPowerMode = HimciSetPowerMode, - .setBusWidth = HimciSetBusWidth, - .setBusTiming = HimciSetBusTiming, - .setSdioIrq = HimciSetSdioIrq, - .hardwareReset = HimciHardwareReset, - .systemInit = HimciSystemInit, - .setEnhanceStrobe= HimciSetEnhanceStrobe, - .switchVoltage = HimciSwitchVoltage, - .devReadOnly = HimciDevReadOnly, - .devPlugged = HimciCardPlugged, - .devBusy = HimciDevBusy, - .tune = HimciTune, - .rescanSdioDev = HimciRescanSdioDev, + .request = HimciDoRequest, + .setClock = HimciSetClock, + .setPowerMode = HimciSetPowerMode, + .setBusWidth = HimciSetBusWidth, + .setBusTiming = HimciSetBusTiming, + .setSdioIrq = HimciSetSdioIrq, + .hardwareReset = HimciHardwareReset, + .systemInit = HimciSystemInit, + .setEnhanceStrobe = HimciSetEnhanceStrobe, + .switchVoltage = HimciSwitchVoltage, + .devReadOnly = HimciDevReadOnly, + .devPlugged = HimciCardPlugged, + .devBusy = HimciDevBusy, + .tune = HimciTune, + .rescanSdioDev = HimciRescanSdioDev, }; ``` - - Bind函数参考 + + - Bind函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 - | 状态(值) | 问题描述 | + **表2** Bind函数说明 + + | 状态(值) | 问题描述 | | -------- | -------- | - | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_INVALID_PARAM | 参数非法 | - | HDF_ERR_IO | I/O 错误 | - | HDF_SUCCESS | 初始化成功 | - | HDF_FAILURE | 初始化失败 | + | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_INVALID_PARAM | 参数非法 | + | HDF_ERR_IO | I/O 错误 | + | HDF_SUCCESS | 初始化成功 | + | HDF_FAILURE | 初始化失败 | 函数说明: - MmcCntlr、HimciHost、HdfDeviceObject之间互相赋值,方便其他函数可以相互转化,初始化自定义结构体HimciHost对象,初始化MmcCntlr成员,调用核心层MmcCntlrAdd函数。 + MmcCntlr、HimciHost、HdfDeviceObject之间互相赋值,方便其他函数可以相互转化,初始化自定义结构体HimciHost对象,初始化MmcCntlr成员,调用核心层MmcCntlrAdd函数,完成MMC控制器的添加。 - - ``` + ```c static int32_t HimciMmcBind(struct HdfDeviceObject *obj) { struct MmcCntlr *cntlr = NULL; @@ -315,34 +343,34 @@ MMC模块适配的三个必选环节是实例化驱动入口,配置属性文 cntlr = (struct MmcCntlr *)OsalMemCalloc(sizeof(struct MmcCntlr)); host = (struct HimciHost *)OsalMemCalloc(sizeof(struct HimciHost)); - host->mmc = cntlr; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 - cntlr->priv = (void *)host; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 - cntlr->ops = &g_himciHostOps; // 【必要】MmcCntlrOps的实例化对象的挂载 - cntlr->hdfDevObj = obj; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 - obj->service = &cntlr->service; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 - ret = MmcCntlrParse(cntlr, obj); // 【必要】 初始化cntlr,失败就goto _ERR。 - ... - ret = HimciHostParse(host, obj); // 【必要】 初始化host对象的相关属性,失败就goto _ERR。 + host->mmc = cntlr; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 + cntlr->priv = (void *)host; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 + cntlr->ops = &g_himciHostOps; // 【必要】MmcCntlrOps的实例化对象的挂载 + cntlr->hdfDevObj = obj; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 + obj->service = &cntlr->service; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 + ret = MmcCntlrParse(cntlr, obj); // 【必要】 初始化cntlr,失败就goto _ERR。 + ... + ret = HimciHostParse(host, obj); // 【必要】 初始化host对象的相关属性,失败就goto _ERR。 ... - ret = HimciHostInit(host, cntlr); // 厂商自定义的初始化,失败就goto _ERR。 + ret = HimciHostInit(host, cntlr); // 驱动适配者自定义的初始化,失败就goto _ERR。 ... - ret = MmcCntlrAdd(cntlr); // 调用核心层函数,失败就goto _ERR。 + ret = MmcCntlrAdd(cntlr); // 调用核心层函数,失败就goto _ERR。 ... - (void)MmcCntlrAddDetectMsgToQueue(cntlr);// 将卡检测消息添加到队列中。 + (void)MmcCntlrAddDetectMsgToQueue(cntlr); // 将卡检测消息添加到队列中。 HDF_LOGD("HimciMmcBind: success."); return HDF_SUCCESS; - _ERR: + ERR: HimciDeleteHost(host); HDF_LOGD("HimciMmcBind: fail, err = %d.", ret); return ret; } ``` - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: @@ -352,8 +380,7 @@ MMC模块适配的三个必选环节是实例化驱动入口,配置属性文 实现ProcMciInit。 - - ``` + ```c static int32_t HimciMmcInit(struct HdfDeviceObject *obj) { static bool procInit = false; @@ -368,11 +395,12 @@ MMC模块适配的三个必选环节是实例化驱动入口,配置属性文 return HDF_SUCCESS; } ``` - - Release函数参考 + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: @@ -380,20 +408,22 @@ MMC模块适配的三个必选环节是实例化驱动入口,配置属性文 函数说明: - 释放内存和删除控制器等操作,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用 Release释放驱动资源。 + 释放内存和删除控制器等操作,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 - - - ``` + ```c static void HimciMmcRelease(struct HdfDeviceObject *obj) { struct MmcCntlr *cntlr = NULL; ... - cntlr = (struct MmcCntlr *)obj->service; // 这里有HdfDeviceObject到MmcCntlr的强制转化,通过service成员,赋值见Bind函数。 + cntlr = (struct MmcCntlr *)obj->service; // 这里有HdfDeviceObject到MmcCntlr的强制转化,通过service成员,赋值见Bind函数。 ... - HimciDeleteHost((struct HimciHost *)cntlr->priv);// 厂商自定义的内存释放函数,这里有MmcCntlr到HimciHost的强制转化。 + HimciDeleteHost((struct HimciHost *)cntlr->priv); // 驱动适配者自定义的内存释放函数,这里有MmcCntlr到HimciHost的强制转化。 } ``` + +4. 驱动调试。 + + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-pin-des.md b/zh-cn/device-dev/driver/driver-platform-pin-des.md index b81839ada182907fe0dd3be34bd6036b5a29a693..aaa3ee8e27dddec654de040ada8e910ad73b394a 100644 --- a/zh-cn/device-dev/driver/driver-platform-pin-des.md +++ b/zh-cn/device-dev/driver/driver-platform-pin-des.md @@ -1,18 +1,21 @@ -# PIN +# PIN ## 概述 ### 功能简介 -PIN即管脚控制器,用于统一管理各SoC厂商管脚资源,对外提供管脚复用功能:包括管脚推拉方式、管脚推拉强度以及管脚功能。 +PIN即管脚控制器,用于统一管理各SoC的管脚资源,对外提供管脚复用功能:包括管脚推拉方式、管脚推拉强度以及管脚功能。 + PIN接口定义了操作PIN管脚的通用方法集合,包括: -- 获取/释放管脚描述句柄: 传入管脚名与链表中每个控制器下管脚名进行匹配,匹配则会获取一个管脚描述句柄,操作完PIN管脚后释放该管脚描述句柄。 -- 设置/获取管脚推拉方式:推拉方式可以是上拉、下拉以及悬空。 -- 设置/获取管脚推拉强度:用户可根据实际设置管脚推拉强度大小。 -- 设置/获取管脚功能:通过管脚功能名设置/获取管脚功能,实现管脚复用。 + +- 获取/释放管脚描述句柄:传入管脚名与链表中每个控制器下管脚名进行匹配,匹配则会获取一个管脚描述句柄,操作完PIN管脚后释放该管脚描述句柄。 +- 设置/获取管脚推拉方式:推拉方式可以是上拉、下拉以及悬空。 +- 设置/获取管脚推拉强度:用户可根据实际设置管脚推拉强度大小。 +- 设置/获取管脚功能:通过管脚功能名设置/获取管脚功能,实现管脚复用。 ### 基本概念 -PIN是一个软件层面的概念,目的是为了统一各SoC厂商PIN管脚管理,对外提供管脚复用功能,配置PIN管脚的电气特性。 + +PIN是一个软件层面的概念,目的是为了统一各SoC的PIN管脚管理,对外提供管脚复用功能,配置PIN管脚的电气特性。 - SoC(System on Chip) @@ -24,50 +27,53 @@ PIN是一个软件层面的概念,目的是为了统一各SoC厂商PIN管脚 ### 运作机制 -在HDF框架中,PIN模块暂不支持用户态,所以不需要发布服务。接口适配模式采用无服务模式,用于不需要在用户态提供API的设备类型。对于没有用户态和内核区分的OS系统,其关联方式是DevHandle直接指向设备对象内核态地址(DevHandle是一个void类型指针)。 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。PIN模块接口适配模式采用统一服务模式。 + +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 PIN模块各分层作用: + - 接口层提供获取PIN管脚、设置PIN管脚推拉方式、获取PIN管脚推拉方式、设置PIN管脚推拉强度、获取PIN管脚推拉强度、设置PIN管脚功能、获取PIN管脚功能、释放PIN管脚的接口。 - 核心层主要提供PIN管脚资源匹配,PIN管脚控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互。 - 适配层主要是将钩子函数的功能实例化,实现具体的功能。 -**图 1** PIN无服务模式 -![](figures/无服务模式结构图.png "PIN无服务模式") +**图 1** PIN统一服务模式 +![PIN统一服务模式](figures/统一服务模式结构图.png "统一服务模式") ### 约束与限制 - PIN模块目前仅支持轻量和小型系统内核(LiteOS)。 +PIN模块目前只支持小型系统LiteOS-A内核。 - ## 使用指导 +## 使用指导 - ### 场景介绍 +### 场景介绍 - PIN模块仅是一个软件层面的概念,主要工作是管脚资源管理。使用复用管脚时,通过设置管脚功能、设置管脚推拉方式、设置管脚推拉强度来适配指定场景的需求。 +PIN模块仅是一个软件层面的概念,主要工作是管脚资源管理。使用复用管脚时,通过设置管脚功能、设置管脚推拉方式、设置管脚推拉强度来适配指定场景的需求。 ### 接口说明 -PIN模块提供的主要接口如[表1](#table1)所示,更多关于接口的介绍请参考对应的API接口文档。 +PIN模块提供的主要接口如表1所示,更多关于接口的介绍请参考对应的API接口文档。 **表 1** PIN驱动API接口功能介绍 | **接口名** | **描述** | | ------------------------------------------------------------ | ---------------- | -| DevHandle PinGet(const char *pinName); | 获取管脚描述句柄 | -| void PinPut(DevHandle handle); | 释放管脚描述句柄 | -| int32_t PinSetPull(DevHandle handle, enum PinPullType pullType); | 设置管脚推拉方式 | -| int32_t PinGetPull(DevHandle handle, enum PinPullType *pullType); | 获取管脚推拉方式 | -| int32_t PinSetStrength(DevHandle handle, uint32_t strength); | 设置管脚推拉强度 | -| int32_t PinGetStrength(DevHandle handle, uint32_t *strength); | 获取管脚推拉强度 | -| int32_t PinSetFunc(DevHandle handle, const char *funcName); | 设置管脚功能 | -| int32_t PinGetFunc(DevHandle handle, const char **funcName); | 获取管脚功能 | +| DevHandle PinGet(const char *pinName) | 获取管脚描述句柄 | +| void PinPut(DevHandle handle) | 释放管脚描述句柄 | +| int32_t PinSetPull(DevHandle handle, enum PinPullType pullType) | 设置管脚推拉方式 | +| int32_t PinGetPull(DevHandle handle, enum PinPullType *pullType) | 获取管脚推拉方式 | +| int32_t PinSetStrength(DevHandle handle, uint32_t strength) | 设置管脚推拉强度 | +| int32_t PinGetStrength(DevHandle handle, uint32_t *strength) | 获取管脚推拉强度 | +| int32_t PinSetFunc(DevHandle handle, const char *funcName) | 设置管脚功能 | +| int32_t PinGetFunc(DevHandle handle, const char **funcName) | 获取管脚功能 | >![](../public_sys-resources/icon-note.gif) **说明:**
->本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +>本文涉及PIN的所有接口,支持内核态及用户态使用。 ### 开发步骤 -使用PIN设备的一般流程如[图2](#fig2)所示。 +使用PIN设备的一般流程如图2所示。 **图 2** PIN使用流程图 ![](figures/PIN使用流程图.png "PIN使用流程图") @@ -76,7 +82,7 @@ PIN模块提供的主要接口如[表1](#table1)所示,更多关于接口的 在使用PIN进行管脚操作时,首先要调用PinGet获取管脚描述句柄,该函数会返回匹配传入管脚名的管脚描述句柄。 -``` +```c DevHandle PinGet(const char *pinName); ``` @@ -93,9 +99,10 @@ DevHandle PinGet(const char *pinName); 假设PIN需要操作的管脚名为P18,获取其管脚描述句柄的示例如下: -``` -DevHandle handle = NULL; /* PIN管脚描述句柄 */ -char pinName = "P18"; /* PIN管脚号 */ +```c +DevHandle handle = NULL; // PIN管脚描述句柄 + +char pinName = "P18"; // PIN管脚名 handle = PinGet(pinName); if (handle == NULL) { HDF_LOGE("PinGet: get handle failed!\n"); @@ -107,7 +114,7 @@ if (handle == NULL) { PIN设置管脚推拉方式的函数如下所示: -``` +```c int32_t PinSetPull(DevHandle handle, enum PinPullType pullType); ``` @@ -125,9 +132,10 @@ int32_t PinSetPull(DevHandle handle, enum PinPullType pullType); 假设PIN要设置的管脚推拉方式为上拉,其实例如下: -``` +```c int32_t ret; enum PinPullType pullTypeNum; + /* PIN设置管脚推拉方式 */ pullTypeNum = 1; ret = PinSetPull(handle, pullTypeNum); @@ -141,7 +149,7 @@ if (ret != HDF_SUCCESS) { PIN获取管脚推拉方式的函数如下所示: -``` +```c int32_t PinGetPull(DevHandle handle, enum PinPullType *pullType); ``` @@ -159,9 +167,10 @@ int32_t PinGetPull(DevHandle handle, enum PinPullType *pullType); PIN获取管脚推拉方式的实例如下: -``` +```c int32_t ret; enum PinPullType pullTypeNum; + /* PIN获取管脚推拉方式 */ ret = PinGetPull(handle, &pullTypeNum); if (ret != HDF_SUCCESS) { @@ -174,7 +183,7 @@ if (ret != HDF_SUCCESS) { PIN设置管脚推拉强度函数如下所示: -``` +```c int32_t PinSetStrength(DevHandle handle, uint32_t strength); ``` @@ -192,7 +201,7 @@ int32_t PinSetStrength(DevHandle handle, uint32_t strength); 假设PIN要设置的管脚推拉强度为2,其实例如下: -``` +```c int32_t ret; uint32_t strengthNum; /* PIN设置管脚推拉强度 */ @@ -208,7 +217,7 @@ if (ret != HDF_SUCCESS) { PIN设置管脚推拉强度后,可以通过PIN获取管脚推拉强度接口来查看PIN管脚推拉强度,PIN获取管脚推拉强度的函数如下所示: -``` +```c int32_t PinGetStrength(DevHandle handle, uint32_t *strength); ``` @@ -226,9 +235,10 @@ int32_t PinGetStrength(DevHandle handle, uint32_t *strength); PIN获取管脚推拉强度的实例如下: -``` +```c int32_t ret; uint32_t strengthNum; + /* PIN获取管脚推拉强度 */ ret = PinGetStrength(handle, &strengthNum); if (ret != HDF_SUCCESS) { @@ -239,11 +249,11 @@ if (ret != HDF_SUCCESS) { #### PIN设置管脚功能 -管脚功能特指的是管脚复用的功能,每个管脚功能都不相同,管脚功能名详细可以参考[PIN配置hcs文件](https://gitee.com/openharmony/device_soc_hisilicon/blob/master/hi3516dv300/sdk_liteos/hdf_config/pin/pin_config.hcs)。 +管脚功能特指的是管脚复用的功能,每个管脚功能都不相同,管脚功能名详细可以参考//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pin/pin_config.hcs。 PIN设置管脚功能函数如下所示: -``` +```c int32_t PinSetFunc(DevHandle handle, const char *funcName); ``` @@ -261,9 +271,10 @@ int32_t PinSetFunc(DevHandle handle, const char *funcName); 假设PIN需要设置的管脚功能为LSADC_CH1(ADC通道1),其实例如下: -``` +```c int32_t ret; char funcName = "LSADC_CH1"; + /* PIN设置管脚功能 */ ret = PinSetFunc(handle, funcName); if (ret != HDF_SUCCESS) { @@ -276,7 +287,7 @@ if (ret != HDF_SUCCESS) { PIN设置管脚功能后,可以通过PIN获取管脚功能接口来查看PIN管脚功能,PIN获取管脚功能的函数如下所示: -``` +```c int32_t PinGetFunc(DevHandle handle, const char **funcName); ``` @@ -294,11 +305,12 @@ int32_t PinGetFunc(DevHandle handle, const char **funcName); PIN获取管脚功能的实例如下: -``` +```c int32_t ret; -char *funcName; +char *funcName = NULL; + /* PIN获取管脚功能 */ -ret = PinGetFunc(handle,&funcName); +ret = PinGetFunc(handle, &funcName); if (ret != HDF_SUCCESS) { HDF_LOGE("PinGetFunc: failed, ret %d\n", ret); return ret; @@ -309,7 +321,7 @@ if (ret != HDF_SUCCESS) { PIN不再进行任何操作后,需要释放PIN管脚描述管脚句柄,函数如下所示: -``` +```c void PinPut(DevHandle handle); ``` @@ -325,13 +337,14 @@ void PinPut(DevHandle handle); PIN销毁管脚描述句柄实例如下: -``` +```c PinPut(handle); ``` ## 使用实例 -使用PIN设置管脚相关属性完整使用可以参考如下示例代码,步骤主要如下: +下面将基于Hi3516DV300开发板展示使用PIN设置管脚相关属性完整操作,步骤主要如下: + 1. 传入要设置的管脚名,获取PIN管脚描述句柄。 2. 通过PIN管脚描述句柄以及推拉方式pullTypeNum设置管脚推拉方式,如果操作失败则释放PIN管脚描述句柄。 3. 通过PIN管脚描述句柄,并用pullTypeNum承接获取的管脚推拉方式,如果操作失败则释放PIN管脚描述句柄。 @@ -341,9 +354,9 @@ PinPut(handle); 6. 通过PIN管脚描述句柄,并用funName承接获取的管脚功能名,如果操作失败则释放PIN管脚描述句柄。 7. 使用完PIN后,不再对管脚进行操作,释放PIN管脚描述句柄。 -``` -#include "hdf_log.h" /* 标准日志打印头文件 */ -#include "pin_if.h" /* PIN标准接口头文件 */ +```c +#include "hdf_log.h" /* 标准日志打印头文件 */ +#include "pin_if.h" /* PIN标准接口头文件 */ int32_t PinTestSample(void) { @@ -359,7 +372,7 @@ int32_t PinTestSample(void) /* PIN获取管脚描述句柄 */ handle = PinGet(pinName); if (handle == NULL) { - HDF_LOGE("PinGet: failed!\n"); + HDF_LOGE("PinGet: pin get failed!\n"); return; } /* PIN设置管脚推拉方式为上拉 */ @@ -405,4 +418,5 @@ ERR: /* 释放PIN管脚描述句柄 */ PinPut(handle); return ret; -} \ No newline at end of file +} +``` diff --git a/zh-cn/device-dev/driver/driver-platform-pin-develop.md b/zh-cn/device-dev/driver/driver-platform-pin-develop.md index f3da58f351440a893e3566eda4d94eaf72dcc6b4..00ae1b6b003d658265815ed4535c47845aa03a67 100755 --- a/zh-cn/device-dev/driver/driver-platform-pin-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-pin-develop.md @@ -1,18 +1,18 @@ # PIN - ## 概述 ### 功能简介 -PIN即管脚控制器,用于统一管理各SoC厂商管脚资源,对外提供管脚复用功能。 + +PIN即管脚控制器,用于统一管理各SoC的管脚资源,对外提供管脚复用功能。 ### 基本概念 -PIN是一个软件层面的概念,目的是为了统一各SoC厂商PIN管脚管理,对外提供管脚复用功能,配置PIN管脚的电气特性。 +PIN是一个软件层面的概念,目的是为了统一对各SoC的PIN管脚进行管理,对外提供管脚复用功能,配置PIN管脚的电气特性。 - SoC(System on Chip) - 系统级芯片,也有称作片上系统,通常是面向特定用途将微处理器、模拟IP核、数字IP核和存储器集成在单一芯片的标准产品。 + 系统级芯片,又称作片上系统,通常是面向特定用途将微处理器、模拟IP核、数字IP核和存储器集成在单一芯片的标准产品。 - 管脚复用 @@ -20,30 +20,34 @@ PIN是一个软件层面的概念,目的是为了统一各SoC厂商PIN管脚 ### 运作机制 -在HDF框架中,PIN模块暂不支持用户态,所以不需要发布服务。接口适配模式采用无服务模式(如图1所示),用于不需要在用户态提供API的设备类型。对于没有用户态和内核区分的OS系统,其关联方式是DevHandle直接指向设备对象内核态地址(DevHandle是一个void类型指针)。 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。PIN模块接口适配模式采用统一服务模式(如图1所示)。 + +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 PIN模块各分层作用: + - 接口层提供获取PIN管脚、设置PIN管脚推拉方式、获取PIN管脚推拉方式、设置PIN管脚推拉强度、获取PIN管脚推拉强度、设置PIN管脚功能、获取PIN管脚功能、释放PIN管脚的接口。 - 核心层主要提供PIN管脚资源匹配,PIN管脚控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互。 - 适配层主要是将钩子函数的功能实例化,实现具体的功能。 -**图 1** 无服务模式结构图 +**图 1** 统一服务模式结构图 -![无服务模式结构图](figures/无服务模式结构图.png) +![统一服务模式结构图](figures/统一服务模式结构图.png) ### 约束与限制 -PIN模块目前仅支持轻量和小型系统内核(LiteOS)。 +PIN模块目前只支持小型系统LiteOS-A内核。 ## 开发指导 ### 场景介绍 -PIN模块主要用于管脚资源管理。在各SoC厂商对接HDF框架时,需要来适配PIN驱动。 +PIN模块主要用于管脚资源管理。在各SoC对接HDF框架时,需要来适配PIN驱动。下文将介绍如何进行PIN驱动适配。 ### 接口说明 -通过以下PinCntlrMethod中的函数调用PIN驱动对应的函数。 +为了保证上层在调用PIN接口时能够正确的操作PIN管脚,核心层在//drivers/hdf_core/framework/support/platform/include/pin/pin_core.h中定义了以下钩子函数,驱动适配者需要在适配层实现这些函数的具体功能,并与钩子函数挂接,从而完成适配层与核心层的交互。 + PinCntlrMethod定义: ```c @@ -57,383 +61,410 @@ struct PinCntlrMethod { }; ``` -**表 1** PinCntlrMethod成员的回调函数功能说明 +**表 1** PinCntlrMethod成员的钩子函数功能说明 | 成员函数 | 入参 | 出参 | 返回值 | 功能 | | ------------ | ------------------------------------------- | ------ | ---- | ---- | -| SetPinPull | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号
pullType:枚举常量,Pin管脚推拉方式 | 无 |HDF_STATUS相关状态|PIN设置管脚推拉方式| -| GetPinPull | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号 | pullType:枚举常量指针,传出Pin管脚推拉方式 | HDF_STATUS相关状态 | PIN获取管脚推拉方式 | -| SetPinStrength | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号
strength:uint32_t变量,Pin推拉强度 | 无 | HDF_STATUS相关状态 | PIN设置推拉强度 | -| GetPinStrength | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号 | strength:uint32_t变量指针,传出Pin推拉强度 | HDF_STATUS相关状态 | PIN获取推拉强度 | -| SetPinFunc | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号
funcName:char指针常量,传入Pin管脚功能 | 无 | HDF_STATUS相关状态 | PIN设置管脚功能 | -| GetPinFunc | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号 | funcName:char双重指针常量,传出Pin管脚功能 | HDF_STATUS相关状态 | PIN获取管脚功能 | +| SetPinPull | cntlr:结构体指针,核心层PIN控制器
index:uint32_t类型变量,管脚索引号
pullType:枚举常量,PIN管脚推拉方式 | 无 |HDF_STATUS相关状态|PIN设置管脚推拉方式| +| GetPinPull | cntlr:结构体指针,核心层PIN控制器
index:uint32_t类型变量,管脚索引号 | pullType:枚举常量指针,传出获取的PIN管脚推拉方式 | HDF_STATUS相关状态 | PIN获取管脚推拉方式 | +| SetPinStrength | cntlr:结构体指针,核心层PIN控制器
index:uint32_t类型变量,管脚索引号
strength:uint32_t变量,PIN推拉强度 | 无 | HDF_STATUS相关状态 | PIN设置推拉强度 | +| GetPinStrength | cntlr:结构体指针,核心层PIN控制器
index:uint32_t类型变量,管脚索引号 | strength:uint32_t变量指针,传出获取的PIN推拉强度 | HDF_STATUS相关状态 | PIN获取推拉强度 | +| SetPinFunc | cntlr:结构体指针,核心层PIN控制器
index:uint32_t类型变量,管脚索引号
funcName:char指针常量,传入PIN管脚功能 | 无 | HDF_STATUS相关状态 | PIN设置管脚功能 | +| GetPinFunc | cntlr:结构体指针,核心层PIN控制器
index:uint32_t类型变量,管脚索引号 | funcName:char双重指针常量,传出获取的PIN管脚功能 | HDF_STATUS相关状态 | PIN获取管脚功能 | ### 开发步骤 -PIN模块适配包含以下四个步骤: +PIN模块适配HDF框架包含以下四个步骤: - 实例化驱动入口。 - 配置属性文件。 -- 实例化核心层接口函数。 +- 实例化PIN控制器对象。 - 驱动调试。 -1. 实例化驱动入口: - - - 实例化HdfDriverEntry结构体成员。 - - 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 - - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 - - 一般在加载驱动时HDF会先调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - - ```c - static struct HdfDriverEntry g_hi35xxPinDriverEntry = { - .moduleVersion = 1, - .Bind = Hi35xxPinBind, - .Init = Hi35xxPinInit, - .Release = Hi35xxPinRelease, - .moduleName = "hi35xx_pin_driver", // 【必要且与HCS文件中里面的moduleName匹配】 - }; - HDF_INIT(g_hi35xxPinDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 - ``` - -2. 配置属性文件: - - - 在vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 - - ```c - root { - device_info { - platform :: host { - hostName = "platform_host"; - priority = 50; - device_pin :: device { - device0 :: deviceNode { // 为每一个Pin控制器配置一个HDF设备节点,存在多个时须添加,否则不用。 - policy = 0; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 - priority = 10; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 */ - moduleName = "hi35xx_pin_driver"; - /* 【必要】用于配置控制器私有数据,要与pin_config.hcs中对应控制器保持一致,具体的控制器信息在pin_config.hcs中。 */ - deviceMatchAttr = "hisilicon_hi35xx_pin_0"; - } - device1 :: deviceNode { - policy = 0; - priority = 10; - permission = 0644; - moduleName = "hi35xx_pin_driver"; - deviceMatchAttr = "hisilicon_hi35xx_pin_1"; - } - ...... - } - } - } - } - ``` - - 添加pin_config.hcs器件属性文件。 - - 在device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pin/pin_config.hcs目录下配置器件属性,其中配置参数如下: - ```c - root { - platform { - pin_config_hi35xx { - template pin_controller { // 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 - number = 0; // 【必要】controller编号 - regStartBasePhy = 0; // 【必要】寄存器物理基地址起始地址 - regSize = 0; // 【必要】寄存器位宽 - pinCount = 0; // 【必要】管脚数量 - match_attr = ""; - template pin_desc { - pinName = ""; // 【必要】管脚名称 - init = 0; // 【必要】寄存器默认值 - F0 = ""; // 【必要】功能0 - F1 = ""; // 功能1 - F2 = ""; // 功能2 - F3 = ""; // 功能3 - F4 = ""; // 功能4 - F5 = ""; // 功能5 - } - } - controller_0 :: pin_controller { - number = 0; - regStartBasePhy = 0x10FF0000; - regSize = 0x48; - pinCount = 18; - match_attr = "hisilicon_hi35xx_pin_0"; - T1 :: pin_desc { - pinName = "T1"; - init = 0x0600; - F0 = "EMMC_CLK"; - F1 = "SFC_CLK"; - F2 = "SFC_BOOT_MODE"; - } - ...... // 对应管脚控制器下的每个管脚,按实际添加。 - } - ......// 每个管脚控制器对应一个controller节点,如存在多个Pin控制器,请依次添加对应的controller节点。 - } - } - } - ``` - -3. 实例化PIN控制器对象: - - - 初始化PinCntlr成员。 - - 在Hi35xxPinCntlrInit函数中对PinCntlr成员进行初始化操作。 - - ```c - struct Hi35xxPinDesc { - // 管脚名 - const char *pinName; - // 初始化值 - uint32_t init; - // 管脚索引 - uint32_t index; - // 管脚推拉方式 - int32_t pullType; - // 管脚推拉强度 - int32_t strength; - // 管脚功能名字符串数组 - const char *func[HI35XX_PIN_FUNC_MAX]; - }; - - struct Hi35xxPinCntlr { - // 管脚控制器 - struct PinCntlr cntlr; - // 管脚描述结构体指针 - struct Hi35xxPinDesc *desc; - // 寄存器映射地址 - volatile unsigned char *regBase; - // 管脚控制器编号 - uint16_t number; - // 寄存器物理基地址起始地址 - uint32_t regStartBasePhy; - // 寄存器位宽 - uint32_t regSize; - // 管脚数量 - uint32_t pinCount; - }; - - // PinCntlr是核心层控制器,其中的成员在Init函数中会被赋值。 - struct PinCntlr { - struct IDeviceIoService service; - struct HdfDeviceObject *device; - struct PinCntlrMethod *method; - struct DListHead node; // 链表节点 - OsalSpinlock spin; // 自旋锁 - uint16_t number; // 管脚控制器编号 - uint16_t pinCount; // 管脚数量 - struct PinDesc *pins; - void *priv; // 私有数据 - }; - - // PinCntlr管脚控制器初始化 - static int32_t Hi35xxPinCntlrInit(struct HdfDeviceObject *device, struct Hi35xxPinCntlr *hi35xx) - { - struct DeviceResourceIface *drsOps = NULL; - int32_t ret; - // 从hcs文件读取管脚控制器相关属性 - drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); - if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetUint16 == NULL) { - HDF_LOGE("%s: invalid drs ops fail!", __func__); - return HDF_FAILURE; - } - ret = drsOps->GetUint16(device->property, "number", &hi35xx->number, 0); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read number failed", __func__); - return ret; - } - - ret = drsOps->GetUint32(device->property, "regStartBasePhy", &hi35xx->regStartBasePhy, 0); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read regStartBasePhy failed", __func__); - return ret; - } - ret = drsOps->GetUint32(device->property, "regSize", &hi35xx->regSize, 0); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read regSize failed", __func__); - return ret; - } - ret = drsOps->GetUint32(device->property, "pinCount", &hi35xx->pinCount, 0); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read pinCount failed", __func__); - return ret; - } - // 将读取的值赋值给管脚控制器的成员,完成管脚控制器初始化。 - hi35xx->cntlr.pinCount = hi35xx->pinCount; - hi35xx->cntlr.number = hi35xx->number; - hi35xx->regBase = OsalIoRemap(hi35xx->regStartBasePhy, hi35xx->regSize); // 管脚控制器映射 - if (hi35xx->regBase == NULL) { - HDF_LOGE("%s: remap Pin base failed", __func__); - return HDF_ERR_IO; - } - hi35xx->desc = (struct Hi35xxPinDesc *)OsalMemCalloc(sizeof(struct Hi35xxPinDesc) * hi35xx->pinCount); - hi35xx->cntlr.pins = (struct PinDesc *)OsalMemCalloc(sizeof(struct PinDesc) * hi35xx->pinCount); - return HDF_SUCCESS; - } - ``` - - - PinCntlr成员回调函数结构体PinCntlrMethod的实例化,其他成员在Init函数中初始化。 - - ```c - // PinCntlrMethod结构体成员都是回调函数,厂商需要根据表1完成相应的函数功能。 - static struct PinCntlrMethod g_method = { - .SetPinPull = Hi35xxPinSetPull, // 设置推拉方式 - .GetPinPull = Hi35xxPinGetPull, // 获取推拉方式 - .SetPinStrength = Hi35xxPinSetStrength, // 设置推拉强度 - .GetPinStrength = Hi35xxPinGetStrength, // 获取推拉强度 - .SetPinFunc = Hi35xxPinSetFunc, // 设置管脚功能 - .GetPinFunc = Hi35xxPinGetFunc, // 获取管脚功能 - }; - ``` - - - Init函数 - - 入参: - - HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 - - 返回值: - - HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见/drivers/framework/include/utils/hdf\_base.h中HDF\_STATUS定义)。 - - | **状态(值)** | **问题描述** | - | ---------------------- | -------------- | - | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_INVALID_PARAM | 参数非法 | - | HDF_ERR_IO | I/O 错误 | - | HDF_SUCCESS | 初始化成功 | - | HDF_FAILURE | 初始化失败 | - - 函数说明: - - 初始化自定义结构体对象和PinCntlr成员,并通过调用核心层PinCntlrAdd函数挂载Pin控制器。 - - ```c - static int32_t Hi35xxPinReadFunc(struct Hi35xxPinDesc *desc, const struct DeviceResourceNode *node, struct DeviceResourceIface *drsOps) - { - int32_t ret; - uint32_t funcNum = 0; - // 从hcs中读取管脚控制器子节点管脚功能名 - ret = drsOps->GetString(node, "F0", &desc->func[funcNum], "NULL"); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read F0 failed", __func__); - return ret; - } - - funcNum++; - ret = drsOps->GetString(node, "F1", &desc->func[funcNum], "NULL"); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read F1 failed", __func__); - return ret; - } - - funcNum++; - ...... - return HDF_SUCCESS; - } - - static int32_t Hi35xxPinParsePinNode(const struct DeviceResourceNode *node, struct Hi35xxPinCntlr *hi35xx, int32_t index) - { - int32_t ret; - struct DeviceResourceIface *drsOps = NULL; - // 从hcs中读取管脚控制器子节点管脚相关属性 - drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); - if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetString == NULL) { - HDF_LOGE("%s: invalid drs ops fail!", __func__); - return HDF_FAILURE; - } - ret = drsOps->GetString(node, "pinName", &hi35xx->desc[index].pinName, "NULL"); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read pinName failed", __func__); - return ret; - } - ...... - ret = Hi35xxPinReadFunc(&hi35xx->desc[index], node, drsOps); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s:Pin read Func failed", __func__); - return ret; - } - hi35xx->cntlr.pins[index].pinName = hi35xx->desc[index].pinName; - hi35xx->cntlr.pins[index].priv = (void *)node; - ...... - return HDF_SUCCESS; - } - - static int32_t Hi35xxPinInit(struct HdfDeviceObject *device) - { - ...... - struct Hi35xxPinCntlr *hi35xx = NULL; - ...... - ret = Hi35xxPinCntlrInit(device, hi35xx); // 管脚控制器初始化 - ...... - DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { // 遍历管脚控制器的每个子节点 - ret = Hi35xxPinParsePinNode(childNode, hi35xx, index); // 解析子节点 - ...... - } - - hi35xx->cntlr.method = &g_method; // 实例化method - ret = PinCntlrAdd(&hi35xx->cntlr); // 挂载控制器 - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: add Pin cntlr: failed", __func__); - ret = HDF_FAILURE; - } - return HDF_SUCCESS; - } - ``` - - - Release函数 - - 入参: - - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 - - 返回值: - - 无。 - - 函数说明: - - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给 Release 接口。当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 - - ```c - static void Hi35xxPinRelease(struct HdfDeviceObject *device) - { - int32_t ret; - uint16_t number; - struct PinCntlr *cntlr = NULL; - struct Hi35xxPinCntlr *hi35xx = NULL; - struct DeviceResourceIface *drsOps = NULL; - - if (device == NULL || device->property == NULL) { - HDF_LOGE("%s: device or property is null", __func__); - return; - } - // 从hcs文件中读取管脚控制器编号 - drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); - if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetString == NULL) { - HDF_LOGE("%s: invalid drs ops", __func__); - return; - } - ret = drsOps->GetUint16(device->property, "number", &number, 0); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: read cntlr number failed", __func__); - return; - } - - cntlr = PinCntlrGetByNumber(number); // 通过管脚控制器编号获取管脚控制器 - PinCntlrRemove(cntlr); - hi35xx = (struct Hi35xxPinCntlr *)cntlr; - if (hi35xx != NULL) { - if (hi35xx->regBase != NULL) { - OsalIoUnmap((void *)hi35xx->regBase); - } - OsalMemFree(hi35xx); - } - } - ``` -4. 驱动调试: +### 开发实例 + +下方将基于Hi3516DV300开发板以//device_soc_hisilicon/common/platform/pin/pin_hi35xx.c驱动为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 + +1. 实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 + + PIN驱动入口开发参考: + + ```c + static struct HdfDriverEntry g_hi35xxPinDriverEntry = { + .moduleVersion = 1, + .Bind = Hi35xxPinBind, + .Init = Hi35xxPinInit, + .Release = Hi35xxPinRelease, + .moduleName = "hi35xx_pin_driver", // 【必要且与HCS文件中里面的moduleName匹配】 + }; + HDF_INIT(g_hi35xxPinDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + ``` + +2. 配置属性文件。 + + 完成驱动入口注册之后,需要在device_info.hcs文件中添加deviceNode信息,deviceNode信息与驱动入口注册相关。本例以两个PIN控制器为例,如有多个器件信息,则需要在device_info.hcs文件增加对应的deviceNode信息。器件属性值对于驱动适配者的驱动实现以及核心层PinCntlr相关成员的默认值或限制范围有密切关系,比如控制器号,控制器管脚数量、管脚等。需要在pin_config.hcs中配置器件属性。 + + - device_info.hcs 配置参考: + + 在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + + ```c + root { + device_info { + platform :: host { + hostName = "platform_host"; + priority = 50; + device_pin :: device { + device0 :: deviceNode { // 用于统一管理PIN并发布服务 + policy = 2; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 + priority = 8; // 启动优先级 + permission = 0644; // 创建设备节点权限 + moduleName = "HDF_PLATFORM_PIN_MANAGER"; + serviceName = "HDF_PLATFORM_PIN_MANAGER"; + } + device1 :: deviceNode { // 为每一个PIN控制器配置一个HDF设备节点,存在多个时必须添加,否则不用。 + policy = 0; + priority = 10; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "hi35xx_pin_driver"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + deviceMatchAttr = "hisilicon_hi35xx_pin_0"; // 【必要】用于配置控制器私有数据,要与pin_config.hcs中对应控制器保持一致,具体的控制器信息在pin_config.hcs中。 + } + device2 :: deviceNode { + policy = 0; + priority = 10; + permission = 0644; + moduleName = "hi35xx_pin_driver"; + deviceMatchAttr = "hisilicon_hi35xx_pin_1"; + } + ... + } + } + } + } + ``` + + - pin_config.hcs配置参考: + + 在//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pin/pin_config.hcs文件配置器件属性,其中配置参数如下: + + ```c + root { + platform { + pin_config_hi35xx { + template pin_controller { // 【必要】配置模板配,如果下面节点使用时继承该模板,则节点中未声明的字段会使用该模板中的默认值。 + number = 0; // 【必要】PIN控制器号 + regStartBasePhy = 0; // 【必要】寄存器物理基地址起始地址 + regSize = 0; // 【必要】寄存器位宽 + pinCount = 0; // 【必要】管脚数量 + match_attr = ""; + template pin_desc { + pinName = ""; // 【必要】管脚名称 + init = 0; // 【必要】寄存器默认值 + F0 = ""; // 【必要】功能0 + F1 = ""; // 功能1 + F2 = ""; // 功能2 + F3 = ""; // 功能3 + F4 = ""; // 功能4 + F5 = ""; // 功能5 + } + } + controller_0 :: pin_controller { + number = 0; + regStartBasePhy = 0x10FF0000; + regSize = 0x48; + pinCount = 18; + match_attr = "hisilicon_hi35xx_pin_0"; + T1 :: pin_desc { + pinName = "T1"; + init = 0x0600; + F0 = "EMMC_CLK"; + F1 = "SFC_CLK"; + F2 = "SFC_BOOT_MODE"; + } + ... // 对应管脚控制器下的每个管脚,按实际添加。 + } + ... // 每个管脚控制器对应一个控制器节点,如存在多个PIN控制器,请依次添加对应的控制器节点。 + } + } + } + ``` + + 需要注意的是,新增pin_config.hcs配置文件后,必须在产品对应的hdf.hcs文件中将其包含如下语句所示,否则配置文件无法生效。 + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pin/pin_config.hcs" // 配置文件相对路径 + ``` + +3. 实例化PIN控制器对象。 + + 完成配置属性文件之后,下一步就是以核心层PinCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化PinCntlr成员PinCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + + - 驱动适配者自定义结构体参考 + + 从驱动的角度看,自定义结构体是参数和数据的载体,而且pin_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 + + 在Hi35xxPinCntlrInit函数中对PinCntlr成员进行初始化操作。 + + ```c + // 驱动适配者自定义管脚描述结构体 + struct Hi35xxPinDesc { + const char *pinName; // 管脚名 + uint32_t init; // 初始化值 + uint32_t index; // 管脚索引 + int32_t pullType; // 管脚推拉方式 + int32_t strength; // 管脚推拉强度 + const char *func[HI35XX_PIN_FUNC_MAX]; // 管脚功能名字符串数组 + }; + + // 驱动适配者自定义结构体 + struct Hi35xxPinCntlr { + struct PinCntlr cntlr; // 是核心层控制对象,具体描述见下面 + struct Hi35xxPinDesc *desc; // 驱动适配者自定义管脚描述结构体指针 + volatile unsigned char *regBase; // 寄存器映射地址 + uint16_t number; // 管脚控制器编号 + uint32_t regStartBasePhy; // 寄存器物理基地址起始地址 + uint32_t regSize; // 寄存器位宽 + uint32_t pinCount; // 管脚数量 + }; + + // PinCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + struct PinCntlr { + struct IDeviceIoService service; // 驱动服务 + struct HdfDeviceObject *device; // 驱动设备对象 + struct PinCntlrMethod *method; // 钩子函数 + struct DListHead node; // 链表节点 + OsalSpinlock spin; // 自旋锁 + uint16_t number; // 管脚控制器编号 + uint16_t pinCount; // 管脚数量 + struct PinDesc *pins; // 管脚资源 + void *priv; // 私有数据 + }; + + // PIN管脚控制器初始化 + static int32_t Hi35xxPinCntlrInit(struct HdfDeviceObject *device, struct Hi35xxPinCntlr *hi35xx) + { + struct DeviceResourceIface *drsOps = NULL; + int32_t ret; + // 从hcs文件读取管脚控制器相关属性 + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetUint16 == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetUint16(device->property, "number", &hi35xx->number, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read number failed", __func__); + return ret; + } + + if (hi35xx->number > HI35XX_PIN_MAX_NUMBER) { + HDF_LOGE("%s: invalid number:%u", __func__, hi35xx->number); + return HDF_ERR_INVALID_PARAM; + } + ret = drsOps->GetUint32(device->property, "regStartBasePhy", &hi35xx->regStartBasePhy, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read regStartBasePhy failed", __func__); + return ret; + } + ret = drsOps->GetUint32(device->property, "regSize", &hi35xx->regSize, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read regSize failed", __func__); + return ret; + } + ret = drsOps->GetUint32(device->property, "pinCount", &hi35xx->pinCount, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read pinCount failed", __func__); + return ret; + } + if (hi35xx->pinCount > PIN_MAX_CNT_PER_CNTLR) { + HDF_LOGE("%s: invalid number:%u", __func__, hi35xx->number); + return HDF_ERR_INVALID_PARAM; + } + // 将读取的值赋值给管脚控制器的成员,完成管脚控制器初始化。 + hi35xx->cntlr.pinCount = hi35xx->pinCount; + hi35xx->cntlr.number = hi35xx->number; + hi35xx->regBase = OsalIoRemap(hi35xx->regStartBasePhy, hi35xx->regSize); // 管脚控制器映射 + if (hi35xx->regBase == NULL) { + HDF_LOGE("%s: remap Pin base failed", __func__); + return HDF_ERR_IO; + } + hi35xx->desc = (struct Hi35xxPinDesc *)OsalMemCalloc(sizeof(struct Hi35xxPinDesc) * hi35xx->pinCount); + if (hi35xx->desc == NULL) { + HDF_LOGE("%s: memcalloc hi35xx desc failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + hi35xx->cntlr.pins = (struct PinDesc *)OsalMemCalloc(sizeof(struct PinDesc) * hi35xx->pinCount); + if (hi35xx->desc == NULL) { + HDF_LOGE("%s: memcalloc hi35xx cntlr pins failed", __func__); + return HDF_ERR_MALLOC_FAIL; + } + return HDF_SUCCESS; + } + ``` + + - PinCntlr成员钩子函数结构体PinCntlrMethod的实例化,其他成员在Init函数中初始化。 + + ```c + static struct PinCntlrMethod g_method = { + .SetPinPull = Hi35xxPinSetPull, // 设置推拉方式 + .GetPinPull = Hi35xxPinGetPull, // 获取推拉方式 + .SetPinStrength = Hi35xxPinSetStrength, // 设置推拉强度 + .GetPinStrength = Hi35xxPinGetStrength, // 获取推拉强度 + .SetPinFunc = Hi35xxPinSetFunc, // 设置管脚功能 + .GetPinFunc = Hi35xxPinGetFunc, // 获取管脚功能 + }; + ``` + + - Init函数开发参考 + + 入参 + + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 + + 返回值: + + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + + | **状态(值)** | **问题描述** | + | ---------------------- | -------------- | + | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_INVALID_PARAM | 参数非法 | + | HDF_ERR_IO | I/O 错误 | + | HDF_SUCCESS | 初始化成功 | + | HDF_FAILURE | 初始化失败 | + + 函数说明: + + 初始化自定义结构体对象和PinCntlr成员,并通过调用核心层PinCntlrAdd函数挂载PIN控制器。 + + ```c + static int32_t Hi35xxPinReadFunc(struct Hi35xxPinDesc *desc, const struct DeviceResourceNode *node, struct DeviceResourceIface *drsOps) + { + int32_t ret; + uint32_t funcNum = 0; + // 从hcs中读取管脚控制器子节点管脚功能名 + ret = drsOps->GetString(node, "F0", &desc->func[funcNum], "NULL"); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read F0 failed", __func__); + return ret; + } + + funcNum++; + ret = drsOps->GetString(node, "F1", &desc->func[funcNum], "NULL"); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read F1 failed", __func__); + return ret; + } + + funcNum++; + ... + return HDF_SUCCESS; + } + + static int32_t Hi35xxPinParsePinNode(const struct DeviceResourceNode *node, struct Hi35xxPinCntlr *hi35xx, int32_t index) + { + int32_t ret; + struct DeviceResourceIface *drsOps = NULL; + // 从hcs中读取管脚控制器子节点管脚相关属性 + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetString == NULL) { + HDF_LOGE("%s: invalid drs ops fail!", __func__); + return HDF_FAILURE; + } + ret = drsOps->GetString(node, "pinName", &hi35xx->desc[index].pinName, "NULL"); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read pinName failed", __func__); + return ret; + } + ... + ret = Hi35xxPinReadFunc(&hi35xx->desc[index], node, drsOps); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:Pin read Func failed", __func__); + return ret; + } + hi35xx->cntlr.pins[index].pinName = hi35xx->desc[index].pinName; + hi35xx->cntlr.pins[index].priv = (void *)node; + ... + return HDF_SUCCESS; + } + + static int32_t Hi35xxPinInit(struct HdfDeviceObject *device) + { + ... + struct Hi35xxPinCntlr *hi35xx = NULL; + ... + ret = Hi35xxPinCntlrInit(device, hi35xx); // 管脚控制器初始化 + ... + DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { // 遍历管脚控制器的每个子节点 + ret = Hi35xxPinParsePinNode(childNode, hi35xx, index); // 解析子节点 + ... + } + + hi35xx->cntlr.method = &g_method; // PinCntlrMethod实例化实例化对象的挂载 + ret = PinCntlrAdd(&hi35xx->cntlr); // 添加控制器 + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: add Pin cntlr: failed", __func__); + ret = HDF_FAILURE; + } + return HDF_SUCCESS; + } + ``` + + - Release函数开发参考 + + 入参: + + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 + + 返回值: + + 无。 + + 函数说明: + + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口。当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + ```c + static void Hi35xxPinRelease(struct HdfDeviceObject *device) + { + int32_t ret; + uint16_t number; + struct PinCntlr *cntlr = NULL; + struct Hi35xxPinCntlr *hi35xx = NULL; + struct DeviceResourceIface *drsOps = NULL; + + if (device == NULL || device->property == NULL) { + HDF_LOGE("%s: device or property is null", __func__); + return; + } + // 从hcs文件中读取管脚控制器编号 + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + if (drsOps == NULL || drsOps->GetUint32 == NULL || drsOps->GetString == NULL) { + HDF_LOGE("%s: invalid drs ops", __func__); + return; + } + ret = drsOps->GetUint16(device->property, "number", &number, 0); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: read cntlr number failed", __func__); + return; + } + + cntlr = PinCntlrGetByNumber(number); // 通过管脚控制器编号获取管脚控制器 + PinCntlrRemove(cntlr); + hi35xx = (struct Hi35xxPinCntlr *)cntlr; + if (hi35xx != NULL) { + if (hi35xx->regBase != NULL) { + OsalIoUnmap((void *)hi35xx->regBase); + } + OsalMemFree(hi35xx); + } + } + ``` + +4. 驱动调试。 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-pwm-des.md b/zh-cn/device-dev/driver/driver-platform-pwm-des.md index be8c703fb3699c971fce77988d76f7dc42c10ff5..18dd7fd810d9762fecd60cd9783acbf6e48baca2 100644 --- a/zh-cn/device-dev/driver/driver-platform-pwm-des.md +++ b/zh-cn/device-dev/driver/driver-platform-pwm-des.md @@ -1,417 +1,408 @@ # PWM - ## 概述 -PWM是脉冲宽度调制(Pulse Width Modulation)的缩写,是一种对模拟信号电平进行数字编码并将其转换为脉冲的技术。常用于马达控制、背光亮度调节等。 +### 功能简介 + +PWM即脉冲宽度调制(Pulse Width Modulation)的缩写,是一种对模拟信号电平进行数字编码并将其转换为脉冲的技术。 PWM接口定义了操作PWM设备的通用方法集合,包括: -- PWM设备句柄获取和释放。 -- PWM周期、占空比、极性的设置。 +- PWM设备句柄获取和释放 +- PWM周期、占空比、极性的设置 +- PWM使能和关闭 +- PWM配置信息的获取和设置 -- PWM使能和关闭。 +### 基本概念 -- PWM配置信息的获取和设置。 +脉冲是“电脉冲”的简称,指电路中电流或电压短暂起伏的现象,其特点是突变和不连续性。脉冲的种类很多,常见的脉冲波形有:三角脉冲、尖脉冲、矩形脉冲、方形脉冲、梯形脉冲及阶梯脉冲等。脉冲的主要参数包括重复周期T(T=1/F,F为煎复频率)、脉冲幅度U、脉冲前沿上升时间ts、后沿下降时间t、脉冲宽度tk等。 +### 运作机制 -### PwmConfig结构体 +在HDF框架中,PWM接口适配模式采用独立服务模式(如图1所示)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 - **表1** PwmConfig结构体介绍 +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: -| 名称 | 描述 | -| -------- | -------- | -| duty | 占空时间,以纳秒为单位。 | -| period | PWM周期,以纳秒为单位。 | -| number | 要生成的方波数:
- 正值:表示将生成指定数量的方波
- 0:表示方波将不断产生 | -| polarity | 极性:正极性/反极性。 | -| status | 状态:启用状态/禁用状态。 | +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 +PWM模块各分层作用: -## 接口说明 +- 接口层提供打开PWM设备、设置PWM设备周期、设置PWM设备占空时间、设置PWM设备极性、设置PWM设备参数、获取PWM设备参数、使能PWM设备、禁止PWM设备、关闭PWM设备的接口。 +- 核心层主要提供PWM控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 - **表2** PWM驱动API接口功能介绍 +**图1** PWM独立服务模式结构图 -| 功能分类 | 接口描述 | -| -------- | -------- | -| PWM句柄操作 | - PwmOpen:获取PWM设备驱动句柄
- PwmClose:释放PWM设备驱动句柄 | -| 使能/禁用PWM | - PwmEnable:使能PWM
- PwmDisable:禁用PWM | -| PWM配置操作 | - PwmSetPeriod:设置PWM周期
- PwmSetDuty:设置PWM占空时间
- PwmSetPolarity:设置PWM极性 | -| 设置/获取PWM配置信息 | - PwmSetConfig:设置PWM设备参数
- PwmGetConfig:获取PWM设备参数 | +![image1](figures/独立服务模式结构图.png "PWM独立服务模式结构图") -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +## 使用指导 +### 场景介绍 -## 使用指导 +通常情况下,在使用马达控制、背光亮度调节时会用到PWM模块。 +### 接口说明 -### 使用流程 +PWM模块设备属性如表1所示,PWM模块提供的主要接口如表2所示。 -使用PWM的一般流程如下图所示。 +**表1** PwmConfig结构体介绍 - **图1** PWM使用流程图 +| 名称 | 描述 | +| -------- | -------- | +| duty | 占空时间,以纳秒为单位。 | +| period | PWM周期,以纳秒为单位。 | +| number | 要生成的方波数:
- 正值:表示将生成指定数量的方波
- 0:表示方波将不断产生 | +| polarity | 极性:正极性/反极性。 | +| status | 状态:启用状态/禁用状态。 | + +**表2** PWM驱动API接口功能介绍 + +| 接口名 | | +| ------------------------------------------------------------ | ------------------- | +| DevHandle PwmOpen(uint32_t num) | 打开PWM设备 | +| void PwmClose(DevHandle handle) | 关闭PWM设备 | +| int32_t PwmSetPeriod(DevHandle handle, uint32_t period) | 设置PWM设备周期 | +| int32_t PwmSetDuty(DevHandle handle, uint32_t duty) | 设置PWM设备占空时间 | +| int32_t PwmSetPolarity(DevHandle handle, uint8_t polarity) | 设置PWM设备极性 | +| int32_t PwmEnable(DevHandle handle) | 使能PWM设备 | +| int32_t PwmDisable(DevHandle handle) | 禁用PWM设备 | +| int32_t PwmSetConfig(DevHandle handle, struct PwmConfig *config) | 设置PWM设备参数 | +| int32_t PwmGetConfig(DevHandle handle, struct PwmConfig *config) | 获取PWM设备参数 | -![image](figures/PWM设备使用流程图.png "PWM设备使用流程图") +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+> 本文涉及PWM的所有接口,支持内核态及用户态使用。 +### 开发步骤 -### 获取PWM设备句柄 +使用PWM的一般流程如下图所示。 -在操作PWM设备时,首先要调用PwmOpen获取PWM设备句柄,该函数会返回指定设备号的PWM设备句柄。 +**图2** PWM使用流程图 +![image2](figures/PWM设备使用流程图.png "PWM设备使用流程图") -``` +#### 获取PWM设备句柄 + +在操作PWM设备时,首先要调用PwmOpen获取PWM设备句柄,该函数会返回指定设备号的PWM设备句柄。 + +```c DevHandle PwmOpen(uint32_t num); ``` - **表3** PwmOpen参数和返回值描述 +**表3** PwmOpen参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | -| num | PWM设备编号 | +| num | PWM设备号 | | **返回值** | **返回值描述** | -| handle | 获取成功,返回PWM设备句柄 | -| NULL | 获取失败 | +| handle | 打开PWM设备成功,返回PWM设备句柄 | +| NULL | 打开PWM设备失败 | 假设系统中的PWM设备号为0,获取该PWM设备句柄的示例如下: - -``` -uint32_t num = 0; /* PWM设备号 */ +```c +uint32_t num = 0; // PWM设备号 DevHandle handle = NULL; -/* 获取PWM设备句柄 */ -handle = PwmOpen(num); +handle = PwmOpen(num); // 打开PWM 0设备并获取PWM设备句柄 if (handle == NULL) { - /* 错误处理 */ + HDF_LOGE("PwmOpen: open pwm_%u failed.\n", num); + return; } ``` - -### 销毁PWM设备句柄 +#### 销毁PWM设备句柄 关闭PWM设备,系统释放对应的资源。 - -``` -voidPwmClose(DevHandle handle); +```c +void PwmClose(DevHandle handle); ``` - **表4** PwmClose参数描述 +**表4** PwmClose参数描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | - +```c +PwmClose(handle); // 关闭PWM设备销毁PWM设备句柄 ``` -/* 销毁PWM设备句柄 */ -PwmClose(handle); -``` - - -### 使能 - -启用PWM设备。 +#### 使能PWM设备 -``` +```c int32_t PwmEnable(DevHandle handle); ``` - **表5** PwmEnable参数和返回值描述 +**表5** PwmEnable参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | **返回值** | **返回值描述** | -| 0 | 使能成功 | +| HDF_SUCCESS | 使能成功 | | 负数 | 使能失败 | - -``` +```c int32_t ret; -/*启用PWM设备*/ -ret = PwmEnable(handle); -if (ret != 0) { - /*错误处理*/ +ret = PwmEnable(handle); // 启用PWM设备 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmEnable: enable pwm failed, ret:%d\n", ret); + return ret; } ``` +#### 禁用PWM设备 -### 禁用 - -禁用PWM设备。 - - -``` +```c int32_t PwmDisable(DevHandle handle); ``` - **表6** PwmDisable参数和返回值描述 +**表6** PwmDisable参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | **返回值** | **返回值描述** | -| 0 | 禁用成功 | +| HDF_SUCCESS | 禁用成功 | | 负数 | 禁用失败 | - -``` +```c int32_t ret; -/* 禁用PWM设备 */ -ret = PwmDisable(handle); -if (ret != 0) { - /* 错误处理 */ +ret = PwmDisable(handle); // 禁用PWM设备 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmDisable: disable pwm failed, ret:%d\n", ret); + return ret; } ``` +#### 设置PWM设备周期 -### 设置PWM设备周期 - -设置PWM设备周期。 - - -``` +```c int32_t PwmSetPeriod(DevHandle handle, uint32_t period); ``` - **表7** PwmSetPeriod参数和返回值描述 +**表7** PwmSetPeriod参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | period | 要设置的周期,单位为纳秒 | | **返回值** | **返回值描述** | -| 0 | 设置成功 | +| HDF_SUCCESS | 设置成功 | | 负数 | 设置失败 | - -``` +```c int32_t ret; -/* 设置周期为50000000纳秒 */ -ret = PwmSetPeriod(handle, 50000000); -if (ret != 0) { - /*错误处理*/ +ret = PwmSetPeriod(handle, 50000000); // 设置周期为50000000纳秒 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetPeriod: pwm set period failed, ret:%d\n", ret); + return ret; } ``` +#### 设置PWM设备占空时间 -### 设置设备占空时间 - -设置PWM设备占空时间。 - - -``` +```c int32_t PwmSetDuty(DevHandle handle, uint32_t duty); ``` - **表8** PwmSetDuty参数和返回值描述 +**表8** PwmSetDuty参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | duty | 要设置的占空时间,单位为纳秒 | | **返回值** | **返回值描述** | -| 0 | 设置成功 | +| HDF_SUCCESS | 设置成功 | | 负数 | 设置失败 | -``` +```c int32_t ret; -/* 设置占空时间为25000000纳秒 */ -ret = PwmSetDuty(handle, 25000000); -if (ret != 0) { - /* 错误处理 */ +ret = PwmSetDuty(handle, 25000000); // 设置占空时间为25000000纳秒 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetDuty: pwm set duty failed, ret:%d\n", ret); + return ret; } ``` +#### 设置PWM设备极性 -### 设置PWM设备极性 - -设置PWM设备极性。 - - -``` +```c int32_t PwmSetPolarity(DevHandle handle, uint8_t polarity); ``` - **表9** PwmSetPolarity参数和返回值描述 +**表9** PwmSetPolarity参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | polarity | 要设置的极性,正/反 | | **返回值** | **返回值描述** | -| 0 | 设置成功 | +| HDF_SUCCESS | 设置成功 | | 负数 | 设置失败 | -``` +```c int32_t ret; -/* 设置极性为反 */ -ret = PwmSetPolarity(handle, PWM_INVERTED_POLARITY); -if (ret != 0) { - /* 错误处理 */ +ret = PwmSetPolarity(handle, PWM_INVERTED_POLARITY); // 设置极性为反 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetPolarity: pwm set polarity failed, ret:%d\n", ret); + return ret; } ``` +#### 设置PWM设备参数 -### 设置PWM设备参数 - -设置PWM设备参数。 - - -``` +```c int32_t PwmSetConfig(DevHandle handle, struct PwmConfig *config); ``` - **表10** PwmSetConfig参数和返回值描述 +**表10** PwmSetConfig参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | \*config | 参数指针 | | **返回值** | **返回值描述** | -| 0 | 设置成功 | +| HDF_SUCCESS | 设置成功 | | 负数 | 设置失败 | - -``` +```c int32_t ret; struct PwmConfig pcfg; -pcfg.duty = 25000000; /* 占空时间为25000000纳秒 */ -pcfg.period = 50000000; /* 周期为50000000纳秒 */ -pcfg.number = 0; /* 不断产生方波 */ -pcfg.polarity = PWM_INVERTED_POLARITY; /* 极性为反 */ -pcfg.status = PWM_ENABLE_STATUS; /* 运行状态为启用 */ - -/* 设置PWM设备参数 */ -ret = PwmSetConfig(handle, &pcfg); -if (ret != 0) { - /* 错误处理 */ -} -``` - -### 获取PWM设备参数 +pcfg.duty = 25000000; // 占空时间为25000000纳秒 +pcfg.period = 50000000; // 周期为50000000纳秒 +pcfg.number = 0; // 不断产生方波 +pcfg.polarity = PWM_INVERTED_POLARITY; // 极性为反 +pcfg.status = PWM_ENABLE_STATUS; // 运行状态为启用 -获取PWM设备参数。 +ret = PwmSetConfig(handle, &pcfg); // 设置PWM设备参数 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetConfig: pwm set config failed, ret:%d\n", ret); + return ret; +} +``` +#### 获取PWM设备参数 -``` +```c int32_t PwmGetConfig(DevHandle handle, struct PwmConfig *config); ``` - **表11** PwmGetConfig参数和返回值描述 +**表11** PwmGetConfig参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | PWM设备句柄 | | \*config | 参数指针 | | **返回值** | **返回值描述** | -| 0 | 获取成功 | +| HDF_SUCCESS | 获取成功 | | 负数 | 获取失败 | - -``` +```c int32_t ret; struct PwmConfig pcfg; -/*获取PWM设备参数*/ -ret = PwmGetConfig(handle, &pcfg); -if (ret != 0) { - /*错误处理*/ +ret = PwmGetConfig(handle, &pcfg); // 获取PWM设备参数 +if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmGetConfig: pwm get config failed, ret:%d\n", ret); + return ret; } ``` - ## 使用实例 -PWM设备完整的使用示例如下所示,首先获取PWM设备句柄,然后设置设备周期、占空时间、极性,获取设备参数。使能,设置设备参数,禁用,最后销毁PWM设备句柄。 +下面将基于Hi3516DV300开发板展示使用PWM完整操作,步骤主要如下: +1. 传入PWM设备号,打开PWM设备并获得PWM设备句柄。 +2. 通过PWM设备句柄及待设置的周期,设置PWM设备周期。 +3. 通过PWM设备句柄及待设置的占空时间,设置PWM设备占空时间。 +4. 通过PWM设备句柄及待设置的极性,设置PWM设备极性。 +5. 通过PWM设备句柄及待获取的设备参数,获取PWM设备参数。 +6. 通过PWM设备句柄,使能PWM设备。 +7. 通过PWM设备句柄及待设置的设备参数,设置PWM设备参数。 +8. 通过PWM设备句柄,禁用PWM设备。 +9. 通过PWM设备句柄,关闭PWM设备。 -``` -void PwmTestSample(void) +```c +#include "pwm_if.h" // pwm标准接口头文件 +#include "hdf_log.h" // 标准日志打印头文件 + +static int32_t PwmTestSample(void) { int32_t ret; uint32_t num; + uint32_t period DevHandle handle = NULL; struct PwmConfig pcfg; - pcfg.duty = 20000000; /* 占空时间为20000000纳秒 */ - pcfg.period = 40000000; /* 周期为40000000纳秒 */ - pcfg.number = 100; /* 生成100个方波 */ - pcfg.polarity = PWM_NORMAL_POLARITY; /* 极性为正 */ - pcfg.status = PWM_ENABLE_STATUS; /* 运行状态为启用 */ + pcfg.duty = 20000000; // 占空时间为20000000纳秒 + pcfg.period = 40000000; // 周期为40000000纳秒 + pcfg.number = 100; // 生成100个方波 + pcfg.polarity = PWM_NORMAL_POLARITY; // 极性为正 + pcfg.status = PWM_ENABLE_STATUS; // 运行状态为启用 - /* PWM设备编号,要填写实际平台上的编号 */ - num = 1; + num = 1; // PWM设备编号,要填写实际平台上的编号 - /* 获取PWM设备句柄 */ - handle = PwmOpen(num); + handle = PwmOpen(num); // 获取PWM设备句柄 if (handle == NULL) { - HDF_LOGE("PwmOpen: failed!\n"); + HDF_LOGE("PwmOpen: open pwm_%u failed!\n", num); return; } - /* 设置周期为50000000纳秒 */ - ret = PwmSetPeriod(handle, 50000000); - if (ret != 0) { - HDF_LOGE("PwmSetPeriod: failed, ret %d\n", ret); - goto _ERR; + ret = PwmSetPeriod(handle, 50000000); // 设置周期为50000000纳秒 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetPeriod: pwm set period failed, ret %d\n", ret); + goto ERR; } - /* 设置占空时间为25000000纳秒 */ - ret = PwmSetDuty(handle, 25000000); - if (ret != 0) { - HDF_LOGE("PwmSetDuty: failed, ret %d\n", ret); - goto _ERR; + ret = PwmSetDuty(handle, 25000000); // 设置占空时间为25000000纳秒 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetDuty: pwm set duty failed, ret %d\n", ret); + goto ERR; } - /* 设置极性为反 */ - ret = PwmSetPolarity(handle, PWM_INVERTED_POLARITY); - if (ret != 0) { - HDF_LOGE("PwmSetPolarity: failed, ret %d\n", ret); - goto _ERR; + ret = PwmSetPolarity(handle, PWM_INVERTED_POLARITY); // 设置极性为反 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetPolarity: pwm set polarity failed, ret %d\n", ret); + goto ERR; } - /* 获取PWM设备参数 */ - ret = PwmGetConfig(handle, &pcfg); - if (ret != 0) { - HDF_LOGE("PwmGetConfig: failed, ret %d\n", ret); - goto _ERR; + ret = PwmGetConfig(handle, &pcfg); // 获取PWM设备参数 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmGetConfig: get pwm config failed, ret %d\n", ret); + goto ERR; } - /* 启用PWM设备 */ - ret = PwmEnable(handle); - if (ret != 0) { - HDF_LOGE("PwmEnable: failed, ret %d\n", ret); - goto _ERR; + ret = PwmEnable(handle); // 启用PWM设备 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmEnable: enable pwm failed, ret %d\n", ret); + goto ERR; } - /* 设置PWM设备参数 */ - ret = PwmSetConfig(handle, &pcfg); - if (ret != 0) { - HDF_LOGE("PwmSetConfig: failed, ret %d\n", ret); - goto _ERR; + ret = PwmSetConfig(handle, &pcfg); // 设置PWM设备参数 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmSetConfig: set pwm config failed, ret %d\n", ret); + goto ERR; } - /* 禁用PWM设备 */ - ret = PwmDisable(handle); - if (ret != 0) { - HDF_LOGE("PwmDisable: failed, ret %d\n", ret); - goto _ERR; + ret = PwmDisable(handle); // 禁用PWM设备 + if (ret != HDF_SUCCESS) { + HDF_LOGE("PwmDisable: disable pwm failed, ret %d\n", ret); + goto ERR; } -_ERR: - /* 销毁PWM设备句柄 */ - PwmClose(handle); +ERR: + PwmClose(handle); // 销毁PWM设备句柄 + return ret; } ``` diff --git a/zh-cn/device-dev/driver/driver-platform-pwm-develop.md b/zh-cn/device-dev/driver/driver-platform-pwm-develop.md index 2b83466cfae808ebc2d85c30ea96f920055f5baf..192c93865f7973df001e0f478bded02db9fbb949 100755 --- a/zh-cn/device-dev/driver/driver-platform-pwm-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-pwm-develop.md @@ -1,210 +1,226 @@ # PWM - ## 概述 -PWM(Pulse Width Modulator)即脉冲宽度调节器。在HDF框架中,PWM的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 - **图1** PWM独立服务模式结构图 +PWM(Pulse Width Modulation)即脉冲宽度调制,是一种对模拟信号电平进行数字编码并将其转换为脉冲的技术,广泛应用在从测量、通信到功率控制与变换的许多领域中。通常情况下,在使用马达控制、背光亮度调节时会用到PWM模块。 - ![image](figures/独立服务模式结构图.png "PWM独立服务模式结构图") +### 基本概念 +脉冲是“电脉冲”的简称,指电路中电流或电压短暂起伏的现象,其特点是突变和不连续性。脉冲的种类很多,常见的脉冲波形有:三角脉冲、尖脉冲、矩形脉冲、方形脉冲、梯形脉冲及阶梯脉冲等。脉冲的主要参数包括重复周期T(T=1/F,F为煎复频率)、脉冲幅度U、脉冲前沿上升时间ts、后沿下降时间t、脉冲宽度tk等。 -## 接口说明 +### 运作机制 -PwmMethod定义: +在HDF框架中,PWM接口适配模式采用独立服务模式(如图1所示)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 - -``` -struct PwmMethod { - int32_t (*setConfig)(struct PwmDev *pwm, struct PwmConfig *config); - int32_t (*open)(struct PwmDev *pwm); - int32_t (*close)(struct PwmDev *pwm); -}; -``` +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: - **表1** PwmMethod结构体成员的回调函数功能说明 +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 -| 成员函数 | 入参 | 返回值 | 功能 | -| -------- | -------- | -------- | -------- | -| setConfig | pwm:结构体指针,核心层PWM控制器
config:结构体指针,属性传入值 | HDF_STATUS相关状态 | 配置属性 | -| open | pwm:结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 打开设备 | -| close | pwm:结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 关闭设备 | +PWM模块各分层作用: +- 接口层提供打开PWM设备、设置PWM设备周期、设置PWM设备占空时间、设置PWM设备极性、设置PWM设备参数、获取PWM设备参数、使能PWM设备、禁止PWM设备、关闭PWM设备的接口。 +- 核心层主要提供PWM控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 -## 开发步骤 +**图1** PWM独立服务模式结构图 -PWM模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及填充核心层接口函数。 +![image](figures/独立服务模式结构图.png "PWM独立服务模式结构图") -1. 实例化驱动入口 - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 +## 开发指导 -2. 配置属性文件 - - 在device_info.hcs文件中添加deviceNode描述。 - - 【可选】添加pwm_config.hcs器件属性文件。 +### 场景介绍 -3. 实例化PWM控制器对象 - - 初始化PwmDev成员。 - - 实例化PwmDev成员PwmMethod。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
- > 实例化PwmDev成员PwmMethod,其定义和成员说明见[接口说明](#接口说明)。 +PWM用于脉冲宽度调制,当驱动开发者需要将PWM设备适配到OpenHarmony时,需要进行PWM驱动适配。下文将介绍如何进行PWM驱动适配。 -4. 驱动调试 +### 接口说明 - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如PWM控制状态,中断响应情况等。 +为了保证上层在调用PWM接口时能够正确的操作PWM控制器,核心层在//drivers/hdf_core/framework/support/platform/include/pwm/pwm_core.h中定义了以下钩子函数,驱动适配者需要在适配层实现这些函数的具体功能,并与钩子函数挂接,从而完成适配层与核心层的交互。 +PwmMethod定义: -## 开发实例 +```c +struct PwmMethod { + int32_t (*setConfig)(struct PwmDev *pwm, struct PwmConfig *config); + int32_t (*open)(struct PwmDev *pwm); + int32_t (*close)(struct PwmDev *pwm); +}; +``` -下方将以pwm_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +**表1** PwmMethod结构体成员的钩子函数功能说明 -1. 驱动开发首先需要实例化驱动入口。 +| 成员函数 | 入参 | 返回值 | 功能 | +| -------- | -------- | -------- | -------- | +| setConfig | pwm:结构体指针,核心层PWM控制器
config:结构体指针,传入设置得设备属性 | HDF_STATUS相关状态 | 配置属性 | +| open | pwm:结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 打开PWM设备 | +| close | pwm:结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 关闭PWM设备 | - 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 +### 开发步骤 - HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +PWM模块适配包含以下四个步骤: +- 驱实例化驱动入口。 +- 配置属性文件。 +- 实例化PWM控制器对象。 +- 驱动调试。 + +### 开发实例 + +下方将基于Hi3516DV300开发板以//device_soc_hisilicon/common/platform/pwm/pwm_hi35xx.c驱动为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 + +1. 驱实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - PWM驱动入口参考: - - ``` + PWM驱动入口开发参考: + + ```c struct HdfDriverEntry g_hdfPwm = { .moduleVersion = 1, - .moduleName = "HDF_PLATFORM_PWM",// 【必要且与HCS文件中里面的moduleName匹配】 - .Bind = HdfPwmBind, - .Init = HdfPwmInit, - .Release = HdfPwmRelease, + .moduleName = "HDF_PLATFORM_PWM", // 【必要且与HCS文件中里面的moduleName匹配】 + .Bind = HdfPwmBind, // 见Bind参考 + .Init = HdfPwmInit, // 见Init参考 + .Release = HdfPwmRelease, // 见Release参考 }; - // 调用HDF_INIT将驱动入口注册到HDF框架中 - HDF_INIT(g_hdfPwm); + HDF_INIT(g_hdfPwm); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在pwm_config.hcs中配置器件属性。 +2. 配置属性文件。 - deviceNode信息与驱动入口注册相关,器件属性值与核心层PwmDev成员的默认值或限制范围有密切关系。如有更多个器件信息,则需要在device_info文件增加deviceNode信息,以及在pwm_config文件中增加对应的器件属性。 + 完成驱动入口注册之后,需要在device_info.hcs文件中添加deviceNode信息,deviceNode信息与驱动入口注册相关。本例以两个PWM控制器为例,如有多个器件信息,则需要在device_info.hcs文件增加对应的deviceNode信息。器件属性值与核心层PwmDev成员的默认值或限制范围有密切关系,比如PWM设备号,需要在pwm_config.hcs文件中增加对应的器件属性。 - - device_info.hcs配置参考 + - device_info.hcs 配置参考: - - ``` + 在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + + ```c root { - device_info { - platform :: host { - hostName = "platform_host"; - priority = 50; - device_pwm :: device { // 为每一个pwm控制器配置一个HDF设备节点 - device0 :: deviceNode { - policy = 1; // 等于1,向内核态发布服务。 - priority = 80; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_PWM"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 - serviceName = "HDF_PLATFORM_PWM_0"; // 【必要且唯一】驱动对外发布服务的名称 - deviceMatchAttr = "hisilicon_hi35xx_pwm_0";// 【必要】用于配置控制器私有数据,要与pwm_config.hcs中对应 - // 控制器保持一致,具体的控制器信息在pwm_config.hcs中。 - } - device1 :: deviceNode { - policy = 1; - priority = 80; - permission = 0644; - moduleName = "HDF_PLATFORM_PWM"; - serviceName = "HDF_PLATFORM_PWM_1"; - deviceMatchAttr = "hisilicon_hi35xx_pwm_1"; + device_info { + platform :: host { + hostName = "platform_host"; + priority = 50; + device_pwm :: device { // 为每一个PWM控制器配置一个HDF设备节点 + device0 :: deviceNode { + policy = 1; // 等于1,向内核态发布服务 + priority = 80; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "HDF_PLATFORM_PWM"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致 + serviceName = "HDF_PLATFORM_PWM_0"; // 【必要且唯一】驱动对外发布服务的名称 + deviceMatchAttr = "hisilicon_hi35xx_pwm_0"; // 【必要】用于配置控制器私有数据,要与pwm_config.hcs中对应控制器保持一致,具体的控制器信息在pwm_config.hcs中 + } + device1 :: deviceNode { + policy = 1; + priority = 80; + permission = 0644; + moduleName = "HDF_PLATFORM_PWM"; + serviceName = "HDF_PLATFORM_PWM_1"; + deviceMatchAttr = "hisilicon_hi35xx_pwm_1"; + } + ... + } } - } } - } } ``` + - pwm_config.hcs 配置参考 - - ``` + 在//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pwm/pwm_config.hcs文件配置器件属性,其中配置参数如下: + + ```c root { - platform { - pwm_config { - template pwm_device { // 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 - serviceName = ""; - match_attr = ""; - num = 0; // 【必要】设备号 - base = 0x12070000; // 【必要】地址映射需要 - } - device_0x12070000 :: pwm_device { // 存在多个设备时,请逐一添加相关HDF节点和设备节点信息。 - match_attr = "hisilicon_hi35xx_pwm_0";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - } - device_0x12070020 :: pwm_device { - match_attr = "hisilicon_hi35xx_pwm_1"; - num = 1; - base = 0x12070020; // 【必要】地址映射需要 - } + platform { + pwm_config { + template pwm_device { // 【必要】配置模板,如果下面节点使用时继承该模板,则节点中未声明的字段会使用该模板中的默认值 + serviceName = ""; + match_attr = ""; + num = 0; // 【必要】设备号 + base = 0x12070000; // 【必要】地址映射需要 + } + device_0x12070000 :: pwm_device { // 存在多个设备时,请逐一添加相关HDF节点和设备节点信息。 + match_attr = "hisilicon_hi35xx_pwm_0"; // 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + } + device_0x12070020 :: pwm_device { + match_attr = "hisilicon_hi35xx_pwm_1"; + num = 1; + base = 0x12070020; // 【必要】地址映射需要 + } + } } - } } ``` -3. 完成驱动入口注册之后,下一步就是以核心层PwmDev对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化PwmDev成员PwmMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + 需要注意的是,新增pwm_config.hcs配置文件后,必须在产品对应的hdf.hcs文件中将其包含如下语句所示,否则配置文件无法生效。 - - 自定义结构体参考。 + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pwm/pwm_config.hcs" // 配置文件相对路径 + ``` - 从驱动的角度看,自定义结构体是参数和数据的载体,而且pwm_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号等。 +3. 实例化PWM控制器对象。 - - ``` + 完成驱动入口注册之后,下一步就是以核心层PwmDev对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化PwmDev成员PwmMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + + - 驱动适配者自定义结构体参考。 + + 从驱动的角度看,驱动适配者自定义结构体是参数和数据的载体,而且pwm_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如PWM设备号。 + + ```c struct HiPwm { - struct PwmDev dev; // 【必要】 核心层结构体 - volatile unsigned char *base; - struct HiPwmRegs *reg; // 设备属性结构体,可自定义。 - bool supportPolarity; + struct PwmDev dev; // 【必要】 核是核心层控制对象 + volatile unsigned char *base; // 【必要】地址映射需要,寄存器基地址 + struct HiPwmRegs *reg; // 设备属性结构体,可自定义。 + bool supportPolarity; // 是否支持极性 }; - - // PwmDev是核心层控制器结构体,其中的成员在Init函数中会被赋值。 - struct PwmDev { - struct IDeviceIoService service; - struct HdfDeviceObject *device; - struct PwmConfig cfg; // 属性结构体,相关定义见下。 - struct PwmMethod *method; // 钩子函数模板 - bool busy; - uint32_t num; // 设备号 - OsalSpinlock lock; - void *priv; // 私有数据,一般存储自定义结构体首地址,方便调用。 + + struct PwmDev { // PwmDev是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + struct IDeviceIoService service; // 驱动服务 + struct HdfDeviceObject *device; // 驱动设备对象 + struct PwmConfig cfg; // 设备属性结构体,相关定义见下。 + struct PwmMethod *method; // 钩子函数 + bool busy; // 是否繁忙 + uint32_t num; // 设备号 + OsalSpinlock lock; // 自旋锁 + void *priv; // 私有数据 }; - struct PwmConfig { - uint32_t duty; // 占空时间 nanoseconds - uint32_t period; // pwm 周期 nanoseconds - uint32_t number; // pwm 连续个数 - uint8_t polarity; // Polarity - // ------------------- | -------------- - // PWM_NORMAL_POLARITY | Normal polarity - // PWM_INVERTED_POLARITY | Inverted polarity - // - uint8_t status; // 运行状态 - // ------------------ | ----------------- - // PWM_DISABLE_STATUS | Disabled - // PWM_ENABLE_STATUS | Enabled + + struct PwmConfig { // PWM设备属性 + uint32_t duty; // 占空时间 nanoseconds + uint32_t period; // pwm 周期 nanoseconds + uint32_t number; // pwm 连续个数 + uint8_t polarity; // Polarity + // ------------------- | -------------- + // PWM_NORMAL_POLARITY | Normal polarity + // PWM_INVERTED_POLARITY | Inverted polarity + // + uint8_t status; // 运行状态 + // ------------------ | ----------------- + // PWM_DISABLE_STATUS | Disabled + // PWM_ENABLE_STATUS | Enabled }; ``` - - PwmDev成员回调函数结构体PwmMethod的实例化,其他成员在Init函数中初始化。 - - - ``` - // pwm_hi35xx.c中的示例:钩子函数的填充 - struct PwmMethod g_pwmOps = { - .setConfig = HiPwmSetConfig,// 配置属性 + - PwmDev成员钩子函数结构体PwmMethod的实例化,其他成员在Init函数中初始化。 + + ```c + struct PwmMethod g_pwmOps = { // pwm_hi35xx.c中的示例:钩子函数实例化 + .setConfig = HiPwmSetConfig, // 配置属性 }; ``` - - Init函数参考 + + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 - | 状态(值) | 问题描述 | + | 状态(值) | 问题描述 | | -------- | -------- | | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | | HDF_ERR_MALLOC_FAIL | 内存分配失败 | @@ -215,58 +231,58 @@ PWM模块适配HDF框架的三个必选环节是实例化驱动入口,配置 函数说明: - 初始化自定义结构体对象,初始化PwmDev成员,调用核心层PwmDeviceAdd函数。 + 初始化自定义结构体对象,初始化PwmDev成员,调用核心层PwmDeviceAdd函数,完成PWM控制器的添加。 - - ``` - // 此处Bind函数为空函数,可与Init函数结合,也可根据厂商需要实现相关操作。 + ```c + // 此处Bind函数为空函数,可与Init函数结合,也可根据驱动适配者需要实现相关操作。 static int32_t HdfPwmBind(struct HdfDeviceObject *obj) { - (void)obj; - return HDF_SUCCESS; + (void)obj; + return HDF_SUCCESS; } - + static int32_t HdfPwmInit(struct HdfDeviceObject *obj) { - int ret; - struct HiPwm *hp = NULL; - ... - hp = (struct HiPwm *)OsalMemCalloc(sizeof(*hp)); - ... - ret = HiPwmProbe(hp, obj); // 【必要】实现见下 - ... - return ret; + int ret; + struct HiPwm *hp = NULL; + ... + hp = (struct HiPwm *)OsalMemCalloc(sizeof(*hp)); + ... + ret = HiPwmProbe(hp, obj); // 【必要】实现见下 + ... + return ret; } - + static int32_t HiPwmProbe(struct HiPwm *hp, struct HdfDeviceObject *obj) { uint32_t tmp; struct DeviceResourceIface *iface = NULL; - iface = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE);//初始化自定义结构体HiPwm + iface = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); //初始化自定义结构体HiPwm ... - hp->reg = (struct HiPwmRegs *)hp->base; // 初始化自定义结构体HiPwm - hp->supportPolarity = false; // 初始化自定义结构体HiPwm - hp->dev.method = &g_pwmOps; // PwmMethod的实例化对象的挂载 - hp->dev.cfg.duty = PWM_DEFAULT_DUTY_CYCLE; // 初始化PwmDev - hp->dev.cfg.period = PWM_DEFAULT_PERIOD; // 初始化PwmDev - hp->dev.cfg.polarity = PWM_DEFAULT_POLARITY; // 初始化PwmDev - hp->dev.cfg.status = PWM_DISABLE_STATUS; // 初始化PwmDev - hp->dev.cfg.number = 0; // 初始化PwmDev - hp->dev.busy = false; // 初始化PwmDev - if (PwmDeviceAdd(obj, &(hp->dev)) != HDF_SUCCESS) { // 【重要】调用核心层函数,初始化hp->dev的设备和服务。 + hp->reg = (struct HiPwmRegs *)hp->base; // 初始化自定义结构体HiPwm + hp->supportPolarity = false; // 初始化自定义结构体HiPwm + hp->dev.method = &g_pwmOps; // PwmMethod的实例化对象的挂载 + hp->dev.cfg.duty = PWM_DEFAULT_DUTY_CYCLE; // 初始化PwmDev + hp->dev.cfg.period = PWM_DEFAULT_PERIOD; // 初始化PwmDev + hp->dev.cfg.polarity = PWM_DEFAULT_POLARITY; // 初始化PwmDev + hp->dev.cfg.status = PWM_DISABLE_STATUS; // 初始化PwmDev + hp->dev.cfg.number = 0; // 初始化PwmDev + hp->dev.busy = false; // 初始化PwmDev + if (PwmDeviceAdd(obj, &(hp->dev)) != HDF_SUCCESS) { // 【重要】调用核心层函数,初始化hp->dev的设备和服务。 OsalIoUnmap((void *)hp->base); return HDF_FAILURE; } return HDF_SUCCESS; } ``` - - Release函数参考 + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: @@ -276,15 +292,18 @@ PWM模块适配HDF框架的三个必选环节是实例化驱动入口,配置 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 - - ``` + ```c static void HdfPwmRelease(struct HdfDeviceObject *obj) { struct HiPwm *hp = NULL; ... - hp = (struct HiPwm *)obj->service;// 这里有HdfDeviceObject到HiPwm的强制转化 - ... - PwmDeviceRemove(obj, &(hp->dev)); // 【必要】调用核心层函数,释放PwmDev的设备和服务,这里有HiPwm到PwmDev的强制转化。 - HiPwmRemove(hp); // 释放HiPwm + hp = (struct HiPwm *)obj->service; // 这里有HdfDeviceObject到HiPwm的强制转化 + ... + PwmDeviceRemove(obj, &(hp->dev)); // 【必要】调用核心层函数,释放PwmDev的设备和服务,这里有HiPwm到PwmDev的强制转化。 + HiPwmRemove(hp); // 释放HiPwm } ``` + +4. 驱动调试。 + + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如PWM控制状态,中断响应情况等。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-regulator-des.md b/zh-cn/device-dev/driver/driver-platform-regulator-des.md index ad0aba61272767671e3b9b74022972a521beb6cb..058114fcbb760cfa5ea74bd4d4610893a46dc147 100755 --- a/zh-cn/device-dev/driver/driver-platform-regulator-des.md +++ b/zh-cn/device-dev/driver/driver-platform-regulator-des.md @@ -30,22 +30,23 @@ Regulator接口定义了操作Regulator设备的通用方法集合,包括: 电源管理芯片,内含多个电源甚至其他子系统。 - ### 运作机制 -在HDF框架中,Regulator模块接口适配模式采用统一服务模式,这需要一个设备服务来作为Regulator模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如Regulator可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 +在HDF框架中,Regulator模块接口适配模式采用统一服务模式(如图1),这需要一个设备服务来作为Regulator模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如Regulator可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问,实现便捷管理和节约资源的目的。 -Regulator模块各分层的作用为:接口层提供打开设备,写入数据,关闭设备接口的能力。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其他具体的功能。 +Regulator模块各分层的作用为: -![](../public_sys-resources/icon-note.gif) 说明:
核心层可以调用接口层的函数,也可以通过钩子函数调用适配层函数,从而使得适配层间接的可以调用接口层函数,但是不可逆转接口层调用适配层函数。 +- 接口层:提供打开设备,操作Regulator,关闭设备的能力。 +- 核心层:主要负责服务绑定、初始化以及释放管理器,并提供添加、删除以及获取Regulator设备的能力。 +- 适配层:由驱动适配者实现与硬件相关的具体功能,如设备的初始化等。 -**图 1** 统一服务模式结构图 +**图 1** Regulator统一服务模式结构图 ![image1](figures/统一服务模式结构图.png) ### 约束与限制 -Regulator模块当前仅支持轻量和小型系统内核(LiteOS)。 +Regulator模块API当前仅支持内核态调用。 ## 使用指导 @@ -58,27 +59,25 @@ Regulator主要用于: ### 接口说明 +Regulator模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/regulator_if.h。 + **表1** Regulator设备API接口说明 -| 接口名 | 描述 | +| 接口名 | 接口描述 | | --------------------- | ------------------------- | -| RegulatorOpen | 获取Regulator设备驱动句柄 | -| RegulatorClose | 销毁Regulator设备驱动句柄 | -| RegulatorEnable | 使能Regulator | -| RegulatorDisable | 禁用Regulator | -| RegulatorForceDisable | 强制禁用Regulator | -| RegulatorSetVoltage | 设置Regulator输出电压 | -| RegulatorGetVoltage | 获取Regulator输出电压 | -| RegulatorSetCurrent | 设置Regulator输出电流 | -| RegulatorGetCurrent | 获取Regulator输出电流 | -| RegulatorGetStatus | 获取Regulator状态 | - - +| DevHandle RegulatorOpen(const char \*name) | 获取Regulator设备驱动句柄 | +| void RegulatorClose(DevHandle handle) | 销毁Regulator设备驱动句柄 | +| int32_t RegulatorEnable(DevHandle handle) | 使能Regulator | +| int32_t RegulatorDisable(DevHandle handle) | 禁用Regulator | +| int32_t RegulatorForceDisable(DevHandle handle) | 强制禁用Regulator | +| int32_t RegulatorSetVoltage(DevHandle handle, uint32_t minUv, uint32_t maxUv) | 设置Regulator输出电压 | +| int32_t RegulatorGetVoltage(DevHandle handle, uint32_t \*voltage) | 获取Regulator输出电压 | +| int32_t RegulatorSetCurrent(DevHandle handle, uint32_t minUa, uint32_t maxUa) | 设置Regulator输出电流 | +| int32_t RegulatorGetCurrent(DevHandle handle, uint32_t \*regCurrent) | 获取Regulator输出电流 | +| int32_t RegulatorGetStatus(DevHandle handle, uint32_t \*status) | 获取Regulator状态 | ### 开发步骤 -在操作系统启动过程中,驱动管理模块根据配置文件加载Regulator驱动,Regulator驱动会检测Regulator器件并初始化驱动。 - 使用Regulator设备的一般流程如图2所示。 **图 2** Regulator设备使用流程图 @@ -89,7 +88,7 @@ Regulator主要用于: 在操作Regulator设备时,首先要调用RegulatorOpen获取Regulator设备句柄,该函数会返回指定设备名称的Regulator设备句柄。 -``` +```c DevHandle RegulatorOpen(const char *name); ``` @@ -104,7 +103,7 @@ DevHandle RegulatorOpen(const char *name); -``` +```c /* Regulator设备名称 */ const char *name = "regulator_virtual_1"; DevHandle handle = NULL; @@ -120,7 +119,7 @@ if (handle == NULL) { 关闭Regulator设备,系统释放对应的资源。 -``` +```c void RegulatorClose(DevHandle handle); ``` @@ -130,7 +129,7 @@ void RegulatorClose(DevHandle handle); | ------ | ----------------- | | handle | Regulator设备句柄 | -``` +```c /* 销毁Regulator设备句柄 */ RegulatorClose(handle); ``` @@ -139,7 +138,7 @@ RegulatorClose(handle); 启用Regulator设备。 -``` +```c int32_t RegulatorEnable(DevHandle handle); ``` @@ -154,7 +153,7 @@ int32_t RegulatorEnable(DevHandle handle); -``` +```c int32_t ret; /* 启用Regulator设备 */ @@ -168,7 +167,7 @@ if (ret != 0) { 禁用Regulator设备。如果Regulator设备状态为常开,或存在Regulator设备子节点未禁用,则禁用失败。 -``` +```c int32_t RegulatorDisable(DevHandle handle); ``` @@ -181,7 +180,7 @@ int32_t RegulatorDisable(DevHandle handle); | 0 | 禁用成功 | | 负数 | 禁用失败 | -``` +```c int32_t ret; /* 禁用Regulator设备 */ @@ -195,7 +194,7 @@ if (ret != 0) { 强制禁用Regulator设备。无论Regulator设备的状态是常开还是子节点已使能,Regulator设备都会被禁用。 -``` +```c int32_t RegulatorForceDisable(DevHandle handle); ``` @@ -209,7 +208,7 @@ int32_t RegulatorForceDisable(DevHandle handle); | 0 | 禁用成功 | | 负数 | 禁用失败 | -``` +```c int32_t ret; /* 强制禁用Regulator设备 */ @@ -221,9 +220,7 @@ if (ret != 0) { #### 设置Regulator输出电压范围 -设置Regulator电压输出电压范围。 - -``` +```c int32_t RegulatorSetVoltage(DevHandle handle, uint32_t minUv, uint32_t maxUv); ``` @@ -238,7 +235,7 @@ int32_t RegulatorSetVoltage(DevHandle handle, uint32_t minUv, uint32_t maxUv); | 0 | 设置成功 | | 负数 | 设置失败 | -``` +```c int32_t ret; int32_t minUv = 0; // 最小电压为0µV int32_t maxUv = 20000; // 最大电压为20000µV @@ -252,9 +249,7 @@ if (ret != 0) { #### 获取Regulator电压 -获取Regulator电压。 - -``` +```c int32_t RegulatorGetVoltage(DevHandle handle, uint32_t *voltage); ``` @@ -269,7 +264,7 @@ int32_t RegulatorGetVoltage(DevHandle handle, uint32_t *voltage); | 0 | 获取成功 | | 负数 | 获取失败 | -``` +```c int32_t ret; uint32_t voltage; @@ -282,9 +277,7 @@ if (ret != 0) { #### 设置Regulator输出电流范围 -设置Regulator输出电流范围。 - -``` +```c int32_t RegulatorSetCurrent(DevHandle handle, uint32_t minUa, uint32_t maxUa); ``` @@ -299,9 +292,9 @@ int32_t RegulatorSetCurrent(DevHandle handle, uint32_t minUa, uint32_t maxUa); | 0
| 设置成功 | | 负数 | 设置失败 | -``` +```c int32_t ret; -int32_t minUa = 0; // 最小电流为0μA +int32_t minUa = 0; // 最小电流为0μA int32_t maxUa = 200; // 最大电流为200μA /* 设置Regulator输出电流范围 */ @@ -313,9 +306,7 @@ if (ret != 0) { #### 获取Regulator电流 -获取Regulator电流。 - -``` +```c int32_t RegulatorGetCurrent(DevHandle handle, uint32_t *regCurrent); ``` @@ -329,7 +320,7 @@ int32_t RegulatorGetCurrent(DevHandle handle, uint32_t *regCurrent); | 0 | 获取成功 | | 负数 | 获取失败 | -``` +```c int32_t ret; uint32_t regCurrent; @@ -342,9 +333,7 @@ if (ret != 0) { #### 获取Regulator状态 -获取Regulator状态。 - -``` +```c int32_t RegulatorGetStatus(DevHandle handle, uint32_t *status); ``` @@ -358,7 +347,7 @@ int32_t RegulatorGetStatus(DevHandle handle, uint32_t *status); | 0 | 获取成功 | | 负数 | 获取失败 | -``` +```c int32_t ret; uint32_t status; @@ -373,9 +362,11 @@ if (ret != 0) { ## 使用实例 +本例拟对Hi3516DV300开发板上Regulator设备进行简单的读取操作。 + Regulator设备完整的使用示例如下所示,首先获取Regulator设备句柄,然后使能,设置电压,获取电压、状态,禁用,最后销毁Regulator设备句柄。 -``` +```c void RegulatorTestSample(void) { int32_t ret; diff --git a/zh-cn/device-dev/driver/driver-platform-regulator-develop.md b/zh-cn/device-dev/driver/driver-platform-regulator-develop.md index b72c9c13199b7ac7b9a5067936366316c0e0785d..4db05339c9ca1561690cca164f41cb788c862e7c 100755 --- a/zh-cn/device-dev/driver/driver-platform-regulator-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-regulator-develop.md @@ -5,42 +5,41 @@ ### 功能简介 -Regulator模块用于控制系统中某些设备的电压/电流供应。在嵌入式系统(尤其是手机)中,控制耗电量很重要,直接影响到电池的续航时间。所以,如果系统中某一个模块暂时不需要使用,就可以通过Regulator关闭其电源供应;或者降低提供给该模块的电压、电流大小。 +Regulator模块用于控制系统中各类设备的电压/电流供应。在嵌入式系统(尤其是手机)中,控制耗电量很重要,直接影响到电池的续航时间。所以,如果系统中某一个模块暂时不需要使用,就可以通过Regulator关闭其电源供应;或者降低提供给该模块的电压、电流大小。 ### 运作机制 -在HDF框架中,Regulator模块接口适配模式采用统一服务模式,这需要一个设备服务来作为Regulator模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如Regulator可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 +在HDF框架中,Regulator模块接口适配模式采用统一服务模式(如图1),这需要一个设备服务来作为Regulator模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如Regulator可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 Regulator模块各分层的作用为: -- 接口层提供打开设备,写入数据,关闭设备接口的能力。 -- 核心层主要提供绑定设备、初始化设备以及释放设备的能力。 -- 适配层实现其他具体的功能。 -![](../public_sys-resources/icon-note.gif) 说明:
核心层可以调用接口层的函数,也可以通过钩子函数调用适配层函数,从而使得适配层间接的可以调用接口层函数,但是不可逆转接口层调用适配层函数。 +- 接口层:提供打开设备,操作Regulator,关闭设备的能力。 +- 核心层:主要负责服务绑定、初始化以及释放管理器,并提供添加、删除以及获取Regulator设备的能力。 +- 适配层:由驱动适配者实现与硬件相关的具体功能,如设备的初始化等。 -**图 1** 统一服务模式结构图 - -![image1](figures/统一服务模式结构图.png) +在统一模式下,所有的控制器都被核心层统一管理,并由核心层统一发布一个服务供接口层,因此这种模式下驱动无需再为每个控制器发布服务。 +**图 1** 统一服务模式结构图 +![image1](figures/统一服务模式结构图.png) ### 约束与限制 -Regulator模块当前仅支持轻量和小型系统内核(LiteOS)。 +Regulator模块当前仅支持小型系统。 ## 开发指导 ### 场景介绍 -Regulator模块用于控制系统中某些设备的电压/电流供应。 +Regulator模块用于控制系统中某些设备的电压/电流供应。当驱动开发者需要将Regulator设备适配到OpenHarmony时,需要进行Regulator驱动适配,下文将介绍如何进行Regulator驱动适配。 ### 接口说明 -通过以下RegulatorMethod中的函数调用Regulator驱动对应的函数。 +为了保证上层在调用Regulator接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/regulator/regulator_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 RegulatorMethod定义: -``` +```c struct RegulatorMethod { int32_t (*open)(struct RegulatorNode *node); int32_t (*close)(struct RegulatorNode *node); @@ -56,8 +55,7 @@ struct RegulatorMethod { }; ``` -**表 1** RegulatorMethod 结构体成员的回调函数功能说明 - +**表 1** RegulatorMethod 结构体成员的钩子函数功能说明 | 成员函数 | 入参 | 返回值 | 功能 | | ------------ | ----------------------------------------------------------- | ----------------- | ---------------- | @@ -87,23 +85,23 @@ Regulator模块适配包含以下四个步骤: 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 HDF框架会汇总所有加载的驱动的HdfDriverEntry对象入口,形成一个类似数组的段地址空间,方便上层调用。 - + 一般在加载驱动时HDF会先调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - - ``` + + ```c struct HdfDriverEntry g_regulatorDriverEntry = { .moduleVersion = 1, - .moduleName = "virtual_regulator_driver",// 【必要且与HCS文件中里面的moduleName匹配】 + .moduleName = "virtual_regulator_driver", // 【必要且与HCS文件中里面的moduleName匹配】 .Init = VirtualRegulatorInit, .Release = VirtualRegulatorRelease, }; - // 调用HDF_INIT将驱动入口注册到HDF框架中 + /* 调用HDF_INIT将驱动入口注册到HDF框架中 */ HDF_INIT(g_regulatorDriverEntry); ``` - + 2. 配置属性文件: - - 在vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + 以Hi3516DV300开发板为例,在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 deviceNode信息与驱动入口注册相关,器件属性值与核心层RegulatorNode成员的默认值或限制范围有密切关系。 @@ -118,43 +116,43 @@ Regulator模块适配包含以下四个步骤: | serviceName | 固定为HDF_PLATFORM_REGULATOR_MANAGER | | deviceMatchAttr | 没有使用,可忽略 | - 从第二个节点开始配置具体Regulator控制器信息,此节点并不表示某一路Regulator控制器,而是代表一个资源性质设备,用于描述一类Regulator控制器的信息。本例只有一个Regulator设备,如有多个设备,则需要在device_info文件增加deviceNode信息,以及在regulator\_config文件中增加对应的器件属性。 + 从第二个节点开始配置具体Regulator控制器信息,此节点并不表示某一路Regulator控制器,而是代表一个资源性质设备,用于描述一类Regulator控制器的信息。本例只有一个Regulator设备,如有多个设备,则需要在device_info.hcs文件增加deviceNode信息,以及在regulator\_config文件中增加对应的器件属性。 - device_info.hcs 配置参考 - ``` + ```c root { - device_info { - platform :: host { - hostName = "platform_host"; - priority = 50; - device_regulator :: device { - device0 :: deviceNode { // 为每一个Regulator控制器配置一个HDF设备节点,存在多个时添加,否则不用。 - policy = 1; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 - priority = 50; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 */ - moduleName = "HDF_PLATFORM_REGULATOR_MANAGER"; - serviceName = "HDF_PLATFORM_REGULATOR_MANAGER"; //【必要且唯一】驱动对外发布服务的名称 - /* 【必要】用于配置控制器私有数据,要与regulator_config.hcs中对应控制器保持一致,具体的控制器信息在regulator_config.hcs中。 */ - deviceMatchAttr = "hdf_platform_regulator_manager"; - } - device1 :: deviceNode { - policy = 0; - priority = 55; - permission = 0644; - moduleName = "linux_regulator_adapter"; - deviceMatchAttr = "linux_regulator_adapter"; + device_info { + platform :: host { + hostName = "platform_host"; + priority = 50; + device_regulator :: device { + device0 :: deviceNode { // 为每一个Regulator控制器配置一个HDF设备节点,存在多个时添加,否则不用。 + policy = 1; // 2:用户态、内核态均可见;1:内核态可见;0:不需要发布服务。 + priority = 50; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 */ + moduleName = "HDF_PLATFORM_REGULATOR_MANAGER"; + serviceName = "HDF_PLATFORM_REGULATOR_MANAGER"; // 【必要且唯一】驱动对外发布服务的名称 + /* 【必要】用于配置控制器私有数据,要与regulator_config.hcs中对应控制器保持一致,具体的控制器信息在regulator_config.hcs中。 */ + deviceMatchAttr = "hdf_platform_regulator_manager"; + } + device1 :: deviceNode { + policy = 0; + priority = 55; + permission = 0644; + moduleName = "linux_regulator_adapter"; + deviceMatchAttr = "linux_regulator_adapter"; + } + } } } - } - } } ``` - regulator\_config.hcs配置参考 - ``` + ```c root { platform { regulator_config { @@ -198,16 +196,24 @@ Regulator模块适配包含以下四个步骤: } ``` + 需要注意的是,新增regulator_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中regulator_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/regulator/regulator_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/regulator/regulator_config.hcs" // 配置文件相对路径 + ``` + 3. 实例化核心层接口函数: - - 完成驱动入口注册之后,下一步就是对核心层RegulatorNode对象的初始化,包括厂商自定义结构体(传递参数和数据),实例化RegulatorNode成员RegulatorMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + 完成驱动入口注册之后,下一步就是对核心层RegulatorNode对象的初始化,包括驱动适配者自定义结构体(传递参数和数据),实例化RegulatorNode成员RegulatorMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - 自定义结构体参考。 从驱动的角度看,RegulatorNode结构体是参数和数据的载体,HDF框架通过DeviceResourceIface将regulator\_config.hcs文件中的数值读入其中。 - ``` - // RegulatorNode是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + ```c + /* RegulatorNode是核心层控制器结构体,其中的成员在Init函数中会被赋值。 */ struct RegulatorNode { struct RegulatorDesc regulatorInfo; struct DListHead node; @@ -217,35 +223,33 @@ Regulator模块适配包含以下四个步骤: }; struct RegulatorDesc { - const char *name; /* regulator名称 */ - const char *parentName; /* regulator父节点名称 */ - struct RegulatorConstraints constraints; /* regulator约束信息 */ - uint32_t minUv; /* 最小输出电压值 */ - uint32_t maxUv; /* 最大输出电压值 */ - uint32_t minUa; /* 最小输出电流值 */ - uint32_t maxUa; /* 最大输出电流值 */ - uint32_t status; /* regulator的状态,开或关。*/ + const char *name; // regulator名称 + const char *parentName; // regulator父节点名称 + struct RegulatorConstraints constraints; // regulator约束信息 + uint32_t minUv; // 最小输出电压值 + uint32_t maxUv; // 最大输出电压值 + uint32_t minUa; // 最小输出电流值 + uint32_t maxUa; // 最大输出电流值 + uint32_t status; // regulator的状态,开或关。 int useCount; - int consumerRegNums; /* regulator用户数量 */ - RegulatorStatusChangecb cb; /* 当regulator状态改变时,可通过此变量通知。*/ + int consumerRegNums; // regulator用户数量 + RegulatorStatusChangecb cb; // 当regulator状态改变时,可通过此变量通知。 }; struct RegulatorConstraints { - uint8_t alwaysOn; /* regulator是否常开 */ - uint8_t mode; /* 模式:电压或者电流 */ - uint32_t minUv; /* 最小可设置输出电压 */ - uint32_t maxUv; /* 最大可设置输出电压 */ - uint32_t minUa; /* 最小可设置输出电流 */ - uint32_t maxUa; /* 最大可设置输出电流 */ + uint8_t alwaysOn; // regulator是否常开 + uint8_t mode; // 模式:电压或者电流 + uint32_t minUv; // 最小可设置输出电压 + uint32_t maxUv; // 最大可设置输出电压 + uint32_t minUa; // 最小可设置输出电流 + uint32_t maxUa; // 最大可设置输出电流 }; ``` - - - + - 实例化RegulatorNode成员RegulatorMethod,其他成员在Init函数中初始化。 ```c - // regulator_virtual.c中的示例:钩子函数的填充 + /* regulator_virtual.c中的示例:钩子函数的填充 */ static struct RegulatorMethod g_method = { .enable = VirtualRegulatorEnable, .disable = VirtualRegulatorDisable, @@ -256,18 +260,16 @@ Regulator模块适配包含以下四个步骤: .getStatus = VirtualRegulatorGetStatus, }; ``` - - - - - Init函数参考 + + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf\_base.h中HDF\_STATUS定义)。 + HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf\_core/framework/include/utils/hdf\_base.h中HDF\_STATUS定义)。 **表 2** HDF\_STATUS相关状态 @@ -283,44 +285,43 @@ Regulator模块适配包含以下四个步骤: 函数说明: 初始化自定义结构体和RegulatorNode成员,并通过调用核心层RegulatorNodeAdd函数挂载Regulator控制器。 - - ```c - static int32_t VirtualRegulatorInit(struct HdfDeviceObject *device) - { - int32_t ret; - const struct DeviceResourceNode *childNode = NULL; - ... - DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { - ret = VirtualRegulatorParseAndInit(device, childNode);// 【必要】实现见下 - ... - } - ... - } - - static int32_t VirtualRegulatorParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) - { - int32_t ret; - struct RegulatorNode *regNode = NULL; - (void)device; - - regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode));//加载HCS文件 - ... - ret = VirtualRegulatorReadHcs(regNode, node); // 读取HCS文件信息 - ... - regNode->priv = (void *)node; // 实例化节点 - regNode->ops = &g_method; // 实例化ops - - ret = RegulatorNodeAdd(regNode); // 挂载节点 - ... - } - ``` - - - Release 函数参考 + ```c + static int32_t VirtualRegulatorInit(struct HdfDeviceObject *device) + { + int32_t ret; + const struct DeviceResourceNode *childNode = NULL; + ... + DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { + ret = VirtualRegulatorParseAndInit(device, childNode); // 【必要】实现见下 + ... + } + ... + } + + static int32_t VirtualRegulatorParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) + { + int32_t ret; + struct RegulatorNode *regNode = NULL; + (void)device; + + regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode)); //加载HCS文件 + ... + ret = VirtualRegulatorReadHcs(regNode, node); // 读取HCS文件信息 + ... + regNode->priv = (void *)node; // 实例化节点 + regNode->ops = &g_method; // 实例化ops + + ret = RegulatorNodeAdd(regNode); // 挂载节点 + ... + } + ``` + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,其包含了HCS配置文件中的相关配置信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,其包含了HCS配置文件中的相关配置信息。 返回值: @@ -334,12 +335,10 @@ Regulator模块适配包含以下四个步骤: static void VirtualRegulatorRelease(struct HdfDeviceObject *device) { ... - RegulatorNodeRemoveAll();// 【必要】调用核心层函数,释放RegulatorNode的设备和服务 + RegulatorNodeRemoveAll(); // 【必要】调用核心层函数,释放RegulatorNode的设备和服务 } ``` - + 4. 驱动调试: 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的测试用例是否成功等。 - - diff --git a/zh-cn/device-dev/driver/driver-platform-rtc-des.md b/zh-cn/device-dev/driver/driver-platform-rtc-des.md index d1be53836624a326e3b79d65c4cb859a349607a9..de7a4a2ce02486f883ca3074cfcfc7738fe286f2 100644 --- a/zh-cn/device-dev/driver/driver-platform-rtc-des.md +++ b/zh-cn/device-dev/driver/driver-platform-rtc-des.md @@ -1,49 +1,61 @@ # RTC - ## 概述 +### 功能简介 + RTC(real-time clock)为操作系统中的实时时钟设备,为操作系统提供精准的实时时间和定时报警功能。当设备下电后,通过外置电池供电,RTC继续记录操作系统时间;设备上电后,RTC提供实时时钟给操作系统,确保断电后系统时间的连续性。 +### 运作机制 -## 接口说明 +在HDF框架中,RTC模块采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,若设备过多会增加内存占用。通常,一个硬件系统中只需要一个RTC设备,因此RTC模块采用独立服务模式较为合适。 - **表1** RTC设备API接口功能介绍 +## 使用指导 -| 功能分类 | 接口描述 | -| -------- | -------- | -| RTC句柄操作 | RtcOpen:获取RTC设备驱动句柄
RtcClose:释放RTC设备驱动句柄 | -| RTC时间操作接口 | RtcReadTime:读RTC时间信息,包括年、月、星期、日、时、分、秒、毫秒
RtcWriteTime:写RTC时间信息,包括年、月、星期、日、时、分、秒、毫秒 | -| RTC报警操作接口 | RtcReadAlarm:读RTC报警时间信息
RtcWriteAlarm:写RTC报警时间信息
RtcRegisterAlarmCallback:注册报警超时回调函数
RtcAlarmInterruptEnable:使能/去使能RTC报警中断 | -| RTC配置操作 | RtcGetFreq:读RTC外接晶振频率
RtcSetFreq:配置RTC外接晶振频率
RtcReset:RTC复位 | -| 读写用户定义寄存器 | RtcReadReg:读用户自定义寄存器
RtcWriteReg:写用户自定义寄存器 | +### 场景介绍 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +RTC主要用于提供实时时间和定时报警功能。 +### 接口说明 -## 使用指导 +RTC模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/rtc_if.h。 +**表1** RTC设备API接口功能介绍 -### 使用流程 +| 接口名 | 接口描述 | +| -------- | -------- | +| DevHandle RtcOpen(void) | 获取RTC设备驱动句柄 | +| void RtcClose(DevHandle handle) | 释放RTC设备驱动句柄 | +| int32_t RtcReadTime(DevHandle handle, struct RtcTime \*time) | 读RTC时间信息 | +| int32_t RtcWriteTime(DevHandle handle, const struct RtcTime \*time) | 写RTC时间信息,包括年、月、星期、日、时、分、秒、毫秒 | +| int32_t RtcReadAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime \*time) | 读RTC报警时间信息 | +| int32_t RtcWriteAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, const struct RtcTime \*time) | 写RTC报警时间信息 | +| int32_t RtcRegisterAlarmCallback(DevHandle handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb) | 注册报警超时回调函数 | +| int32_t RtcAlarmInterruptEnable(DevHandle handle, enum RtcAlarmIndex alarmIndex, uint8_t enable) | 使能/去使能RTC报警中断 | +| int32_t RtcGetFreq(DevHandle handle, uint32_t \*freq) | 读RTC外接晶振频率 | +| int32_t RtcSetFreq(DevHandle handle, uint32_t freq) | 配置RTC外接晶振频率 | +| int32_t RtcReset(DevHandle handle) | RTC复位 | +| int32_t RtcReadReg(DevHandle handle, uint8_t usrDefIndex, uint8_t \*value) | 读用户自定义寄存器 | +| int32_t RtcWriteReg(DevHandle handle, uint8_t usrDefIndex, uint8_t value) | 写用户自定义寄存器 | -在操作系统启动过程中,驱动管理模块根据配置文件加载RTC驱动,RTC驱动会检测RTC器件并初始化驱动。 +### 使用流程 使用RTC设备的一般流程如下图所示。 - **图1** RTC设备使用流程图 - - ![image](figures/RTC设备使用流程图.png "RTC设备使用流程图") +**图1** RTC设备使用流程图 +![image](figures/RTC设备使用流程图.png "RTC设备使用流程图") -### 创建RTC设备句柄 +#### 创建RTC设备句柄 RTC驱动加载成功后,使用驱动框架提供的查询接口并调用RTC设备驱动接口。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 当前操作系统支持一个RTC设备。 +> 当前操作系统仅支持一个RTC设备。 +```c DevHandle RtcOpen(void); +``` **表2** RtcOpen参数和返回值描述 @@ -55,7 +67,7 @@ DevHandle RtcOpen(void); | NULL | 操作失败 | -``` +```c DevHandle handle = NULL; /* 获取RTC句柄 */ @@ -65,33 +77,15 @@ if (handle == NULL) { } ``` - -### 销毁RTC设备句柄 - -销毁RTC设备句柄,系统释放对应的资源。 - -void RtcClose(DevHandle handle); - - **表3** RtcClose参数描述 - -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | - - -``` -/* 销毁RTC句柄 */ -RtcClose(handle); -``` - - -### 注册RTC定时报警回调函数 +#### 注册RTC定时报警回调函数 系统启动后需要注册RTC定时报警回调函数,报警超时后触发回调函数。 +```c int32_t RtcRegisterAlarmCallback(DevHandle handle, enum RtcAlarmIndex alarmIndex, RtcAlarmCallback cb); +``` - **表4** RtcRegisterAlarmCallback参数和返回值描述 + **表3** RtcRegisterAlarmCallback参数和返回值描述 | **参数** | **描述** | | -------- | -------- | @@ -104,7 +98,7 @@ int32_t RtcRegisterAlarmCallback(DevHandle handle, enum RtcAlarmIndex alarmIndex 注册RTC_ALARM_INDEX_A的定时报警处理函数, 示例如下: -``` +```c /* 用户注册RTC定时报警回调函数的方法 */ int32_t RtcAlarmACallback(enum RtcAlarmIndex alarmIndex) { @@ -126,318 +120,346 @@ if (ret != 0) { ``` -### 操作RTC +#### 操作RTC - 读取RTC时间。 -系统从RTC读取时间信息,包括年、月、星期、日、时、分、秒、毫秒,则可以通过以下函数完成: + 系统从RTC读取时间信息,包括年、月、星期、日、时、分、秒、毫秒,则可以通过以下函数完成: -int32_t RtcReadTime(DevHandle handle, struct RtcTime \*time); + ```c + int32_t RtcReadTime(DevHandle handle, struct RtcTime \*time); + ``` - **表5** RtcReadTime参数和返回值描述 + **表4** RtcReadTime参数和返回值描述 -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| time | RTC读取时间信息,包括年、月、星期、日、时、分、秒、毫秒 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | - - -``` -int32_t ret; -struct RtcTime tm; + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | time | RTC读取时间信息,包括年、月、星期、日、时、分、秒、毫秒 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | -/* 系统从RTC读取时间信息 */ -ret = RtcReadTime(handle, &tm); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + struct RtcTime tm; + + /* 系统从RTC读取时间信息 */ + ret = RtcReadTime(handle, &tm); + if (ret != 0) { + /* 错误处理 */ + } + ``` - 设置RTC时间 -设置RTC时间,则可以通过以下函数完成: - -int32_t RtcWriteTime(DevHandle handle, struct RtcTime \*time); + 设置RTC时间,则可以通过以下函数完成: - **表6** RtcWriteTime参数和返回值描述 + ```c + int32_t RtcWriteTime(DevHandle handle, struct RtcTime \*time); + ``` -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| time | 写RTC时间信息,包括年、月、星期、日、时、分、秒、毫秒 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | + **表5** RtcWriteTime参数和返回值描述 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> RTC起始时间为UTC 1970/01/01 Thursday 00:00:00,年的最大取值按照用户器件手册要求计算配置,星期不用配置。 + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | time | 写RTC时间信息,包括年、月、星期、日、时、分、秒、毫秒 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > RTC起始时间为UTC 1970/01/01 Thursday 00:00:00,年的最大取值按照用户器件手册要求计算配置,星期不用配置。 -``` -int32_t ret; -struct RtcTime tm; - -/* 设置RTC时间为 UTC 2020/01/01 00:59:00 .000 */ -tm.year = 2020; -tm.month = 01; -tm.day = 01; -tm.hour= 00; -tm.minute = 59; -tm.second = 00; -tm.millisecond = 0; -/* 写RTC时间信息 */ -ret = RtcWriteTime(handle, &tm); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + struct RtcTime tm; + + /* 设置RTC时间为 UTC 2020/01/01 00:59:00 .000 */ + tm.year = 2020; + tm.month = 01; + tm.day = 01; + tm.hour= 00; + tm.minute = 59; + tm.second = 00; + tm.millisecond = 0; + /* 写RTC时间信息 */ + ret = RtcWriteTime(handle, &tm); + if (ret != 0) { + /* 错误处理 */ + } + ``` - 读取RTC报警时间 -如果需要读取定时报警时间,则可以通过以下函数完成: + 如果需要读取定时报警时间,则可以通过以下函数完成: -int32_t RtcReadAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime \*time); + ```c + int32_t RtcReadAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime \*time); + ``` - **表7** RtcReadAlarm参数和返回值描述 + **表6** RtcReadAlarm参数和返回值描述 -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| alarmIndex | 报警索引 | -| time | RTC报警时间信息,包括年、月、星期、日、时、分、秒、毫秒 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | - - -``` -int32_t ret; -struct RtcTime alarmTime; + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | alarmIndex | 报警索引 | + | time | RTC报警时间信息,包括年、月、星期、日、时、分、秒、毫秒 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | -/* 读RTC_ALARM_INDEX_A索引的RTC定时报警时间信息 */ -ret = RtcReadAlarm(handle, RTC_ALARM_INDEX_A, &alarmTime); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + struct RtcTime alarmTime; + + /* 读RTC_ALARM_INDEX_A索引的RTC定时报警时间信息 */ + ret = RtcReadAlarm(handle, RTC_ALARM_INDEX_A, &alarmTime); + if (ret != 0) { + /* 错误处理 */ + } + ``` - 设置RTC报警时间 -根据报警索引设置RTC报警时间,通过以下函数完成: - -int32_t RtcWriteAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime \*time); + 根据报警索引设置RTC报警时间,通过以下函数完成: - **表8** RtcWriteAlarm参数和返回值描述 + ```c + int32_t RtcWriteAlarm(DevHandle handle, enum RtcAlarmIndex alarmIndex, struct RtcTime \*time); + ``` -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| alarmIndex | 报警索引 | -| time | RTC报警时间信息,包括年、月、星期、日、时、分、秒、毫秒 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | + **表7** RtcWriteAlarm参数和返回值描述 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> RTC起始时间为UTC 1970/01/01 Thursday 00:00:00,年的最大取值按照用户器件手册要求计算配置,星期不用配置。 + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | alarmIndex | 报警索引 | + | time | RTC报警时间信息,包括年、月、星期、日、时、分、秒、毫秒 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > RTC起始时间为UTC 1970/01/01 Thursday 00:00:00,年的最大取值按照用户器件手册要求计算配置,星期不用配置。 -``` -int32_t ret; -struct RtcTime alarmTime; - -/* 设置RTC报警时间为2020/01/01 00:59:59 .000 */ -alarmTime.year = 2020; -alarmTime.month = 01; -alarmTime.day = 01; -alarmTime.hour = 00; -alarmTime.minute = 59; -alarmTime.second = 59; -alarmTime.millisecond = 0; -/* 设置RTC_ALARM_INDEX_A索引的定时报警时间 */ -ret = RtcWriteAlarm(handle, RTC_ALARM_INDEX_A, &alarmTime); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + struct RtcTime alarmTime; + + /* 设置RTC报警时间为2020/01/01 00:59:59 .000 */ + alarmTime.year = 2020; + alarmTime.month = 01; + alarmTime.day = 01; + alarmTime.hour = 00; + alarmTime.minute = 59; + alarmTime.second = 59; + alarmTime.millisecond = 0; + /* 设置RTC_ALARM_INDEX_A索引的定时报警时间 */ + ret = RtcWriteAlarm(handle, RTC_ALARM_INDEX_A, &alarmTime); + if (ret != 0) { + /* 错误处理 */ + } + ``` - 设置定时报警中断使能或去使能 -在启动报警操作前,需要先设置报警中断使能,报警超时后会触发告警回调函数,可以通过以下函数完成: - -int32_t RtcAlarmInterruptEnable(DevHandle handle, enum RtcAlarmIndex alarmIndex, uint8_t enable); + 在启动报警操作前,需要先设置报警中断使能,报警超时后会触发告警回调函数,可以通过以下函数完成: - **表9** RtcAlarmInterruptEnable参数和返回值描述 + ```c + int32_t RtcAlarmInterruptEnable(DevHandle handle, enum RtcAlarmIndex alarmIndex, uint8_t enable); + ``` -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| alarmIndex | 报警索引 | -| enable | RTC报警中断配置,1:使能,0:去使能 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | + **表8** RtcAlarmInterruptEnable参数和返回值描述 + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | alarmIndex | 报警索引 | + | enable | RTC报警中断配置,1:使能,0:去使能 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | -``` -int32_t ret; - -/* 设置RTC报警中断使能 */ -ret = RtcAlarmInterruptEnable(handle, RTC_ALARM_INDEX_A, 1); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + + /* 设置RTC报警中断使能 */ + ret = RtcAlarmInterruptEnable(handle, RTC_ALARM_INDEX_A, 1); + if (ret != 0) { + /* 错误处理 */ + } + ``` - 读取RTC外频 -读取RTC外接晶体振荡频率,可以通过以下函数完成: + 读取RTC外接晶体振荡频率,可以通过以下函数完成: -int32_t RtcGetFreq(DevHandle handle, uint32_t \*freq); - - **表10** RtcGetFreq参数和返回值描述 - -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| freq | RTC的外接晶体振荡频率,单位(HZ) | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | + ```c + int32_t RtcGetFreq(DevHandle handle, uint32_t \*freq); + ``` + **表9** RtcGetFreq参数和返回值描述 -``` -int32_t ret; -uint32_t freq = 0; + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | freq | RTC的外接晶体振荡频率,单位(HZ) | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | -/* 读取RTC外接晶体振荡频率 */ -ret = RtcGetFreq(handle, &freq); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + uint32_t freq = 0; + + /* 读取RTC外接晶体振荡频率 */ + ret = RtcGetFreq(handle, &freq); + if (ret != 0) { + /* 错误处理 */ + } + ``` - 配置RTC外频 -配置RTC外接晶体振荡频率,可以通过以下函数完成: + 配置RTC外接晶体振荡频率,可以通过以下函数完成: -int32_t RtcSetFreq(DevHandle handle, uint32_t freq); + ```c + int32_t RtcSetFreq(DevHandle handle, uint32_t freq); + ``` - **表11** RtcSetFreq参数和返回值描述 + **表10** RtcSetFreq参数和返回值描述 -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| freq | RTC的外接晶体振荡频率,单位(HZ) | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | freq | RTC的外接晶体振荡频率,单位(HZ) | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | + ```c + int32_t ret; + uint32_t freq = 32768; /* 32768 Hz */ + + /* 设置RTC外接晶体振荡频率,注意按照器件手册要求配置RTC外频 */ + ret = RtcSetFreq(handle, freq); + if (ret != 0) { + /* 错误处理 */ + } + ``` -``` -int32_t ret; -uint32_t freq = 32768; /* 32768 Hz */ +- 复位RTC -/* 设置RTC外接晶体振荡频率,注意按照器件手册要求配置RTC外频 */ -ret = RtcSetFreq(handle, freq); -if (ret != 0) { - /* 错误处理 */ -} -``` + 复位RTC,复位RTC后各配置寄存器恢复默认值,可以通过以下函数完成: -- 复位RTC + ```c + int32_t RtcReset(DevHandle handle); + ``` -复位RTC,复位RTC后各配置寄存器恢复默认值,可以通过以下函数完成: + **表11** RtcReset参数和返回值描述 -int32_t RtcReset(DevHandle handle); + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | - **表12** RtcReset参数和返回值描述 + ```c + int32_t ret; + + /* 复位RTC,各配置寄存器恢复默认值 */ + ret = RtcReset(handle); + if (ret != 0) { + /* 错误处理 */ + } + ``` -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | +- 读取RTC自定义寄存器配置 + 按照用户定义的寄存器索引,读取对应的寄存器配置,一个索引对应一字节的配置值,通过以下函数完成: -``` -int32_t ret; + ```c + int32_t RtcReadReg(DevHandle handle, uint8_t usrDefIndex, uint8_t \*value); + ``` -/* 复位RTC,各配置寄存器恢复默认值 */ -ret = RtcReset(handle); -if (ret != 0) { - /* 错误处理 */ -} -``` + **表12** RtcReadReg参数和返回值描述 -- 读取RTC自定义寄存器配置 + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | usrDefIndex | 用户定义的寄存器对应索引 | + | value | 寄存器值 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | -按照用户定义的寄存器索引,读取对应的寄存器配置,一个索引对应一字节的配置值,通过以下函数完成: + ```c + int32_t ret; + uint8_t usrDefIndex = 0; /* 定义0索引对应用户定义的第一个寄存器*/ + uint8_t value = 0; + + /* 按照用户定义的寄存器索引,读取对应的寄存器配置,一个索引对应一字节的配置值 */ + ret = RtcReadReg(handle, usrDefIndex, &value); + if (ret != 0) { + /* 错误处理 */ + } + ``` -int32_t RtcReadReg(DevHandle handle, uint8_t usrDefIndex, uint8_t \*value); +- 设置RTC自定义寄存器配置 - **表13** RtcReadReg参数和返回值描述 + 按照用户定义的寄存器索引,设置对应的寄存器配置,一个索引对应一字节的配置值,通过以下函数完成: -| **参数** | **描述** | -| -------- | -------- | -| handle | RTC设备句柄 | -| usrDefIndex | 用户定义的寄存器对应索引 | -| value | 寄存器值 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | + ```c + int32_t RtcWriteReg(DevHandle handle, uint8_t usrDefIndex, uint8_t value); + ``` + **表13** RtcWriteReg参数和返回值描述 -``` -int32_t ret; -uint8_t usrDefIndex = 0; /* 定义0索引对应用户定义的第一个寄存器*/ -uint8_t value = 0; + | **参数** | **描述** | + | -------- | -------- | + | handle | RTC设备句柄 | + | usrDefIndex | 用户定义的寄存器对应索引 | + | value | 寄存器值 | + | **返回值** | **描述** | + | 0 | 操作成功 | + | 负数 | 操作失败 | -/* 按照用户定义的寄存器索引,读取对应的寄存器配置,一个索引对应一字节的配置值 */ -ret = RtcReadReg(handle, usrDefIndex, &value); -if (ret != 0) { - /* 错误处理 */ -} -``` + ```c + int32_t ret; + uint8_t usrDefIndex = 0; /* 定义0索引对应用户定义第一个寄存器*/ + uint8_t value = 0x10; + + /* 按照用户的定义的寄存器索引,设置对应的寄存器配置,一个索引对应一字节的配置值 */ + ret = RtcWriteReg(handle, usrDefIndex, value); + if (ret != 0) { + /* 错误处理 */ + } + ``` -- 设置RTC自定义寄存器配置 +#### 销毁RTC设备句柄 -按照用户定义的寄存器索引,设置对应的寄存器配置,一个索引对应一字节的配置值,通过以下函数完成: +销毁RTC设备句柄,系统释放对应的资源。 -int32_t RtcWriteReg(DevHandle handle, uint8_t usrDefIndex, uint8_t value); +```c +void RtcClose(DevHandle handle); +``` - **表14** RtcWriteReg参数和返回值描述 + **表14** RtcClose参数描述 | **参数** | **描述** | | -------- | -------- | | handle | RTC设备句柄 | -| usrDefIndex | 用户定义的寄存器对应索引 | -| value | 寄存器值 | -| **返回值** | **描述** | -| 0 | 操作成功 | -| 负数 | 操作失败 | - +```c +/* 销毁RTC句柄 */ +RtcClose(handle); ``` -int32_t ret; -uint8_t usrDefIndex = 0; /* 定义0索引对应用户定义第一个寄存器*/ -uint8_t value = 0x10; - -/* 按照用户的定义的寄存器索引,设置对应的寄存器配置,一个索引对应一字节的配置值 */ -ret = RtcWriteReg(handle, usrDefIndex, value); -if (ret != 0) { - /* 错误处理 */ -} -``` - -## 使用实例 +### 使用实例 -本实例提供RTC接口的完整使用流程: +本例基于Hi3516DV300开发板,提供RTC接口的完整使用流程: 1. 系统启动,驱动管理模块会识别系统当前的RTC器件; @@ -449,9 +471,9 @@ if (ret != 0) { 示例如下: - -``` +```c #include "rtc_if.h" + int32_t RtcAlarmACallback(enum RtcAlarmIndex alarmIndex) { if (alarmIndex == RTC_ALARM_INDEX_A) { diff --git a/zh-cn/device-dev/driver/driver-platform-rtc-develop.md b/zh-cn/device-dev/driver/driver-platform-rtc-develop.md index e94f517b89392ef3e256833ad0ded234bbbe9e56..16eeb076e3ead1bf7096f48b9073db5e0c0d6148 100755 --- a/zh-cn/device-dev/driver/driver-platform-rtc-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-rtc-develop.md @@ -1,21 +1,37 @@ # RTC - ## 概述 -RTC(Real-time Clock)为操作系统中的实时时钟设备。在HDF框架中,RTC的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 + +RTC(real-time clock)为操作系统中的实时时钟设备,为操作系统提供精准的实时时间和定时报警功能。当设备下电后,通过外置电池供电,RTC继续记录操作系统时间;设备上电后,RTC提供实时时钟给操作系统,确保断电后系统时间的连续性。 + +### 运作机制 + +在HDF框架中,RTC的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 + +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 + +**图1** RTC独立服务模式结构图 + +![image](figures/独立服务模式结构图.png "RTC独立服务模式结构图") + +## 开发指导 - **图1** RTC独立服务模式结构图 +### 场景介绍 - ![image](figures/独立服务模式结构图.png "RTC独立服务模式结构图") +RTC主要用于提供实时时间和定时报警功能。当驱动开发者需要将RTC设备适配到OpenHarmony时,需要进行RTC驱动适配,下文将介绍如何进行RTC驱动适配。 +### 接口说明 -## 接口说明 +为了保证上层在调用RTC接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/rtc/rtc_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 RtcMethod定义: - -``` +```c struct RtcMethod { int32_t (*ReadTime)(struct RtcHost *host, struct RtcTime *time); int32_t (*WriteTime)(struct RtcHost *host, const struct RtcTime *time); @@ -31,7 +47,7 @@ struct RtcMethod { }; ``` - **表1** RtcMethod结构体成员的回调函数功能说明 + **表1** RtcMethod结构体成员的钩子函数功能说明 | 函数 | 入参 | 出参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -------- | @@ -48,7 +64,7 @@ struct RtcMethod { | WriteReg | host:结构体指针,核心层RTC控制器
usrDefIndex:结构体,用户自定义寄存器索引
value:uint8_t,寄存器传入值 | 无 | HDF_STATUS相关状态 | 按照用户定义的寄存器索引,设置对应的寄存器配置,一个索引对应一字节的配置值 | -## 开发步骤 +### 开发步骤 RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及填充核心层接口函数。 @@ -71,9 +87,9 @@ RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置 【可选】针对新增驱动程序,建议验证驱动基本功能,例如RTC控制状态,中断响应情况等。 -## 开发实例 +### 开发实例 -下方将以rtc_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +下方将以Hi3516DV300的驱动//device/soc/hisilicon/common/platform/rtc/rtc_hi35xx.c为示例,展示驱动适配者需要提供哪些内容来完整实现设备功能。 1. 驱动开发首先需要实例化驱动入口。 @@ -85,94 +101,101 @@ RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置 RTC驱动入口参考: - ``` + ```c struct HdfDriverEntry g_rtcDriverEntry = { .moduleVersion = 1, - .Bind = HiRtcBind, // 见Bind参考 - .Init = HiRtcInit, // 见Init参考 - .Release = HiRtcRelease, // 见Release参考 + .Bind = HiRtcBind, // 见Bind开发参考 + .Init = HiRtcInit, // 见Init开发参考 + .Release = HiRtcRelease, // 见Release开发参考 .moduleName = "HDF_PLATFORM_RTC",// 【必要】且与HCS里面的名字匹配 }; - //调用HDF_INIT将驱动入口注册到HDF框架中 + /* 调用HDF_INIT将驱动入口注册到HDF框架中 */ HDF_INIT(g_rtcDriverEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在rtc_config.hcs中配置器件属性。 +2. 完成驱动入口注册之后,下一步请在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode信息,并在rtc_config.hcs中配置器件属性。 deviceNode信息与驱动入口注册相关,器件属性值与核心层RtcHost成员的默认值或限制范围有密切关系。 - 本例只有一个RTC控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在rtc_config文件中增加对应的器件属性。 + 本例只有一个RTC控制器,如有多个器件信息,则需要在device_info.hcs文件增加deviceNode信息,以及在rtc_config文件中增加对应的器件属性。 - device_info.hcs配置参考 - ``` + ```c root { - device_info { - platform :: host { - device_rtc :: device { - device0 :: deviceNode { - policy = 1; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 - priority = 30; // 值越小,优先级越高。 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_RTC"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 - serviceName = "HDF_PLATFORM_RTC"; // 【必要】驱动对外发布服务的名称,必须唯一。 - deviceMatchAttr = "hisilicon_hi35xx_rtc";// 【必要】需要与设备hcs文件中的match_attr匹配。 + device_info { + platform :: host { + device_rtc :: device { + device0 :: deviceNode { + policy = 1; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 + priority = 30; // 值越小,优先级越高。 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "HDF_PLATFORM_RTC"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_RTC"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_rtc"; // 【必要】需要与设备hcs文件中的match_attr匹配。 + } + } } - } } - } } ``` - rtc_config.hcs配置参考 - ``` + ```c root { - platform { - rtc_config { - controller_0x12080000 { - match_attr = "hisilicon_hi35xx_rtc";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - rtcSpiBaseAddr = 0x12080000; // 地址映射相关 - regAddrLength = 0x100; // 地址映射相关 - irq = 37; // 中断号 - supportAnaCtrl = false; - supportLock = false; - anaCtrlAddr = 0xff; - lock0Addr = 0xff; - lock1Addr = 0xff; - lock2Addr = 0xff; - lock3Addr = 0xff; - } + platform { + rtc_config { + controller_0x12080000 { + match_attr = "hisilicon_hi35xx_rtc"; // 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + rtcSpiBaseAddr = 0x12080000; // 地址映射相关 + regAddrLength = 0x100; // 地址映射相关 + irq = 37; // 中断号 + supportAnaCtrl = false; + supportLock = false; + anaCtrlAddr = 0xff; + lock0Addr = 0xff; + lock1Addr = 0xff; + lock2Addr = 0xff; + lock3Addr = 0xff; + } + } } - } } ``` -3. 完成属性文件配置之后,下一步就是以核心层RtcHost对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化RtcHost成员RtcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + 需要注意的是,新增rtc_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中rtc_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/rtc/rtc_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/rtc/rtc_config.hcs" // 配置文件相对路径 + ``` + +3. 完成属性文件配置之后,下一步就是以核心层RtcHost对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化RtcHost成员RtcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - 自定义结构体参考。 从驱动的角度看,自定义结构体是参数和数据的载体,而且rtc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员。 - - ``` + ```c struct RtcConfigInfo { - uint32_t spiBaseAddr; // 地址映射相关 - volatile void *remapBaseAddr; // 地址映射相关 - uint16_t regAddrLength; // 地址映射相关 - uint8_t supportAnaCtrl; // 是否支持anactrl - uint8_t supportLock; // 是否支持锁 - uint8_t irq; // 中断号 - uint8_t alarmIndex; // 闹钟索引 - uint8_t anaCtrlAddr; // anactrl地址 - struct RtcLockAddr lockAddr; // 锁地址 - RtcAlarmCallback cb; // 回调函数 - struct OsalMutex mutex; // 互斥锁 + uint32_t spiBaseAddr; // 地址映射相关 + volatile void *remapBaseAddr; // 地址映射相关 + uint16_t regAddrLength; // 地址映射相关 + uint8_t supportAnaCtrl; // 是否支持anactrl + uint8_t supportLock; // 是否支持锁 + uint8_t irq; // 中断号 + uint8_t alarmIndex; // 闹钟索引 + uint8_t anaCtrlAddr; // anactrl地址 + struct RtcLockAddr lockAddr; // 锁地址 + RtcAlarmCallback cb; // 回调函数 + struct OsalMutex mutex; // 互斥锁 }; - // RtcHost是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + /* RtcHost是核心层控制器结构体,其中的成员在Init函数中会被赋值。 */ struct RtcHost { struct IDeviceIoService service; struct HdfDeviceObject *device; @@ -180,35 +203,35 @@ RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置 void *data; }; ``` - - RtcHost成员回调函数结构体RtcMethod的实例化,其他成员在Init函数中初始化。 - - ``` - // rtc_hi35xx.c中的示例:钩子函数的填充 + - RtcHost成员钩子函数结构体RtcMethod的实例化,其他成员在Init函数中初始化。 + + ```c + /* rtc_hi35xx.c中的示例:钩子函数的填充 */ static struct RtcMethod g_method = { - .ReadTime = HiRtcReadTime, - .WriteTime = HiRtcWriteTime, - .ReadAlarm = HiReadAlarm, + .ReadTime = HiRtcReadTime, + .WriteTime = HiRtcWriteTime, + .ReadAlarm = HiReadAlarm, .WriteAlarm = HiWriteAlarm, - .RegisterAlarmCallback = HiRegisterAlarmCallback, - .AlarmInterruptEnable = HiAlarmInterruptEnable, - .GetFreq = HiGetFreq, - .SetFreq = HiSetFreq, - .Reset = HiReset, - .ReadReg = HiReadReg, + .RegisterAlarmCallback = HiRegisterAlarmCallback, + .AlarmInterruptEnable = HiAlarmInterruptEnable, + .GetFreq = HiGetFreq, + .SetFreq = HiSetFreq, + .Reset = HiReset, + .ReadReg = HiReadReg, .WriteReg = HiWriteReg, }; ``` - - Bind 函数参考 + - Bind函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 **表2** HDF_STATUS返回值描述 @@ -225,25 +248,24 @@ RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置 关联HdfDeviceObject对象和RtcHost。 - - ``` + ```c static int32_t HiRtcBind(struct HdfDeviceObject *device) { - struct RtcHost *host = NULL; - host = RtcHostCreate(device); // 实际是申请内存并挂接device: host->device = device - // 使HdfDeviceObject与RtcHost可以相互转化的前提 - ... - device->service = &host->service;// 使HdfDeviceObject与RtcHost可以相互转化的前提 - // 方便后续通过调用RtcHostFromDevice实现全局性质的host - return HDF_SUCCESS; + struct RtcHost *host = NULL; + host = RtcHostCreate(device); // 实际是申请内存并挂接device: host->device = device + // 使HdfDeviceObject与RtcHost可以相互转化的前提 + ... + device->service = &host->service; // 使HdfDeviceObject与RtcHost可以相互转化的前提 + // 方便后续通过调用RtcHostFromDevice实现全局性质的host + return HDF_SUCCESS; } ``` - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -253,39 +275,39 @@ RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置 初始化自定义结构体对象,初始化RtcHost成员。 - - ``` + ```c static int32_t HiRtcInit(struct HdfDeviceObject *device) { - struct RtcHost *host = NULL; - struct RtcConfigInfo *rtcInfo = NULL; - ... - host = RtcHostFromDevice(device);// 这里是HdfDeviceObject到RtcHost的强制转化 - rtcInfo = OsalMemCalloc(sizeof(*rtcInfo)); - ... - // HiRtcConfigData会从设备配置树中读取属性填充rtcInfo的supportAnaCtrl、supportLock、spiBaseAddr、regAddrLength、irq, - // 为HiRtcSwInit和HiRtcSwInit提供参数,当函数HiRtcSwInit和HiRtcSwInit内部执行失败后进行内存释放等操作。 - if (HiRtcConfigData(rtcInfo, device->property) != 0) { - ... - } - if (HiRtcSwInit(rtcInfo) != 0) {// 地址映射以及中断注册相关 + struct RtcHost *host = NULL; + struct RtcConfigInfo *rtcInfo = NULL; ... - } - if (HiRtcHwInit(rtcInfo) != 0) {// 初始化anaCtrl和lockAddr相关内容 + host = RtcHostFromDevice(device); // 这里是HdfDeviceObject到RtcHost的强制转换 + rtcInfo = OsalMemCalloc(sizeof(*rtcInfo)); ... - } + /* HiRtcConfigData会从设备配置树中读取属性填充rtcInfo的supportAnaCtrl、supportLock、spiBaseAddr、regAddrLength、irq, + * 为HiRtcSwInit和HiRtcSwInit提供参数,当函数HiRtcSwInit和HiRtcSwInit内部执行失败后进行内存释放等操作。 + */ + if (HiRtcConfigData(rtcInfo, device->property) != 0) { + ... + } + if (HiRtcSwInit(rtcInfo) != 0) { // 地址映射以及中断注册相关 + ... + } + if (HiRtcHwInit(rtcInfo) != 0) { // 初始化anaCtrl和lockAddr相关内容 + ... + } - host->method = &g_method;// RtcMethod的实例化对象的挂载 - host->data = rtcInfo; // 使RtcConfigInfo与RtcHost可以相互转化的前提 - HDF_LOGI("Hdf dev service:%s init success!", HdfDeviceGetServiceName(device)); - return HDF_SUCCESS; + host->method = &g_method; // RtcMethod的实例化对象的挂载 + host->data = rtcInfo; // 使RtcConfigInfo与RtcHost可以相互转化的前提 + HDF_LOGI("Hdf dev service:%s init success!", HdfDeviceGetServiceName(device)); + return HDF_SUCCESS; } ``` - - Release 函数参考 + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -299,19 +321,19 @@ RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置 > 所有强制转换获取相应对象的操作前提是在Init或Bind函数中具备对应赋值的操作。 - ``` + ```c static void HiRtcRelease(struct HdfDeviceObject *device) { struct RtcHost *host = NULL; struct RtcConfigInfo *rtcInfo = NULL; ... - host = RtcHostFromDevice(device); // 这里是HdfDeviceObject到RtcHost的强制转化 - rtcInfo = (struct RtcConfigInfo *)host->data;// 这里是RtcHost到RtcConfigInfo的强制转化 + host = RtcHostFromDevice(device); // 这里是HdfDeviceObject到RtcHost的强制转换 + rtcInfo = (struct RtcConfigInfo *)host->data; // 这里是RtcHost到RtcConfigInfo的强制转换 if (rtcInfo != NULL) { HiRtcSwExit(rtcInfo); - OsalMemFree(rtcInfo); // 释放RtcConfigInfo + OsalMemFree(rtcInfo); // 释放RtcConfigInfo host->data = NULL; } - RtcHostDestroy(host); // 释放RtcHost + RtcHostDestroy(host); // 释放RtcHost } ``` diff --git a/zh-cn/device-dev/driver/driver-platform-sdio-des.md b/zh-cn/device-dev/driver/driver-platform-sdio-des.md index bd0330af218ae12ba632f155e4cca10d151d52da..c43d88eecd9d918c5298ad7ef9317e42d81a8ce2 100644 --- a/zh-cn/device-dev/driver/driver-platform-sdio-des.md +++ b/zh-cn/device-dev/driver/driver-platform-sdio-des.md @@ -1,11 +1,21 @@ # SDIO - ## 概述 -SDIO是安全数字输入输出接口(Secure Digital Input and Output)的缩写,是从SD内存卡接口的基础上演化出来的一种外设接口。SDIO接口兼容以前的SD内存卡,并且可以连接支持SDIO接口的设备。 +### 功能简介 -SDIO的应用比较广泛,目前,有许多手机都支持SDIO功能,并且很多SDIO外设也被开发出来,使得手机外接外设更加容易。常见的SDIO外设有WLAN、GPS、CAMERA、蓝牙等。 +SDIO是安全数字输入输出接口(Secure Digital Input and Output)的缩写,是从SD内存卡接口的基础上演化出来的一种外设接口。SDIO接口兼容以前的SD卡,并且可以连接支持SDIO接口的其他设备。 + +SDIO接口定义了操作SDIO的通用方法集合,包括: +- 打开/关闭SDIO控制器 +- 独占/释放HOST +- 使能/去使能设备 +- 申请/释放中断 +- 读写、获取/设置公共信息 + +### 运作机制 + +在HDF框架中,SDIO的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,若设备过多可能增加内存占用。 SDIO总线有两端,其中一端是主机端(HOST),另一端是设备端(DEVICE)。所有的通信都是由HOST端发出命令开始的,在DEVICE端只要能解析HOST的命令,就可以同HOST进行通信了。SDIO的HOST可以连接多个DEVICE,如下图所示: - CLK信号:HOST给DEVICE的时钟信号。 @@ -18,30 +28,42 @@ SDIO总线有两端,其中一端是主机端(HOST),另一端是设备端 ![image](figures/SDIO的HOST-DEVICE连接示意图.png "SDIO的HOST-DEVICE连接示意图") -SDIO接口定义了操作SDIO的通用方法集合,包括打开/关闭SDIO控制器、独占/释放HOST、使能/去使能设备、申请/释放中断、读写、获取/设置公共信息等。 +### 约束与限制 +SDIO模块API当前仅支持内核态调用。 -## 接口说明 +## 使用指导 - **表1** SDIO驱动API接口功能介绍 +### 场景介绍 -| 功能分类 | 接口描述 | -| -------- | -------- | -| SDIO设备打开/关闭接口 | - SdioOpen:打开指定总线号的SDIO控制器
- SdioClose:关闭SDIO控制器 | -| SDIO读写接口 | - SdioReadBytes:从指定地址开始,增量读取指定长度的数据
- SdioWriteBytes:从指定地址开始,增量写入指定长度的数据
- SdioReadBytesFromFixedAddr:从固定地址读取指定长度的数据
- SdioWriteBytesToFixedAddr:向固定地址写入指定长度的数据
- SdioReadBytesFromFunc0:从SDIO function 0的指定地址空间读取指定长度的数据
- SdioWriteBytesToFunc0:向SDIO function 0的指定地址空间写入指定长度的数据 | -| SDIO设置块大小接口 | SdioSetBlockSize:设置块的大小 | -| SDIO获取/设置公共信息接口 | - SdioGetCommonInfo:获取公共信息
- SdioSetCommonInfo:设置公共信息 | -| SDIO刷新数据接口 | SdioFlushData:刷新数据 | -| SDIO独占/释放HOST接口 | - SdioClaimHost:独占Host
- SdioReleaseHost:释放Host | -| SDIO使能/去使能功能设备接口 | - SdioEnableFunc:使能SDIO功能设备
- SdioDisableFunc:去使能SDIO功能设备 | -| SDIO申请/释放中断接口 | - SdioClaimIrq:申请中断
- SdioReleaseIrq:释放中断 | +SDIO的应用比较广泛,目前,有许多手机都支持SDIO功能,并且很多SDIO外设也被开发出来,使得手机外接外设更加容易。常见的SDIO外设有WLAN、GPS、CAMERA、蓝牙等。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,目前只支持在内核态使用,不支持在用户态使用。 +### 接口说明 +SDIO模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/sdio_if.h。 -## 使用指导 +**表1** SDIO驱动API接口功能介绍 +| 接口名 | 接口描述 | +| -------- | -------- | +| DevHandle SdioOpen(int16_t mmcBusNum, struct SdioFunctionConfig \*config) | 打开指定总线号的SDIO控制器 | +| void SdioClose(DevHandle handle) | 关闭SDIO控制器 | +| int32_t SdioReadBytes(DevHandle handle, uint8_t \*data, uint32_t addr, uint32_t size) | 从指定地址开始,增量读取指定长度的数据 | +| int32_t SdioWriteBytes(DevHandle handle, uint8_t \*data, uint32_t addr, uint32_t size) | 从指定地址开始,增量写入指定长度的数据 | +| int32_t SdioReadBytesFromFixedAddr(DevHandle handle, uint8_t \*data, uint32_t addr, uint32_t size, uint32_t scatterLen) | 从固定地址读取指定长度的数据 | +| int32_t SdioWriteBytesToFixedAddr(DevHandle handle, uint8_t \*data, uint32_t addr, uint32_t size, uint32_t scatterLen) | 向固定地址写入指定长度的数据 | +| int32_t SdioReadBytesFromFunc0(DevHandle handle, uint8_t \*data, uint32_t addr, uint32_t size) | 从SDIO function 0的指定地址空间读取指定长度的数据 | +| int32_t SdioWriteBytesToFunc0(DevHandle handle, uint8_t \*data, uint32_t addr, uint32_t size) | 向SDIO function 0的指定地址空间写入指定长度的数据 | +| int32_t SdioSetBlockSize(DevHandle handle, uint32_t blockSize) | 设置块的大小 | +| int32_t SdioGetCommonInfo(DevHandle handle, SdioCommonInfo \*info, SdioCommonInfoType infoType) | 获取公共信息 | +| int32_t SdioSetCommonInfo(DevHandle handle, SdioCommonInfo \*info, SdioCommonInfoType infoType) | 设置公共信息 | +| int32_t SdioFlushData(DevHandle handle) | 刷新数据 | +| void SdioClaimHost(DevHandle handle) | 独占Host | +| void SdioReleaseHost(DevHandle handle) | 释放Host | +| int32_t SdioEnableFunc(DevHandle handle) | 使能SDIO功能设备 | +| int32_t SdioDisableFunc(DevHandle handle) | 去使能SDIO功能设备 | +| int32_t SdioClaimIrq(DevHandle handle, SdioIrqHandler \*irqHandler) | 申请中断 | +| int32_t SdioReleaseIrq(DevHandle handle) | 释放中断 | ### 使用流程 @@ -51,13 +73,11 @@ SDIO接口定义了操作SDIO的通用方法集合,包括打开/关闭SDIO控 ![image](figures/SDIO使用流程图.png "SDIO使用流程图") - -### 打开SDIO控制器 +#### 打开SDIO控制器 在使用SDIO进行通信前,首先要调用SdioOpen获取SDIO控制器的设备句柄,该函数会返回指定总线号的SDIO控制器的设备句柄。 - -``` +```c DevHandle SdioOpen(int16_t mmcBusNum, struct SdioFunctionConfig *config); ``` @@ -72,8 +92,8 @@ DevHandle SdioOpen(int16_t mmcBusNum, struct SdioFunctionConfig *config); | 设备句柄 | SDIO控制器的设备句柄 | 打开SDIO控制器的示例如下: - -``` + +```c DevHandle handle = NULL; struct SdioFunctionConfig config; config.funcNr = 1; @@ -86,13 +106,11 @@ if (handle == NULL) { } ``` - -### 独占HOST +#### 独占HOST 获取到SDIO控制器的设备句柄之后,需要先独占HOST才能进行SDIO后续的一系列操作,独占HOST函数如下所示: - -``` +```c void SdioClaimHost(DevHandle handle); ``` @@ -104,18 +122,15 @@ void SdioClaimHost(DevHandle handle); 独占HOST示例如下: - -``` +```c SdioClaimHost(handle); /* 独占HOST */ ``` - -### 使能SDIO设备 +#### 使能SDIO设备 在访问寄存器之前,需要先使能SDIO设备,使能SDIO设备的函数如下所示: - -``` +```c int32_t SdioEnableFunc(DevHandle handle); ``` @@ -130,8 +145,7 @@ int32_t SdioEnableFunc(DevHandle handle); 使能SDIO设备的示例如下: - -``` +```c int32_t ret; /* 使能SDIO设备 */ ret = SdioEnableFunc(handle); @@ -140,13 +154,11 @@ if (ret != 0) { } ``` - -### 注册SDIO中断 +#### 注册SDIO中断 在通信之前,还需要注册SDIO中断,注册SDIO中断函数如下图所示: - -``` +```c int32_t SdioClaimIrq(DevHandle handle, SdioIrqHandler *handler); ``` @@ -161,8 +173,8 @@ int32_t SdioClaimIrq(DevHandle handle, SdioIrqHandler *handler); | 负数 | 注册中断失败 | 注册SDIO中的示例如下: - -``` + +```c /* 中断服务函数需要根据各自平台的情况去实现 */ static void SdioIrqFunc(void *data) { @@ -181,15 +193,13 @@ if (ret != 0) { } ``` - -### 进行SDIO通信 +#### 进行SDIO通信 - 向SDIO设备增量写入指定长度的数据 对应的接口函数如下所示: - - ``` + ```c int32_t SdioWriteBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size); ``` @@ -207,8 +217,7 @@ if (ret != 0) { 向SDIO设备增量写入指定长度的数据的示例如下: - - ``` + ```c int32_t ret; uint8_t wbuff[] = {1,2,3,4,5}; uint32_t addr = 0x100 + 0x09; @@ -223,8 +232,7 @@ if (ret != 0) { 对应的接口函数如下所示: - - ``` + ```c int32_t SdioReadBytes(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size); ``` @@ -242,8 +250,7 @@ if (ret != 0) { 从SDIO设备增量读取指定长度的数据的示例如下: - - ``` + ```c int32_t ret; uint8_t rbuff[5] = {0}; uint32_t addr = 0x100 + 0x09; @@ -255,10 +262,10 @@ if (ret != 0) { ``` - 向SDIO设备的固定地址写入指定长度的数据 + 对应的接口函数如下所示: - - ``` + ```c int32_t SdioWriteBytesToFixedAddr(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); ``` @@ -277,8 +284,7 @@ if (ret != 0) { 向SDIO设备的固定地址写入指定长度的数据的示例如下: - - ``` + ```c int32_t ret; uint8_t wbuff[] = {1,2,3,4,5}; uint32_t addr = 0x100 + 0x09; @@ -290,10 +296,10 @@ if (ret != 0) { ``` - 从SDIO设备的固定地址读取指定长度的数据 + 对应的接口函数如下所示: - - ``` + ```c int32_t SdioReadBytesFromFixedAddr(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); ``` @@ -312,8 +318,7 @@ if (ret != 0) { 从SDIO设备的固定地址读取指定长度的数据的示例如下: - - ``` + ```c int32_t ret; uint8_t rbuff[5] = {0}; uint32_t addr = 0x100 + 0x09; @@ -328,8 +333,7 @@ if (ret != 0) { 当前只支持写入一个字节的数据,对应的接口函数如下所示: - - ``` + ```c int32_t SdioWriteBytesToFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size); ``` @@ -347,8 +351,7 @@ if (ret != 0) { 向SDIO function 0的指定地址空间写入指定长度的数据的示例如下: - - ``` + ```c int32_t ret; uint8_t wbuff = 1; /* 向SDIO function 0地址0x2中写入1字节的数据 */ @@ -362,8 +365,7 @@ if (ret != 0) { 当前只支持读取一个字节的数据,对应的接口函数如下所示: - - ``` + ```c int32_t SdioReadBytesFromFunc0(DevHandle handle, uint8_t *data, uint32_t addr, uint32_t size); ``` @@ -381,8 +383,7 @@ if (ret != 0) { 从SDIO function 0的指定地址空间读取指定长度的数据的示例如下: - - ``` + ```c int32_t ret; uint8_t rbuff; /* 从SDIO function 0设备地址0x2中读取1字节的数据 */ @@ -392,8 +393,7 @@ if (ret != 0) { } ``` - -### 释放SDIO中断 +#### 释放SDIO中断 通信完成之后,需要释放SDIO中断,函数如下所示: @@ -410,8 +410,7 @@ int32_t SdioReleaseIrq(DevHandle handle); 释放SDIO中断的示例如下: - -``` +```c int32_t ret; /* 释放SDIO中断 */ ret = SdioReleaseIrq(handle); @@ -420,8 +419,7 @@ if (ret != 0) { } ``` - -### 去使能SDIO设备 +#### 去使能SDIO设备 通信完成之后,还需要去使能SDIO设备,函数如下所示: @@ -438,8 +436,7 @@ int32_t SdioDisableFunc(DevHandle handle); 去使能SDIO设备的示例如下: - -``` +```c int32_t ret; /* 去使能SDIO设备 */ ret = SdioDisableFunc(handle); @@ -448,13 +445,11 @@ if (ret != 0) { } ``` - -### 释放HOST +#### 释放HOST 通信完成之后,还需要释放去HOST,函数如下所示: - -``` +```c void SdioReleaseHost(DevHandle handle); ``` @@ -466,18 +461,15 @@ void SdioReleaseHost(DevHandle handle); 释放HOST的示例如下: - -``` +```c SdioReleaseHost(handle); /* 释放HOST */ ``` - -### 关闭SDIO控制器 +#### 关闭SDIO控制器 SDIO通信完成之后,最后需要关闭SDIO控制器,函数如下所示: - -``` +```c void SdioClose(DevHandle handle); ``` @@ -491,17 +483,17 @@ void SdioClose(DevHandle handle); 关闭SDIO控制器的示例如下: - -``` +```c SdioClose(handle); /* 关闭SDIO控制器 */ ``` +### 使用实例 -## 使用实例 +本例拟对Hi3516DV300开发板上SDIO设备进行操作。 - SDIO设备完整的使用示例如下所示,首先打开总线号为1的SDIO控制器,然后独占HOST、使能设备、注册中断,接着进行SDIO通信(读写等),通信完成之后,释放中断、去使能设备、释放HOST,最后关闭SDIO控制器。 +SDIO设备完整的使用示例如下所示,首先打开总线号为1的SDIO控制器,然后独占HOST、使能设备、注册中断,接着进行SDIO通信(读写等),通信完成之后,释放中断、去使能设备、释放HOST,最后关闭SDIO控制器。 -``` +```c #include "hdf_log.h" #include "sdio_if.h" @@ -529,7 +521,7 @@ void SdioTestSample(void) struct SdioFunctionConfig config = {1, 0x123, 0x456}; uint8_t val; uint32_t addr; - + /* 打开总线号为1的SDIO设备 */ handle = SdioOpen(1, &config); if (handle == NULL) { diff --git a/zh-cn/device-dev/driver/driver-platform-sdio-develop.md b/zh-cn/device-dev/driver/driver-platform-sdio-develop.md index bd8a24365c64192e6abc03906022c298eb0df433..b5d7e6205a959a27f5be0d71202e9435a4604043 100755 --- a/zh-cn/device-dev/driver/driver-platform-sdio-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-sdio-develop.md @@ -1,44 +1,64 @@ # SDIO - ## 概述 -SDIO(Secure Digital Input and Output)由SD卡发展而来,被统称为MMC(MultiMediaCard),相关技术差别不大。在HDF框架中,SDIO的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 + +SDIO(Secure Digital Input and Output)由SD卡发展而来,与SD卡统称为MMC(MultiMediaCard),二者使用相同的通信协议。SDIO接口兼容以前的SD卡,并且可以连接支持SDIO接口的其他设备。 + +### 运作机制 + +在HDF框架中,SDIO的接口适配模式采用独立服务模式(如图1)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,若设备过多可能增加内存占用。 + +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 + +**图1** SDIO独立服务模式结构图 + +![image](figures/独立服务模式结构图.png "SDIO独立服务模式结构图") + +### 约束与限制 - **图1** SDIO独立服务模式结构图 +SDIO模块API当前仅支持内核态调用。 - ![image](figures/独立服务模式结构图.png "SDIO独立服务模式结构图") +## 开发指导 +### 场景介绍 -## 接口说明 +SDIO的应用比较广泛,目前,有许多手机都支持SDIO功能,并且很多SDIO外设也被开发出来,使得手机外接外设更加容易。常见的SDIO外设有WLAN、GPS、CAMERA、蓝牙等。当驱动开发者需要将SDIO设备适配到OpenHarmony时,需要进行SDIO驱动适配,下文将介绍如何进行SDIO驱动适配。 + +### 接口说明 + +为了保证上层在调用SDIO接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/model/storage/include/mmc//mmc_sdio.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 SdioDeviceOps定义: - -``` -// 函数模板 +```c +/* 函数模板 */ struct SdioDeviceOps { - int32_t (*incrAddrReadBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); - int32_t (*incrAddrWriteBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); - int32_t (*fixedAddrReadBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); - int32_t (*fixedAddrWriteBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); - int32_t (*func0ReadBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); - int32_t (*func0WriteBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); - int32_t (*setBlockSize)(struct SdioDevice *dev, uint32_t blockSize); - int32_t (*getCommonInfo)(struct SdioDevice *dev, SdioCommonInfo *info, uint32_t infoType); - int32_t (*setCommonInfo)(struct SdioDevice *dev, SdioCommonInfo *info, uint32_t infoType); - int32_t (*flushData)(struct SdioDevice *dev); - int32_t (*enableFunc)(struct SdioDevice *dev); - int32_t (*disableFunc)(struct SdioDevice *dev); - int32_t (*claimIrq)(struct SdioDevice *dev, SdioIrqHandler *irqHandler); - int32_t (*releaseIrq)(struct SdioDevice *dev); - int32_t (*findFunc)(struct SdioDevice *dev, struct SdioFunctionConfig *configData); - int32_t (*claimHost)(struct SdioDevice *dev); - int32_t (*releaseHost)(struct SdioDevice *dev); + int32_t (*incrAddrReadBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); + int32_t (*incrAddrWriteBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); + int32_t (*fixedAddrReadBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); + int32_t (*fixedAddrWriteBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size, uint32_t scatterLen); + int32_t (*func0ReadBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); + int32_t (*func0WriteBytes)(struct SdioDevice *dev, uint8_t *data, uint32_t addr, uint32_t size); + int32_t (*setBlockSize)(struct SdioDevice *dev, uint32_t blockSize); + int32_t (*getCommonInfo)(struct SdioDevice *dev, SdioCommonInfo *info, uint32_t infoType); + int32_t (*setCommonInfo)(struct SdioDevice *dev, SdioCommonInfo *info, uint32_t infoType); + int32_t (*flushData)(struct SdioDevice *dev); + int32_t (*enableFunc)(struct SdioDevice *dev); + int32_t (*disableFunc)(struct SdioDevice *dev); + int32_t (*claimIrq)(struct SdioDevice *dev, SdioIrqHandler *irqHandler); + int32_t (*releaseIrq)(struct SdioDevice *dev); + int32_t (*findFunc)(struct SdioDevice *dev, struct SdioFunctionConfig *configData); + int32_t (*claimHost)(struct SdioDevice *dev); + int32_t (*releaseHost)(struct SdioDevice *dev); }; ``` - **表1** SdioDeviceOps结构体成员的回调函数功能说明 + **表1** SdioDeviceOps结构体成员的钩子函数功能说明 | 函数 | 入参 | 出参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -------- | @@ -65,9 +85,9 @@ struct SdioDeviceOps { > CommonInfo包括maxBlockNum(单个request中最大block数)、maxBlockSize(单个block最大字节数)、maxRequestSize(单个Request最大字节数)、enTimeout(最大超时时间,毫秒)、funcNum(功能编号1~7)、irqCap(IRQ capabilities)、(void \*)data。 -## 开发步骤 +### 开发步骤 -SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及填充核心层接口函数。 +SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及实例化SDIO控制器对象。 1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 @@ -87,10 +107,9 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 【可选】针对新增驱动程序,建议验证驱动基本功能,例如SDIO控制状态,中断响应情况等。 +### 开发实例 -## 开发实例 - -下方将以sdio_adapter.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +下方将以sdio_adapter.c为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 1. 驱动开发首先需要实例化驱动入口。 @@ -101,77 +120,83 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 SDIO 驱动入口参考: - - ``` + + ```c struct HdfDriverEntry g_sdioDriverEntry = { .moduleVersion = 1, - .Bind = Hi35xxLinuxSdioBind, // 见Bind参考 - .Init = Hi35xxLinuxSdioInit, // 见Init参考 - .Release = Hi35xxLinuxSdioRelease,// 见Release参考 - .moduleName = "HDF_PLATFORM_SDIO",// 【必要且与HCS文件中里面的moduleName匹配】 + .Bind = Hi35xxLinuxSdioBind, // 见Bind开发参考 + .Init = Hi35xxLinuxSdioInit, // 见Init开发参考 + .Release = Hi35xxLinuxSdioRelease, // 见Release开发参考 + .moduleName = "HDF_PLATFORM_SDIO", // 【必要且与HCS文件中里面的moduleName匹配】 }; - // 调用HDF_INIT将驱动入口注册到HDF框架中 + /* 调用HDF_INIT将驱动入口注册到HDF框架中 */ HDF_INIT(g_sdioDriverEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在sdio_config.hcs中配置器件属性。 +2. 完成驱动入口注册之后,下一步请在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode信息,并在sdio_config.hcs中配置器件属性。 deviceNode信息与驱动入口注册相关,器件属性值与核心层SdioDevice成员的默认值或限制范围有密切关系。 - 本例只有一个SDIO控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在sdio_config文件中增加对应的器件属性。 + 本例只有一个SDIO控制器,如有多个器件信息,则需要在device_info.hcs文件增加deviceNode信息,以及在sdio_config文件中增加对应的器件属性。 - device_info.hcs 配置参考: - - - ``` + + ```c root { - device_info { - match_attr = "hdf_manager"; - platform :: host { - hostName = "platform_host"; - priority = 50; - device_sdio :: device { - device0 :: deviceNode { - policy = 1; - priority = 70; - permission = 0644; - moduleName = "HDF_PLATFORM_SDIO"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 - serviceName = "HDF_PLATFORM_MMC_2"; // 【必要】驱动对外发布服务的名称,必须唯一。 - deviceMatchAttr = "hisilicon_hi35xx_sdio_0";// 【必要】用于配置控制器私有数据,要与sdio_config.hcs中对应控制器保持一致。 + device_info { + match_attr = "hdf_manager"; + platform :: host { + hostName = "platform_host"; + priority = 50; + device_sdio :: device { + device0 :: deviceNode { + policy = 1; + priority = 70; + permission = 0644; + moduleName = "HDF_PLATFORM_SDIO"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_MMC_2"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_sdio_0"; // 【必要】用于配置控制器私有数据,要与sdio_config.hcs中对应控制器保持一致。 + } + } } - } } - } } ``` - + - sdio_config.hcs 配置参考: - ``` + ```c root { - platform { - sdio_config { - template sdio_controller { - match_attr = ""; - hostId = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍。 - devType = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍。 - } - controller_0x2dd1 :: sdio_controller { - match_attr = "hisilicon_hi35xx_sdio_0";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致。 + platform { + sdio_config { + template sdio_controller { + match_attr = ""; + hostId = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍。 + devType = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍。 + } + controller_0x2dd1 :: sdio_controller { + match_attr = "hisilicon_hi35xx_sdio_0"; // 【必要】需要和device_info.hcs中的deviceMatchAttr值一致。 + } } - } } ``` -3. 完成属性文件配置之后,下一步就是以核心层SdioDevice对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化SdioDevice成员SdioDeviceOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + 需要注意的是,新增sdio_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中sdio_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/sdio/sdio_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/sdio/sdio_config.hcs" // 配置文件相对路径 + ``` + +3. 完成属性文件配置之后,下一步就是以核心层SdioDevice对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化SdioDevice成员SdioDeviceOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - 自定义结构体参考: 从驱动的角度看,自定义结构体是参数和数据的载体,而且sdio_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 - - ``` + ```c typedef struct { uint32_t maxBlockNum; // 单个request最大的block个数 uint32_t maxBlockSize; // 单个block最大的字节数1~2048 @@ -182,7 +207,7 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 void *data; // 私有数据 } SdioFuncInfo; - // SdioDevice是核心层控制器结构体,其中的成员在Bind函数中会被赋值。 + /* SdioDevice是核心层控制器结构体,其中的成员在Bind函数中会被赋值。 */ struct SdioDevice { struct SdDevice sd; struct SdioDeviceOps *sdioOps; @@ -190,17 +215,16 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 uint32_t functions; struct SdioFunction *sdioFunc[SDIO_MAX_FUNCTION_NUMBER]; struct SdioFunction *curFunction; - struct OsalThread thread; /* irq thread */ + struct OsalThread thread; // 中断线程 struct OsalSem sem; bool irqPending; bool threadRunning; }; ``` - - SdioDevice成员回调函数结构体SdioDeviceOps的实例化,其他成员在Init函数中初始化。 + - SdioDevice成员钩子函数结构体SdioDeviceOps的实例化,其他成员在Init函数中初始化。 - - ``` + ```c static struct SdioDeviceOps g_sdioDeviceOps = { .incrAddrReadBytes = Hi35xxLinuxSdioIncrAddrReadBytes, .incrAddrWriteBytes = Hi35xxLinuxSdioIncrAddrWriteBytes, @@ -221,15 +245,16 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 .releaseHost = Hi35xxLinuxSdioReleaseHost, }; ``` - - Bind函数参考 + + - Bind函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 **表2** Bind函数入参及返回值 @@ -244,10 +269,10 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 函数说明: - 初始化自定义结构体对象,初始化SdioCntlr成员,调用核心层SdioCntlrAdd函数,以及其他厂商自定义初始化操作。 + 初始化自定义结构体对象,初始化SdioCntlr成员,调用核心层SdioCntlrAdd函数,以及其他驱动适配者自定义初始化操作。 - ``` + ```c static int32_t Hi35xxLinuxSdioBind(struct HdfDeviceObject *obj) { struct MmcCntlr *cntlr = NULL; @@ -277,11 +302,11 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 } ``` - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -289,22 +314,22 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 函数说明: - 无操作,可根据厂商需要添加。 + 无操作,可根据驱动适配者需要添加。 - ``` + ```c static int32_t Hi35xxLinuxSdioInit(struct HdfDeviceObject *obj) { - (void)obj;// 无操作,可根据厂商需要添加 + (void)obj; // 无操作,可根据驱动适配者的需要进行添加 HDF_LOGD("Hi35xxLinuxSdioInit: Success!"); return HDF_SUCCESS; } ``` - - Release函数参考 + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -317,12 +342,12 @@ SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 所有强制转换获取相应对象的操作前提是在Bind函数中具备对应赋值的操作。 - ``` + ```c static void Hi35xxLinuxSdioRelease(struct HdfDeviceObject *obj) { if (obj == NULL) { return; } - Hi35xxLinuxSdioDeleteCntlr((struct MmcCntlr *)obj->service);// 【必要】自定义的内存释放函数,这里有HdfDeviceObject到MmcCntlr的强制转化 + Hi35xxLinuxSdioDeleteCntlr((struct MmcCntlr *)obj->service); // 【必要】自定义的内存释放函数,这里有HdfDeviceObject到MmcCntlr的强制转换 } ``` \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-spi-des.md b/zh-cn/device-dev/driver/driver-platform-spi-des.md index 79787c85ae86460d349cb0ea0cb55d33729ff6e3..0f5f1f7432a2b3e7d4ad4ab6963ee4bc1a845ee2 100644 --- a/zh-cn/device-dev/driver/driver-platform-spi-des.md +++ b/zh-cn/device-dev/driver/driver-platform-spi-des.md @@ -1,9 +1,20 @@ # SPI - ## 概述 -SPI指串行外设接口(Serial Peripheral Interface),是一种高速的,全双工,同步的通信总线。SPI是由Motorola公司开发,用于在主设备和从设备之间进行通信,常用于与闪存、实时时钟、传感器以及模数转换器等进行通信。 +### 功能简介 + +SPI指串行外设接口(Serial Peripheral Interface),是一种高速的,全双工,同步的通信总线。SPI是由Motorola公司开发,用于在主设备和从设备之间进行通信。 + +SPI接口定义了操作SPI设备的通用方法集合,包括: + - SPI设备句柄获取和释放。 + - SPI读写:从SPI设备读取或写入指定长度数据。 + - SPI自定义传输:通过消息传输结构体执行任意读写组合过程。 + - SPI设备配置:获取和设置SPI设备属性。 + +### 运作机制 + +在HDF框架中,SPI的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,若设备过多可能增加内存占用。 SPI以主从方式工作,通常有一个主设备和一个或者多个从设备。主设备和从设备之间一般用4根线相连,它们分别是: - SCLK:时钟信号,由主设备产生; @@ -13,9 +24,9 @@ SPI以主从方式工作,通常有一个主设备和一个或者多个从设 一个主设备和两个从设备的连接示意图如下所示,Device A和Device B共享主设备的SCLK、MISO和MOSI三根引脚,Device A的片选CS0连接主设备的CS0,Device B的片选CS1连接主设备的CS1。 - **图1** SPI主从设备连接示意图 +**图1** SPI主从设备连接示意图 - ![image](figures/SPI主从设备连接示意图.png "SPI主从设备连接示意图") +![image](figures/SPI主从设备连接示意图.png "SPI主从设备连接示意图") - SPI通信通常由主设备发起,通过以下步骤完成一次通信: 1. 通过CS选中要通信的从设备,在任意时刻,一个主设备上最多只能有一个从设备被选中。 @@ -28,36 +39,31 @@ SPI以主从方式工作,通常有一个主设备和一个或者多个从设 - CPOL=1,CPHA=0 时钟信号idle状态为高电平,第一个时钟边沿采样数据。 - CPOL=1,CPHA=1 时钟信号idle状态为高电平,第二个时钟边沿采样数据。 -- SPI接口定义了操作SPI设备的通用方法集合,包括: - - SPI设备句柄获取和释放。 - - SPI读写: 从SPI设备读取或写入指定长度数据。 - - SPI自定义传输:通过消息传输结构体执行任意读写组合过程。 - - SPI设备配置:获取和设置SPI设备属性。 +### 约束与限制 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 当前只支持主机模式,不支持从机模式。 +SPI模块当前只支持主机模式,不支持从机模式。 +## 使用指导 -## 接口说明 +### 场景介绍 - **表1** SPI驱动API接口功能介绍 +SPI通常用于与闪存、实时时钟、传感器以及模数/数模转换器等支持SPI协议的设备进行通信。 -| 接口名 | 接口描述 | -| -------- | -------- | -| SpiOpen | 获取SPI设备句柄 | -| SpiClose | 释放SPI设备句柄 | -| SpiRead | 读取指定长度的数据 | -| SpiWrite | 写入指定长度的数据 | -| SpiTransfer | SPI数据传输接口 | -| SpiSetCfg | 根据指定参数,配置SPI设备 | -| SpiGetCfg | 获取SPI设备配置参数 | +### 接口说明 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +SPI模块提供的主要接口如表1所示,具体API详见//drivers/hdf_core/framework/include/platform/spi_if.h。 +**表1** SPI驱动API接口功能介绍 -## 使用指导 - +| 接口名 | 接口描述 | +| -------- | -------- | +| DevHandle SpiOpen(const struct SpiDevInfo \*info) | 获取SPI设备句柄 | +| void SpiClose(DevHandle handle) | 释放SPI设备句柄 | +| int32_t SpiRead(DevHandle handle, uint8_t \*buf, uint32_t len) | 读取指定长度的数据 | +| int32_t SpiWrite(DevHandle handle, uint8_t \*buf, uint32_t len) | 写入指定长度的数据 | +| int32_t SpiTransfer(DevHandle handle, struct SpiMsg \*msgs, uint32_t count) | SPI数据传输接口 | +| int32_t SpiSetCfg(DevHandle handle, struct SpiCfg \*cfg) | 根据指定参数,配置SPI设备 | +| int32_t SpiGetCfg(DevHandle handle, struct SpiCfg \*cfg) | 获取SPI设备配置参数 | ### 使用流程 @@ -67,13 +73,11 @@ SPI以主从方式工作,通常有一个主设备和一个或者多个从设 ![image](figures/SPI使用流程图.png "SPI使用流程图") - -### 获取SPI设备句柄 +#### 获取SPI设备句柄 在使用SPI进行通信时,首先要调用SpiOpen获取SPI设备句柄,该函数会返回指定总线号和片选号的SPI设备句柄。 - -``` +```c DevHandle SpiOpen(const struct SpiDevInfo *info); ``` @@ -88,8 +92,7 @@ DevHandle SpiOpen(const struct SpiDevInfo *info); 假设系统中的SPI设备总线号为0,片选号为0,获取该SPI设备句柄的示例如下: - -``` +```c struct SpiDevInfo spiDevinfo; /* SPI设备描述符 */ DevHandle spiHandle = NULL; /* SPI设备句柄 */ spiDevinfo.busNum = 0; /* SPI设备总线号 */ @@ -103,13 +106,11 @@ if (spiHandle == NULL) { } ``` - -### 获取SPI设备属性 +#### 获取SPI设备属性 在获取到SPI设备句柄之后,需要配置SPI设备属性。配置SPI设备属性之前,可以先获取SPI设备属性,获取SPI设备属性的函数如下所示: - -``` +```c int32_t SpiGetCfg(DevHandle handle, struct SpiCfg *cfg); ``` @@ -123,8 +124,7 @@ int32_t SpiGetCfg(DevHandle handle, struct SpiCfg *cfg); | 0 | 获取配置成功 | | 负数 | 获取配置失败 | - -``` +```c int32_t ret; struct SpiCfg cfg = {0}; /* SPI配置信息*/ ret = SpiGetCfg(spiHandle, &cfg); /* 获取SPI设备属性 */ @@ -133,13 +133,11 @@ if (ret != 0) { } ``` - -### 配置SPI设备属性 +#### 配置SPI设备属性 在获取到SPI设备句柄之后,需要配置SPI设备属性,配置SPI设备属性的函数如下所示: - -``` +```c int32_t SpiSetCfg(DevHandle handle, struct SpiCfg *cfg); ``` @@ -153,29 +151,26 @@ int32_t SpiSetCfg(DevHandle handle, struct SpiCfg *cfg); | 0 | 配置成功 | | 负数 | 配置失败 | - -``` +```c int32_t ret; struct SpiCfg cfg = {0}; /* SPI配置信息*/ cfg.mode = SPI_MODE_LOOP; /* 以回环模式进行通信 */ cfg.transferMode = PAL_SPI_POLLING_TRANSFER; /* 以轮询的方式进行通信 */ cfg.maxSpeedHz = 115200; /* 最大传输频率 */ -cfg.bitsPerWord = 8; /* 读写位宽为8个比特 */ +cfg.bitsPerWord = 8; /* 读写位宽为8比特 */ ret = SpiSetCfg(spiHandle, &cfg); /* 配置SPI设备属性 */ if (ret != 0) { HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret); } ``` - -### 进行SPI通信 +#### 进行SPI通信 - 向SPI设备写入指定长度的数据 如果只向SPI设备写一次数据,则可以通过以下函数完成: - - ``` + ```c int32_t SpiWrite(DevHandle handle, uint8_t *buf, uint32_t len); ``` @@ -190,8 +185,7 @@ if (ret != 0) { | 0 | 写入成功 | | 负数 | 写入失败 | - - ``` + ```c int32_t ret; uint8_t wbuff[4] = {0x12, 0x34, 0x56, 0x78}; /* 向SPI设备写入指定长度的数据 */ @@ -205,8 +199,7 @@ if (ret != 0) { 如果只读取一次数据,则可以通过以下函数完成: - - ``` + ```c int32_t SpiRead(DevHandle handle, uint8_t *buf, uint32_t len); ``` @@ -221,8 +214,7 @@ if (ret != 0) { | 0 | 读取成功 | | 负数 | 读取失败 | - - ``` + ```c int32_t ret; uint8_t rbuff[4] = {0}; /* 从SPI设备读取指定长度的数据 */ @@ -236,8 +228,7 @@ if (ret != 0) { 如果需要发起一次自定义传输,则可以通过以下函数完成: - - ``` + ```c int32_t SpiTransfer(DevHandle handle, struct SpiMsg *msgs, uint32_t count); ``` @@ -252,8 +243,7 @@ if (ret != 0) { | 0 | 执行成功 | | 负数 | 执行失败 | - - ``` + ```c int32_t ret; uint8_t wbuff[1] = {0x12}; uint8_t rbuff[1] = {0}; @@ -271,13 +261,11 @@ if (ret != 0) { } ``` - -### 销毁SPI设备句柄 +#### 销毁SPI设备句柄 SPI通信完成之后,需要销毁SPI设备句柄,销毁SPI设备句柄的函数如下所示: - -``` +```c void SpiClose(DevHandle handle); ``` @@ -289,17 +277,17 @@ void SpiClose(DevHandle handle); | -------- | -------- | | handle | SPI设备句柄 | - -``` +```c SpiClose(spiHandle); /* 销毁SPI设备句柄 */ ``` +### 使用实例 -## 使用实例 +本例拟对Hi3516DV300开发板上SPI设备进行操作。 - SPI设备完整的使用示例如下所示,首先获取SPI设备句柄,然后配置SPI设备属性,接着调用读写接口进行数据传输,最后销毁SPI设备句柄。 +SPI设备完整的使用示例如下所示,首先获取SPI设备句柄,然后配置SPI设备属性,接着调用读写接口进行数据传输,最后销毁SPI设备句柄。 -``` +```c #include "hdf_log.h" #include "spi_if.h" diff --git a/zh-cn/device-dev/driver/driver-platform-spi-develop.md b/zh-cn/device-dev/driver/driver-platform-spi-develop.md index 5904024e4ca36b0e2babfec72ab0947ee904118c..906e067e5db54c62fc2e59d7e5629d7c6b6cc1ee 100755 --- a/zh-cn/device-dev/driver/driver-platform-spi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-spi-develop.md @@ -1,30 +1,70 @@ # SPI - ## 概述 -SPI即串行外设接口(Serial Peripheral Interface)。在HDF框架中,SPI的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 + +SPI即串行外设接口(Serial Peripheral Interface),是一种高速的,全双工,同步的通信总线。SPI是由Motorola公司开发,用于在主设备和从设备之间进行通信。 + +### 运作机制 + +在HDF框架中,SPI的接口适配模式采用独立服务模式(如图1),在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,若设备过多可能增加内存占用。 + +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 + +**图1** SPI独立服务模式结构图 + +![image](figures/独立服务模式结构图.png "RTC独立服务模式结构图") + +SPI以主从方式工作,通常有一个主设备和一个或者多个从设备。主设备和从设备之间一般用4根线相连,它们分别是: + - SCLK:时钟信号,由主设备产生; + - MOSI:主设备数据输出,从设备数据输入; + - MISO:主设备数据输入,从设备数据输出; + - CS:片选,从设备使能信号,由主设备控制。 + +一个主设备和两个从设备的连接示意图如下所示,Device A和Device B共享主设备的SCLK、MISO和MOSI三根引脚,Device A的片选CS0连接主设备的CS0,Device B的片选CS1连接主设备的CS1。 + + **图2** SPI主从设备连接示意图 + + ![image](figures/SPI主从设备连接示意图.png "SPI主从设备连接示意图") + +- SPI通信通常由主设备发起,通过以下步骤完成一次通信: + 1. 通过CS选中要通信的从设备,在任意时刻,一个主设备上最多只能有一个从设备被选中。 + 2. 通过SCLK给选中的从设备提供时钟信号。 + 3. 基于SCLK时钟信号,主设备数据通过MOSI发送给从设备,同时通过MISO接收从设备发送的数据,完成通信。 + +- 根据SCLK时钟信号的CPOL(Clock Polarity,时钟极性)和CPHA(Clock Phase,时钟相位)的不同组合,SPI有以下四种工作模式: + - CPOL=0,CPHA=0 时钟信号idle状态为低电平,第一个时钟边沿采样数据。 + - CPOL=0,CPHA=1 时钟信号idle状态为低电平,第二个时钟边沿采样数据。 + - CPOL=1,CPHA=0 时钟信号idle状态为高电平,第一个时钟边沿采样数据。 + - CPOL=1,CPHA=1 时钟信号idle状态为高电平,第二个时钟边沿采样数据。 + +## 开发指导 - **图1** SPI独立服务模式结构图 +### 场景介绍 - ![image](figures/独立服务模式结构图.png "SPI独立服务模式结构图") +SPI通常用于与闪存、实时时钟、传感器以及模数/数模转换器等支持SPI协议的设备进行通信。当驱动开发者需要将SPI设备适配到OpenHarmony时,需要进行SPI驱动适配,下文将介绍如何进行SPI驱动适配。 -## 接口说明 +### 接口说明 + +为了保证上层在调用SPI接口时能够正确的操作硬件,核心层在//drivers/hdf_core/framework/support/platform/include/spi/spi_core.h中定义了以下钩子函数。驱动适配者需要在适配层实现这些函数的具体功能,并与这些钩子函数挂接,从而完成接口层与核心层的交互。 SpiCntlrMethod定义: - -``` +```c struct SpiCntlrMethod { - int32_t (*GetCfg)(struct SpiCntlr *cntlr, struct SpiCfg *cfg); - int32_t (*SetCfg)(struct SpiCntlr *cntlr, struct SpiCfg *cfg); - int32_t (*Transfer)(struct SpiCntlr *cntlr, struct SpiMsg *msg, uint32_t count); - int32_t (*Open)(struct SpiCntlr *cntlr); - int32_t (*Close)(struct SpiCntlr *cntlr); + int32_t (*GetCfg)(struct SpiCntlr *cntlr, struct SpiCfg *cfg); + int32_t (*SetCfg)(struct SpiCntlr *cntlr, struct SpiCfg *cfg); + int32_t (*Transfer)(struct SpiCntlr *cntlr, struct SpiMsg *msg, uint32_t count); + int32_t (*Open)(struct SpiCntlr *cntlr); + int32_t (*Close)(struct SpiCntlr *cntlr); }; ``` - **表1** SpiCntlrMethod结构体成员的回调函数功能说明 + **表1** SpiCntlrMethod结构体成员的钩子函数功能说明 | 成员函数 | 入参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | @@ -35,7 +75,7 @@ struct SpiCntlrMethod { | Close | cntlr:结构体指针,核心层SPI控制器。 | HDF_STATUS相关状态 | 关闭SPI | -## 开发步骤 +### 开发步骤 SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 @@ -57,10 +97,9 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 【可选】针对新增驱动程序,建议验证驱动基本功能,例如SPI控制状态,中断响应情况等。 +### 开发实例 -## 开发实例 - -下方将以spi_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +下方将以//device/soc/hisilicon/common/platform/spi/spi_hi35xx.c为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 1. 首先需要实例化驱动入口。 @@ -71,162 +110,169 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 SPI驱动入口参考: - - ``` + + ```c struct HdfDriverEntry g_hdfSpiDevice = { .moduleVersion = 1, - .moduleName = "HDF_PLATFORM_SPI",//【必要且与HCS文件中里面的moduleName匹配】 - .Bind = HdfSpiDeviceBind, //见Bind参考 - .Init = HdfSpiDeviceInit, //见Init参考 - .Release = HdfSpiDeviceRelease, //见Release参考 + .moduleName = "HDF_PLATFORM_SPI", //【必要且与HCS文件中里面的moduleName匹配】 + .Bind = HdfSpiDeviceBind, //见Bind开发参考 + .Init = HdfSpiDeviceInit, //见Init开发参考 + .Release = HdfSpiDeviceRelease, //见Release开发参考 }; - // 调用HDF_INIT将驱动入口注册到HDF框架中 + /* 调用HDF_INIT将驱动入口注册到HDF框架中 */ HDF_INIT(g_hdfSpiDevice); ``` -2. 完成驱动入口注册之后,在device_info.hcs文件中添加deviceNode信息,并在spi_config.hcs中配置器件属性。 +2. 完成驱动入口注册之后,在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode信息,并在spi_config.hcs中配置器件属性。 deviceNode信息与驱动入口注册相关,器件属性值与核心层SpiCntlr成员的默认值或限制范围有密切关系。 - 本例只有一个SPI控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在spi_config文件中增加对应的器件属性。 + 本例只有一个SPI控制器,如有多个器件信息,则需要在device_info.hcs文件增加deviceNode信息,以及在spi_config文件中增加对应的器件属性。 - device_info.hcs配置参考 - - - ``` + + ```c root { - device_info { - match_attr = "hdf_manager"; - platform :: host { - hostName = "platform_host"; - priority = 50; - device_spi :: device { //为每一个SPI控制器配置一个HDF设备节点 - device0 :: deviceNode { - policy = 1; - priority = 60; - permission = 0644; - moduleName = "HDF_PLATFORM_SPI"; - serviceName = "HDF_PLATFORM_SPI_0"; - deviceMatchAttr = "hisilicon_hi35xx_spi_0"; + device_info { + match_attr = "hdf_manager"; + platform :: host { + hostName = "platform_host"; + priority = 50; + device_spi :: device { //为每一个SPI控制器配置一个HDF设备节点 + device0 :: deviceNode { + policy = 2; + priority = 60; + permission = 0644; + moduleName = "HDF_PLATFORM_SPI"; + serviceName = "HDF_PLATFORM_SPI_0"; + deviceMatchAttr = "hisilicon_hi35xx_spi_0"; + } + device1 :: deviceNode { + policy = 2; + priority = 60; + permission = 0644; + moduleName = "HDF_PLATFORM_SPI"; // 【必要】用于指定驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 + serviceName = "HDF_PLATFORM_SPI_1"; // 【必要且唯一】驱动对外发布服务的名称。 + deviceMatchAttr = "hisilicon_hi35xx_spi_1"; // 需要与spi_config.hcs配置文件中的match_attr匹配。 + } + ... + } } - device1 :: deviceNode { - policy = 1; - priority = 60; - permission = 0644; - moduleName = "HDF_PLATFORM_SPI"; // 【必要】用于指定驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 - serviceName = "HDF_PLATFORM_SPI_1"; // 【必要且唯一】驱动对外发布服务的名称。 - deviceMatchAttr = "hisilicon_hi35xx_spi_1"; // 需要与设备hcs文件中的match_attr匹配。 - } - ... - } } - } } ``` - spi_config.hcs配置参考 - ``` + ```c root { - platform { - spi_config { // 每一个SPI控制器配置私有数据 - template spi_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 - serviceName = ""; - match_attr = ""; - transferMode = 0; // 数据传输模式:中断传输(0)、流控传输(1)、DMA传输(2) - busNum = 0; // 总线号 - clkRate = 100000000; - bitsPerWord = 8; // 传输位宽 - mode = 19; // SPI 数据的输入输出模式 - maxSpeedHz = 0; // 最大时钟频率 - minSpeedHz = 0; // 最小时钟频率 - speed = 2000000; // 当前消息传输速度 - fifoSize = 256; // FIFO大小 - numCs = 1; // 片选号 - regBase = 0x120c0000; // 地址映射需要 - irqNum = 100; // 中断号 - REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4 - CRG_SPI_CKEN = 0; - CRG_SPI_RST = 0; - REG_MISC_CTRL_SPI = 0x12030024; // MISC_REG_BASE(0x12030000) + 0x24 - MISC_CTRL_SPI_CS = 0; - MISC_CTRL_SPI_CS_SHIFT = 0; - } - controller_0x120c0000 :: spi_controller { - busNum = 0; // 【必要】总线号 - CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk - CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset - match_attr = "hisilicon_hi35xx_spi_0";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - } - controller_0x120c1000 :: spi_controller { - busNum = 1; - CRG_SPI_CKEN = 0x20000; // (0x1 << 17) 0:close clk, 1:open clk - CRG_SPI_RST = 0x2; // (0x1 << 1) 0:cancel reset, 1:reset - match_attr = "hisilicon_hi35xx_spi_1"; - regBase = 0x120c1000; // 【必要】地址映射需要 - irqNum = 101; // 【必要】中断号 - } - ... - // 【可选】可新增,但需要在device_info.hcs添加对应的节点。 + platform { + spi_config { // 每一个SPI控制器配置私有数据 + template spi_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 + serviceName = ""; + match_attr = ""; + transferMode = 0; // 数据传输模式:中断传输(0)、流控传输(1)、DMA传输(2) + busNum = 0; // 总线号 + clkRate = 100000000; + bitsPerWord = 8; // 传输位宽 + mode = 19; // SPI 数据的输入输出模式 + maxSpeedHz = 0; // 最大时钟频率 + minSpeedHz = 0; // 最小时钟频率 + speed = 2000000; // 当前消息传输速度 + fifoSize = 256; // FIFO大小 + numCs = 1; // 片选号 + regBase = 0x120c0000; // 地址映射需要 + irqNum = 100; // 中断号 + REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4 + CRG_SPI_CKEN = 0; + CRG_SPI_RST = 0; + REG_MISC_CTRL_SPI = 0x12030024; // MISC_REG_BASE(0x12030000) + 0x24 + MISC_CTRL_SPI_CS = 0; + MISC_CTRL_SPI_CS_SHIFT = 0; + } + controller_0x120c0000 :: spi_controller { + busNum = 0; // 【必要】总线号 + CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk + CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset + match_attr = "hisilicon_hi35xx_spi_0"; // 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + } + controller_0x120c1000 :: spi_controller { + busNum = 1; + CRG_SPI_CKEN = 0x20000; // (0x1 << 17) 0:close clk, 1:open clk + CRG_SPI_RST = 0x2; // (0x1 << 1) 0:cancel reset, 1:reset + match_attr = "hisilicon_hi35xx_spi_1"; + regBase = 0x120c1000; // 【必要】地址映射需要 + irqNum = 101; // 【必要】中断号 + } + ... + /* 【可选】可新增,但需要在device_info.hcs添加对应的节点。 */ + } } - } } ``` -3. 完成属性文件配置之后,下一步就是以核心层SpiCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化SpiCntlr成员SpiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + 需要注意的是,新增spi_config.hcs配置文件后,必须在hdf.hcs文件中将其包含,否则配置文件无法生效。 + + 例如:本例中spi_config.hcs所在路径为device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/spi/spi_config.hcs,则必须在产品对应的hdf.hcs中添加如下语句: + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/spi/spi_config.hcs" // 配置文件相对路径 + ``` + +3. 完成属性文件配置之后,下一步就是以核心层SpiCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化SpiCntlr成员SpiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - 自定义结构体参考 从驱动的角度看,自定义结构体是参数和数据的载体,而且spi_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号、总线号等。 - ``` - struct Pl022 {//对应于hcs中的参数 - struct SpiCntlr *cntlr; - struct DListHead deviceList; - struct OsalSem sem; - volatile unsigned char *phyBase; - volatile unsigned char *regBase; - uint32_t irqNum; - uint32_t busNum; - uint32_t numCs; - uint32_t curCs; - uint32_t speed; - uint32_t fifoSize; - uint32_t clkRate; - uint32_t maxSpeedHz; - uint32_t minSpeedHz; - uint32_t regCrg; - uint32_t clkEnBit; - uint32_t clkRstBit; - uint32_t regMiscCtrl; - uint32_t miscCtrlCsShift; - uint32_t miscCtrlCs; - uint16_t mode; - uint8_t bitsPerWord; - uint8_t transferMode; - }; - - // SpiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 - struct SpiCntlr { - struct IDeviceIoService service; - struct HdfDeviceObject *device; - uint32_t busNum; - uint32_t numCs; - uint32_t curCs; - struct OsalMutex lock; - struct SpiCntlrMethod *method; - struct DListHead list; - void *priv; - }; - ``` + ```c + struct Pl022 { //对应于spi_config.hcs中的参数 + struct SpiCntlr *cntlr; + struct DListHead deviceList; + struct OsalSem sem; + volatile unsigned char *phyBase; + volatile unsigned char *regBase; + uint32_t irqNum; + uint32_t busNum; + uint32_t numCs; + uint32_t curCs; + uint32_t speed; + uint32_t fifoSize; + uint32_t clkRate; + uint32_t maxSpeedHz; + uint32_t minSpeedHz; + uint32_t regCrg; + uint32_t clkEnBit; + uint32_t clkRstBit; + uint32_t regMiscCtrl; + uint32_t miscCtrlCsShift; + uint32_t miscCtrlCs; + uint16_t mode; + uint8_t bitsPerWord; + uint8_t transferMode; + }; + + /* SpiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 */ + struct SpiCntlr { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + uint32_t busNum; + uint32_t numCs; + uint32_t curCs; + struct OsalMutex lock; + struct SpiCntlrMethod *method; + struct DListHead list; + void *priv; + }; + ``` - - SpiCntlr成员回调函数结构体SpiCntlrMethod的实例化,其他成员在Init函数中初始化。 + - SpiCntlr成员钩子函数结构体SpiCntlrMethod的实例化,其他成员在Init函数中初始化。 - ``` - // spi_hi35xx.c中的示例:钩子函数的实例化 + ```c + /* spi_hi35xx.c中的示例:钩子函数的实例化 */ struct SpiCntlrMethod g_method = { .Transfer = Pl022Transfer, .SetCfg = Pl022SetCfg, @@ -240,7 +286,7 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -251,7 +297,7 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 将SpiCntlr对象同HdfDeviceObject进行了关联。 - ``` + ```c static int32_t HdfSpiDeviceBind(struct HdfDeviceObject *device) { ... @@ -260,28 +306,28 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device) { - struct SpiCntlr *cntlr = NULL; // 创建核心层SpiCntlr对象 + struct SpiCntlr *cntlr = NULL; // 创建核心层SpiCntlr对象 ... - cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr));// 分配内存 + cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr)); // 分配内存 ... - cntlr->device = device; // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 - device->service = &(cntlr->service); // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 - (void)OsalMutexInit(&cntlr->lock); // 锁初始化 - DListHeadInit(&cntlr->list); // 添加对应的节点 + cntlr->device = device; // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 + device->service = &(cntlr->service); // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 + (void)OsalMutexInit(&cntlr->lock); // 锁初始化 + DListHeadInit(&cntlr->list); // 添加对应的节点 cntlr->priv = NULL; return cntlr; } ``` - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 **表2** HDF_STATUS返回值描述 @@ -299,55 +345,55 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 初始化自定义结构体对象,初始化SpiCntlr成员。 - ``` + ```c static int32_t HdfSpiDeviceInit(struct HdfDeviceObject *device) { - int32_t ret; - struct SpiCntlr *cntlr = NULL; - ... - cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转化,通过service成员,赋值见Bind函数。 - // return (device == NULL) ? NULL : (struct SpiCntlr *)device->service; - ... - ret = Pl022Init(cntlr, device); // 【必要】实例化厂商自定义操作对象,示例见下。 - ... - ret = Pl022Probe(cntlr->priv); - ... - return ret; + int32_t ret; + struct SpiCntlr *cntlr = NULL; + ... + cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转换,通过service成员,赋值见Bind函数。 + // return (device == NULL) ? NULL : (struct SpiCntlr *)device->service; + ... + ret = Pl022Init(cntlr, device); // 【必要】实例化驱动适配者自定义操作对象,示例见下。 + ... + ret = Pl022Probe(cntlr->priv); + ... + return ret; } static int32_t Pl022Init(struct SpiCntlr *cntlr, const struct HdfDeviceObject *device) { - int32_t ret; - struct Pl022 *pl022 = NULL; - ... - pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022));// 申请内存 - ... - ret = SpiGetBaseCfgFromHcs(pl022, device->property); // 初始化busNum、numCs、speed、fifoSize、clkRate、mode、bitsPerWord、transferMode参数值。 - ... - ret = SpiGetRegCfgFromHcs(pl022, device->property); // 初始化regBase、phyBase、irqNum、regCrg、clkEnBit、clkRstBit、regMiscCtrl、regMiscCtrl、 miscCtrlCs、miscCtrlCsShift参数值。 - ... - // 计算最大、最小速度对应的频率。 - pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN); - pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX); - DListHeadInit(&pl022->deviceList); // 初始化DList链表 - pl022->cntlr = cntlr; // 使Pl022与SpiCntlr可以相互转化的前提 - cntlr->priv = pl022; // 使Pl022与SpiCntlr可以相互转化的前提 - cntlr->busNum = pl022->busNum; // 给SpiCntlr的busNum赋值 - cntlr->method = &g_method; // SpiCntlrMethod的实例化对象的挂载 - ... - ret = Pl022CreatAndInitDevice(pl022); - if (ret != 0) { - Pl022Release(pl022); // 初始化失败就释放Pl022对象 - return ret; - } - return 0; - } + int32_t ret; + struct Pl022 *pl022 = NULL; + ... + pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022)); // 申请内存 + ... + ret = SpiGetBaseCfgFromHcs(pl022, device->property); // 初始化busNum、numCs、speed、fifoSize、clkRate、mode、bitsPerWord、transferMode参数值。 + ... + ret = SpiGetRegCfgFromHcs(pl022, device->property); // 初始化regBase、phyBase、irqNum、regCrg、clkEnBit、clkRstBit、regMiscCtrl、regMiscCtrl、 miscCtrlCs、miscCtrlCsShift参数值。 + ... + // 计算最大、最小速度对应的频率。 + pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN); + pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX); + DListHeadInit(&pl022->deviceList); // 初始化DList链表 + pl022->cntlr = cntlr; // 使Pl022与SpiCntlr可以相互转化的前提 + cntlr->priv = pl022; // 使Pl022与SpiCntlr可以相互转化的前提 + cntlr->busNum = pl022->busNum; // 给SpiCntlr的busNum赋值 + cntlr->method = &g_method; // SpiCntlrMethod的实例化对象的挂载 + ... + ret = Pl022CreatAndInitDevice(pl022); + if (ret != 0) { + Pl022Release(pl022); // 初始化失败则释放Pl022对象 + return ret; + } + return 0; + } ``` - - Release函数参考 + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外提供的接口参数,具备HCS配置文件的信息。 返回值: @@ -360,17 +406,16 @@ SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 - - ``` + ```c static void HdfSpiDeviceRelease(struct HdfDeviceObject *device) { struct SpiCntlr *cntlr = NULL; ... - cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转化,通过service成员,赋值见Bind函数 + cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转换,通过service成员,赋值见Bind函数 // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service; ... if (cntlr->priv != NULL) { - Pl022Remove((struct Pl022 *)cntlr->priv); // 这里有SpiCntlr到Pl022的强制转化 + Pl022Remove((struct Pl022 *)cntlr->priv); // 这里有SpiCntlr到Pl022的强制转换 } SpiCntlrDestroy(cntlr); // 释放Pl022对象 } diff --git a/zh-cn/device-dev/driver/driver-platform-uart-des.md b/zh-cn/device-dev/driver/driver-platform-uart-des.md index b042d8fd09c9783091e3ce6ecbc3a5f848735a4b..500ab657eac4f5a9392d64771cc3eb01f9bed8b3 100644 --- a/zh-cn/device-dev/driver/driver-platform-uart-des.md +++ b/zh-cn/device-dev/driver/driver-platform-uart-des.md @@ -1,328 +1,350 @@ # UART - ## 概述 -UART指异步收发传输器(Universal Asynchronous Receiver/Transmitter),是通用串行数据总线,用于异步通信。该总线双向通信,可以实现全双工传输。 +### 功能简介 -UART应用比较广泛,常用于输出打印信息,也可以外接各种模块,如GPS、蓝牙等。 +UART指异步收发传输器(Universal Asynchronous Receiver/Transmitter),是通用串行数据总线,用于异步通信。该总线双向通信,可以实现全双工传输。 两个UART设备的连接示意图如下,UART与其他模块一般用2线(图1)或4线(图2)相连,它们分别是: + - TX:发送数据端,和对端的RX相连。 - RX:接收数据端,和对端的TX相连。 - RTS:发送请求信号,用于指示本设备是否准备好,可接受数据,和对端CTS相连。 - CTS:允许发送信号,用于判断是否可以向对端发送数据,和对端RTS相连。 - **图1** 2线UART设备连接示意图 +**图1** 2线UART设备连接示意图 - ![image](figures/2线UART设备连接示意图.png "2线UART设备连接示意图") +![image1](figures/2线UART设备连接示意图.png "2线UART设备连接示意图") - **图2** 4线UART设备连接示意图 +**图2** 4线UART设备连接示意图 - ![image](figures/4线UART设备连接示意图.png "4线UART设备连接示意图") +![image2](figures/4线UART设备连接示意图.png "4线UART设备连接示意图") -- UART通信之前,收发双方需要约定好一些参数:波特率、数据格式(起始位、数据位、校验位、停止位)等。通信过程中,UART通过TX发送给对端数据,通过RX接收对端发送的数据。当UART接收缓存达到预定的门限值时,RTS变为不可发送数据,对端的CTS检测到不可发送数据,则停止发送数据。 +UART通信之前,收发双方需要约定好一些参数:波特率、数据格式(起始位、数据位、校验位、停止位)等。通信过程中,UART通过TX发送给对端数据,通过RX接收对端发送的数据。当UART接收缓存达到预定的门限值时,RTS变为不可发送数据,对端的CTS检测到不可发送数据,则停止发送数据。 -- UART接口定义了操作UART端口的通用方法集合,包括获取、释放设备句柄、读写数据、获取和设置波特率、获取和设置设备属性。 +UART接口定义了操作UART端口的通用方法集合,包括: +- 打开/关闭UART设备 +- 读写数据 +- 设置/获取UART设备波特率 +- 设置/获取UART设备属性 -## 接口说明 +### 基本概念 - **表1** UART驱动API接口功能介绍 +- 异步通信 -| 接口名 | 接口描述 | -| -------- | -------- | -| UartOpen | UART获取设备句柄 | -| UartClose | UART释放设备句柄 | -| UartRead | 从UART设备中读取指定长度的数据 | -| UartWrite | 向UART设备中写入指定长度的数据 | -| UartGetBaud | UART获取波特率 | -| UartSetBaud | UART设置波特率 | -| UartGetAttribute | UART获取设备属性 | -| UartSetAttribute | UART设置设备属性 | -| UartSetTransMode | UART设置传输模式 | + 异步通信中,数据通常以字符或者字节为单位组成字符帧传送。字符帧由发送端逐帧发送,通过传输线被接收设备逐帧接收。发送端和接收端可以由各自的时钟来控制数据的发送和接收,这两个时钟源彼此独立,互不同步。异步通信以一个字符为传输单位,通信中两个字符间的时间间隔是不固定的,然而在同一个字符中的两个相邻位代码间的时间间隔是固定的。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的所有接口,仅限内核态使用,不支持在用户态使用。 +- 全双工传输(Full Duplex) + + 此通信模式允许数据在两个方向上同时传输,它在能力上相当于两个单工通信方式的结合。全双工可以同时进行信号的双向传输。 + +### 运作机制 + +在HDF框架中,UART接口适配模式采用独立服务模式(如图3所示)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 + +UART模块各分层作用: + +- 接口层提供打开UART设备、UART设备读取指定长度数据、UART设备写入指定长度数据、设置UART设备波特率、获取设UART设备波特率、设置UART设备属性、获取UART设备波特率、设置UART设备传输模式、关闭UART设备的接口。 +- 核心层主要提供看UART控制器的创建、移除以及管理的能力,通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 + +**图3** UART独立服务模式结构图 + +![image3](figures/独立服务模式结构图.png "UART独立服务模式结构图") ## 使用指导 +### 场景介绍 + +UART模块应用比较广泛,主要用于实现设备之间的低速串行通信,例如输出打印信息,当然也可以外接各种模块,如GPS、蓝牙等。 + +### 接口说明 + +**表1** UART驱动API接口功能介绍 + +| 接口名 | 接口描述 | +| -------- | -------- | +| DevHandle UartOpen(uint32_t port) | UART获取设备句柄 | +| void UartClose(DevHandle handle) | UART释放设备句柄 | +| int32_t UartRead(DevHandle handle, uint8_t *data, uint32_t size) | 从UART设备中读取指定长度的数据 | +| int32_t UartWrite(DevHandle handle, uint8_t *data, uint32_t size) | 向UART设备中写入指定长度的数据 | +| int32_t UartGetBaud(DevHandle handle, uint32_t *baudRate) | UART获取波特率 | +| int32_t UartSetBaud(DevHandle handle, uint32_t baudRate) | UART设置波特率 | +| int32_t UartGetAttribute(DevHandle handle, struct UartAttribute *attribute) | UART获取设备属性 | +| int32_t UartSetAttribute(DevHandle handle, struct UartAttribute *attribute) | UART设置设备属性 | +| int32_t UartSetTransMode(DevHandle handle, enum UartTransMode mode) | UART设置传输模式 | + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+> 本文涉及的UART所有接口,支持内核态及用户态使用。 -### 使用流程 +### 开发步骤 使用UART的一般流程如下图所示。 - **图3** UART使用流程图 +**图3** UART使用流程图 - ![image](figures/UART使用流程图.png "UART使用流程图") +![image3](figures/UART使用流程图.png "UART使用流程图") -### 获取UART设备句柄 +#### 获取UART设备句柄 在使用UART进行通信时,首先要调用UartOpen获取UART设备句柄,该函数会返回指定端口号的UART设备句柄。 - -``` +```c DevHandle UartOpen(uint32_t port); ``` - **表2** UartOpen参数和返回值描述 +**表2** UartOpen参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| port | UART设备号 | -| **返回值** | **返回值描述** | -| NULL | 获取UART设备句柄失败 | -| 设备句柄 | UART设备句柄 | +| port | UART设备号 | +| **返回值** | **返回值描述** | +| NULL | 获取UART设备句柄失败 | +| 设备句柄 | UART设备句柄 | + +假设系统中的UART端口号为1,获取该UART设备句柄的示例如下: + +```c +DevHandle handle = NULL; // UART设备句柄 +uint32_t port = 1; // UART设备端口号 - 假设系统中的UART端口号为3,获取该UART设备句柄的示例如下: - -``` -DevHandle handle = NULL; /* UART设备句柄 */ -uint32_t port = 3; /* UART设备端口号 */ handle = UartOpen(port); if (handle == NULL) { - HDF_LOGE("UartOpen: failed!\n"); + HDF_LOGE("UartOpen: open uart_%u failed!\n", port); return; } ``` - -### UART设置波特率 +#### UART设置波特率 在通信之前,需要设置UART的波特率,设置波特率的函数如下所示: - -``` +```c int32_t UartSetBaud(DevHandle handle, uint32_t baudRate); ``` - **表3** UartSetBaud参数和返回值描述 +**表3** UartSetBaud参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| baudRate | 待设置的波特率值 | -| **返回值** | **返回值描述** | -| 0 | UART设置波特率成功 | -| 负数 | UART设置波特率失败 | +| handle | UART设备句柄 | +| baudRate | 待设置的波特率值 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | UART设置波特率成功 | +| 负数 | UART设置波特率失败 | 假设需要设置的UART波特率为9600,设置波特率的实例如下: - -``` +```c int32_t ret; -/* 设置UART波特率 */ -ret = UartSetBaud(handle, 9600); -if (ret != 0) { + +ret = UartSetBaud(handle, 9600); // 设置UART波特率 +if (ret != HDF_SUCCESS) { HDF_LOGE("UartSetBaud: failed, ret %d\n", ret); + return ret; } ``` - -### UART获取波特率 +#### UART获取波特率 设置UART的波特率后,可以通过获取波特率接口来查看UART当前的波特率,获取波特率的函数如下所示: - -``` +```c int32_t UartGetBaud(DevHandle handle, uint32_t *baudRate); ``` - **表4** UartGetBaud参数和返回值描述 +**表4** UartGetBaud参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| baudRate | 接收波特率值的指针 | -| **返回值** | **返回值描述** | -| 0 | UART获取波特率成功 | -| 负数 | UART获取波特率失败 | +| handle | UART设备句柄 | +| baudRate | 接收波特率值的指针 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | UART获取波特率成功 | +| 负数 | UART获取波特率失败 | 获取波特率的实例如下: - -``` +```c int32_t ret; uint32_t baudRate; -/* 获取UART波特率 */ -ret = UartGetBaud(handle, &baudRate); -if (ret != 0) { + +ret = UartGetBaud(handle, &baudRate); // 获取UART波特率 +if (ret != HDF_SUCCESS) { HDF_LOGE("UartGetBaud: failed, ret %d\n", ret); + return ret; } ``` +#### UART设置设备属性 -### UART设置设备属性 - -在通信之前,需要设置UART的设备属性,设置设备属性的函数如下图所示: +在通信之前,需要设置UART的设备属性,设置设备属性的函数如下所示: - -``` -int32_t UartSetAttribute(DevHandle handle, struct UartAttribute *attribute); +```c +int32_t UartSetAttribute(DevHandle handle, struct UartAttribute *attribute); ``` - **表5** UartSetAttribute参数和返回值描述 +**表5** UartSetAttribute参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| attribute | 待设置的设备属性 | -| **返回值** | **返回值描述** | -| 0 | UART设置设备属性成功 | -| 负数 | UART设置设备属性失败 | +| handle | UART设备句柄 | +| attribute | 待设置的设备属性 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | UART设置设备属性成功 | +| 负数 | UART设置设备属性失败 | 设置UART的设备属性的实例如下: - -``` +```c int32_t ret; struct UartAttribute attribute; -attribute.dataBits = UART_ATTR_DATABIT_7; /* UART传输数据位宽,一次传输7个bit */ -attribute.parity = UART_ATTR_PARITY_NONE; /* UART传输数据无校检 */ -attribute.stopBits = UART_ATTR_STOPBIT_1; /* UART传输数据停止位为1位 */ -attribute.rts = UART_ATTR_RTS_DIS; /* UART禁用RTS */ -attribute.cts = UART_ATTR_CTS_DIS; /* UART禁用CTS */ -attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; /* UART使能RX FIFO */ -attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; /* UART使能TX FIFO */ -/* 设置UART设备属性 */ -ret = UartSetAttribute(handle, &attribute); -if (ret != 0) { + +attribute.dataBits = UART_ATTR_DATABIT_7; // UART传输数据位宽,一次传输7个bit +attribute.parity = UART_ATTR_PARITY_NONE; // UART传输数据无校检 +attribute.stopBits = UART_ATTR_STOPBIT_1; // UART传输数据停止位为1位 +attribute.rts = UART_ATTR_RTS_DIS; // UART禁用RTS +attribute.cts = UART_ATTR_CTS_DIS; // UART禁用CTS +attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; // UART使能RX FIFO +attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; // UART使能TX FIFO + +ret = UartSetAttribute(handle, &attribute); // 设置UART设备属性 +if (ret != HDF_SUCCESS) { HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret); +turn ret; } ``` +#### UART获取设备属性 -### UART获取设备属性 - -设置UART的设备属性后,可以通过获取设备属性接口来查看UART当前的设备属性,获取设备属性的函数如下图所示: +设置UART的设备属性后,可以通过获取设备属性接口来查看UART当前的设备属性,获取设备属性的函数如下所示: - -``` +```c int32_t UartGetAttribute(DevHandle handle, struct UartAttribute *attribute); ``` - **表6** UartGetAttribute参数和返回值描述 +**表6** UartGetAttribute参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| attribute | 接收UART设备属性的指针 | -| **返回值** | **返回值描述** | -| 0 | UART获取设备属性成功 | -| 负数 | UART获取设备属性失败 | +| handle | UART设备句柄 | +| attribute | 接收UART设备属性的指针 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | UART获取设备属性成功 | +| 负数 | UART获取设备属性失败 | 获取UART的设备属性的实例如下: - -``` +```c int32_t ret; struct UartAttribute attribute; -/* 获取UART设备属性 */ -ret = UartGetAttribute(handle, &attribute); -if (ret != 0) { + +ret = UartGetAttribute(handle, &attribute); // 获取UART设备属性 +if (ret != HDF_SUCCESS) { HDF_LOGE("UartGetAttribute: failed, ret %d\n", ret); + return ret; } ``` +#### 设置UART传输模式 -### 设置UART传输模式 - -在通信之前,需要设置UART的传输模式,设置传输模式的函数如下图所示: +在通信之前,需要设置UART的传输模式,设置传输模式的函数如下所示: - -``` -int32_t UartSetTransMode(DevHandle handle, enum UartTransMode mode); +```c +int32_t UartSetTransMode(DevHandle handle, enum UartTransMode mode); ``` - **表7** UartSetTransMode参数和返回值描述 +**表7** UartSetTransMode参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| mode | 待设置的传输模式, | -| **返回值** | **返回值描述** | -| 0 | UART设置传输模式成功 | -| 负数 | UART设置传输模式失败 | +| handle | UART设备句柄 | +| mode | 待设置的传输模式, | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | UART设置传输模式成功 | +| 负数 | UART设置传输模式失败 | 假设需要设置的UART传输模式为UART_MODE_RD_BLOCK,设置传输模式的实例如下: - -``` +```c int32_t ret; -/* 设置UART传输模式 */ -ret = UartSetTransMode(handle, UART_MODE_RD_BLOCK); -if (ret != 0) { + +ret = UartSetTransMode(handle, UART_MODE_RD_BLOCK); // 设置UART传输模式 +if (ret != HDF_SUCCESS) { HDF_LOGE("UartSetTransMode: failed, ret %d\n", ret); + return ret; } ``` - -### 向UART设备写入指定长度的数据 +#### 向UART设备写入指定长度的数据 对应的接口函数如下所示: - -``` +```c int32_t UartWrite(DevHandle handle, uint8_t *data, uint32_t size); ``` - **表8** UartWrite参数和返回值描述 +**表8** UartWrite参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| data | 待写入数据的指针 | -| size | 待写入数据的长度 | -| **返回值** | **返回值描述** | -| 0 | UART写数据成功 | -| 负数 | UART写数据失败 | +| handle | UART设备句柄 | +| data | 待写入数据的指针 | +| size | 待写入数据的长度 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | UART写数据成功 | +| 负数 | UART写数据失败 | 写入指定长度数据的实例如下: - -``` +```c int32_t ret; uint8_t wbuff[5] = {1, 2, 3, 4, 5}; -/* 向UART设备写入指定长度的数据 */ -ret = UartWrite(handle, wbuff, 5); -if (ret != 0) { + +ret = UartWrite(handle, wbuff, 5); // 向UART设备写入指定长度的数据 +if (ret != HDF_SUCCESS) { HDF_LOGE("UartWrite: failed, ret %d\n", ret); + return ret; } ``` - -### 从UART设备中读取指定长度的数据 +#### 从UART设备中读取指定长度的数据 对应的接口函数如下所示: - -``` +```c int32_t UartRead(DevHandle handle, uint8_t *data, uint32_t size); ``` - **表9** UartRead参数和返回值描述 +**表9** UartRead参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | -| data | 接收读取数据的指针 | -| size | 待读取数据的长度 | -| **返回值** | **返回值描述** | -| 非负数 | UART读取到的数据长度 | -| 负数 | UART读取数据失败 | +| handle | UART设备句柄 | +| data | 接收读取数据的指针 | +| size | 待读取数据的长度 | +| **返回值** | **返回值描述** | +| 非负数 | UART读取到的数据长度 | +| 负数 | UART读取数据失败 | 读取指定长度数据的实例如下: - -``` +```c int32_t ret; uint8_t rbuff[5] = {0}; -/* 从UART设备读取指定长度的数据 */ -ret = UartRead(handle, rbuff, 5); + +ret = UartRead(handle, rbuff, 5); // 从UART设备读取指定长度的数据 if (ret < 0) { HDF_LOGE("UartRead: failed, ret %d\n", ret); + return ret; } ``` @@ -330,94 +352,115 @@ if (ret < 0) { > UART返回值为非负值,表示UART读取成功。若返回值等于0,表示UART无有效数据可以读取。若返回值大于0,表示实际读取到的数据长度,该长度小于或等于传入的参数size的大小,并且不超过当前正在使用的UART控制器规定的最大单次读取数据长度的值。 -### 销毁UART设备句柄 +#### 销毁UART设备句柄 UART通信完成之后,需要销毁UART设备句柄,函数如下所示: - -``` +```c void UartClose(DevHandle handle); ``` 该函数会释放申请的资源。 - **表10** UartClose参数和返回值描述 +**表10** UartClose参数和返回值描述 -| 参数 | 参数描述 | +| 参数 | 参数描述 | | -------- | -------- | -| handle | UART设备句柄 | +| handle | UART设备句柄 | 销毁UART设备句柄的实例如下: - -``` -UartClose(handle); /* 销毁UART设备句柄 * +```c +UartClose(handle); // 销毁UART设备句柄 ``` - ## 使用实例 - UART设备完整的使用示例如下所示,首先获取UART设备句柄,接着设置波特率、设备属性和传输模式,之后进行UART通信,最后销毁UART设备句柄。 - -``` +下面将基于Hi3516DV300开发板展示使用UART完整操作,步骤主要如下: + +1. 传入UART端口号num,打开端口号对应的UART设备并获得UART设备句柄。 +2. 通过UART设备句柄及设置的波特率,设置UART设备的波特率。 +3. 通过UART设备句柄及待获取的波特率,获取UART设备的波特率。 +4. 通过UART设备句柄及待设置的设备属性,设置UART设备的设备属性。 +5. 通过UART设备句柄及待获取的设备属性,获取UART设备的设备属性。 +6. 通过UART设备句柄及待设置的传输模式,设置UART设备的传输模式。 +7. 通过UART设备句柄及待传输的数据及大小,传输指定长度的数据。 +8. 通过UART设备句柄及待接收的数据及大小,接收指定长度的数据。 +9. 通过UART设备句柄,关闭UART设备。 + +```c #include "hdf_log.h" #include "uart_if.h" void UartTestSample(void) { int32_t ret; - uint32_t port; + uint32_t port; + uint32_t baud; DevHandle handle = NULL; uint8_t wbuff[5] = { 1, 2, 3, 4, 5 }; uint8_t rbuff[5] = { 0 }; struct UartAttribute attribute; - attribute.dataBits = UART_ATTR_DATABIT_7; /* UART传输数据位宽,一次传输7个bit */ - attribute.parity = UART_ATTR_PARITY_NONE; /* UART传输数据无校检 */ - attribute.stopBits = UART_ATTR_STOPBIT_1; /* UART传输数据停止位为1位 */ - attribute.rts = UART_ATTR_RTS_DIS; /* UART禁用RTS */ - attribute.cts = UART_ATTR_CTS_DIS; /* UART禁用CTS */ - attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; /* UART使能RX FIFO */ - attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; /* UART使能TX FIFO */ - /* UART设备端口号,要填写实际平台上的端口号 */ - port = 1; - /* 获取UART设备句柄 */ - handle = UartOpen(port); + + attribute.dataBits = UART_ATTR_DATABIT_7; // UART传输数据位宽,一次传输7个bit + attribute.parity = UART_ATTR_PARITY_NONE; // UART传输数据无校检 + attribute.stopBits = UART_ATTR_STOPBIT_1; // UART传输数据停止位为1位 + attribute.rts = UART_ATTR_RTS_DIS; // UART禁用RTS + attribute.cts = UART_ATTR_CTS_DIS; // UART禁用CTS + attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; // UART使能RX FIFO + attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; // UART使能TX FIFO + + port = 1; // UART设备端口号,要填写实际平台上的端口号 + + handle = UartOpen(port); // 获取UART设备句柄 if (handle == NULL) { - HDF_LOGE("UartOpen: failed!\n"); + HDF_LOGE("UartOpen: open uart_%u failed!\n", port); return; } - /* 设置UART波特率为9600 */ - ret = UartSetBaud(handle, 9600); - if (ret != 0) { - HDF_LOGE("UartSetBaud: failed, ret %d\n", ret); - goto _ERR; + + ret = UartSetBaud(handle, 9600); // 设置UART波特率为9600 + if (ret != HDF_SUCCESS) { + HDF_LOGE("UartSetBaud: set baud failed, ret %d\n", ret); + goto ERR; } - /* 设置UART设备属性 */ - ret = UartSetAttribute(handle, &attribute); - if (ret != 0) { - HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret); - goto _ERR; + + ret = UartGetBaud(handle, &baud); // 获取UART波特率 + if (ret != HDF_SUCCESS) { + HDF_LOGE("UartGetBaud: get baud failed, ret %d\n", ret); + goto ERR; } - /* 设置UART传输模式为非阻塞模式 */ - ret = UartSetTransMode(handle, UART_MODE_RD_NONBLOCK); - if (ret != 0) { - HDF_LOGE("UartSetTransMode: failed, ret %d\n", ret); - goto _ERR; + + ret = UartSetAttribute(handle, &attribute); // 设置UART设备属性 + if (ret != HDF_SUCCESS) { + HDF_LOGE("UartSetAttribute: set attribute failed, ret %d\n", ret); + goto ERR; } - /* 向UART设备写入5字节的数据 */ - ret = UartWrite(handle, wbuff, 5); - if (ret != 0) { - HDF_LOGE("UartWrite: failed, ret %d\n", ret); - goto _ERR; + + ret = UartGetAttribute(handle, &attribute); // 获取UART设备属性 + if (ret != HDF_SUCCESS) { + HDF_LOGE("UartGetAttribute: get attribute failed, ret %d\n", ret); + goto ERR; } - /* 从UART设备读取5字节的数据 */ - ret = UartRead(handle, rbuff, 5); + + ret = UartSetTransMode(handle, UART_MODE_RD_NONBLOCK); // 设置UART传输模式为非阻塞模式 + if (ret != HDF_SUCCESS) { + HDF_LOGE("UartSetTransMode: set trans mode failed, ret %d\n", ret); + goto ERR; + } + + ret = UartWrite(handle, wbuff, 5); // 向UART设备写入5字节的数据 + if (ret != HDF_SUCCESS) { + HDF_LOGE("UartWrite: write data failed, ret %d\n", ret); + goto ERR; + } + + ret = UartRead(handle, rbuff, 5); // 从UART设备读取5字节的数据 if (ret < 0) { - HDF_LOGE("UartRead: failed, ret %d\n", ret); - goto _ERR; + HDF_LOGE("UartRead: read data failed, ret %d\n", ret); + goto ERR; } -_ERR: - /* 销毁UART设备句柄 */ - UartClose(handle); +ERR: + UartClose(handle); // 销毁UART设备句柄 + return ret; } ``` diff --git a/zh-cn/device-dev/driver/driver-platform-uart-develop.md b/zh-cn/device-dev/driver/driver-platform-uart-develop.md index 29495e8eec5394b09e1d0a9446575abd59a097e3..cff8e0e2b1c72bd1b9ad3e2ed2750e8a83ed89d7 100755 --- a/zh-cn/device-dev/driver/driver-platform-uart-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-uart-develop.md @@ -1,299 +1,334 @@ # UART - ## 概述 -在HDF框架中,UART(Universal Asynchronous Receiver/Transmitter,通用异步收发传输器)的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 - **图1** UART独立服务模式结构图 +UART指异步收发传输器(Universal Asynchronous Receiver/Transmitter),是通用串行数据总线,用于异步通信。该总线双向通信,可以实现全双工传输。 - ![image](figures/独立服务模式结构图.png "UART独立服务模式结构图") +两个UART设备的连接示意图如下,UART与其他模块一般用2线(图1)或4线(图2)相连,它们分别是: + - TX:发送数据端,和对端的RX相连。 + - RX:接收数据端,和对端的TX相连。 + - RTS:发送请求信号,用于指示本设备是否准备好,可接受数据,和对端CTS相连。 + - CTS:允许发送信号,用于判断是否可以向对端发送数据,和对端RTS相连。 -## 接口说明 +**图1** 2线UART设备连接示意图 -UartHostMethod定义: +![image1](figures/2线UART设备连接示意图.png "2线UART设备连接示意图") - -``` -struct UartHostMethod { - int32_t (*Init)(struct UartHost *host); - int32_t (*Deinit)(struct UartHost *host); - int32_t (*Read)(struct UartHost *host, uint8_t *data, uint32_t size); - int32_t (*Write)(struct UartHost *host, uint8_t *data, uint32_t size); - int32_t (*GetBaud)(struct UartHost *host, uint32_t *baudRate); - int32_t (*SetBaud)(struct UartHost *host, uint32_t baudRate); - int32_t (*GetAttribute)(struct UartHost *host, struct UartAttribute *attribute); - int32_t (*SetAttribute)(struct UartHost *host, struct UartAttribute *attribute); - int32_t (*SetTransMode)(struct UartHost *host, enum UartTransMode mode); - int32_t (*pollEvent)(struct UartHost *host, void *filep, void *table); -}; -``` +**图2** 4线UART设备连接示意图 - **表1** UartHostMethod结构体成员的回调函数功能说明 +![image2](figures/4线UART设备连接示意图.png "4线UART设备连接示意图") -| 函数 | 入参 | 出参 | 返回值 | 功能 | -| -------- | -------- | -------- | -------- | -------- | -| Init | host:结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 初始化Uart设备 | -| Deinit | host:结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 去初始化Uart设备 | -| Read | host:结构体指针,核心层UART控制器
size:uint32_t,数据大小 | data:uint8_t指针,传出的数据 | HDF_STATUS相关状态 | 接收数据RX | -| Write | host:结构体指针,核心层UART控制器
data:uint8_t指针,传入数据
size:uint32_t,数据大小 | 无 | HDF_STATUS相关状态 | 发送数据TX | -| SetBaud | host:结构体指针,核心层UART控制器
baudRate:uint32_t指针,波特率传入值 | 无 | HDF_STATUS相关状态 | 设置波特率 | -| GetBaud | host:结构体指针,核心层UART控制器 | baudRate:uint32_t指针,传出的波特率 | HDF_STATUS相关状态 | 获取当前设置的波特率 | -| GetAttribute | host:结构体指针,核心层UART控制器 | attribute:结构体指针,传出的属性值(见uart_if.h中UartAttribute定义) | HDF_STATUS相关状态 | 获取设备uart相关属性 | -| SetAttribute | host:结构体指针,核心层UART控制器
attribute:结构体指针,属性传入值 | 无 | HDF_STATUS相关状态 | 设置设备UART相关属性 | -| SetTransMode | host:结构体指针,核心层UART控制器
mode:枚举值(见uart_if.h中UartTransMode定义),传输模式 | 无 | HDF_STATUS相关状态 | 设置传输模式 | -| PollEvent | host:结构体指针,核心层UART控制器
filep:void指针file
table:void指针poll_table | 无 | HDF_STATUS相关状态 | poll机制 | +UART通信之前,收发双方需要约定好一些参数:波特率、数据格式(起始位、数据位、校验位、停止位)等。通信过程中,UART通过TX发送给对端数据,通过RX接收对端发送的数据。当UART接收缓存达到预定的门限值时,RTS变为不可发送数据,对端的CTS检测到不可发送数据,则停止发送数据。 +### 基本概念 -## 开发步骤 +- 异步通信 -UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 + 异步通信中,数据通常以字符或者字节为单位组成字符帧传送。字符帧由发送端逐帧发送,通过传输线被接收设备逐帧接收。发送端和接收端可以由各自的时钟来控制数据的发送和接收,这两个时钟源彼此独立,互不同步。异步通信以一个字符为传输单位,通信中两个字符间的时间间隔是不固定的,然而在同一个字符中的两个相邻位代码间的时间间隔是固定的。 -1. 实例化驱动入口 - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 +- 全双工传输(Full Duplex) -2. 配置属性文件 - - 在device_info.hcs文件中添加deviceNode描述。 - - 【可选】添加uart_config.hcs器件属性文件。 + 此通信模式允许数据在两个方向上同时传输,它在能力上相当于两个单工通信方式的结合。全双工可以同时进行信号的双向传输。 -3. 实例化UART控制器对象 - - 初始化UartHost成员。 - - 实例化UartHost成员UartHostMethod。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
- > 实例化UartHost成员UartHostMethod,其定义和成员说明见[接口说明](#接口说明)。 +### 运作机制 + +在HDF框架中,UART接口适配模式采用独立服务模式(如图3所示)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 + +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 + +UART模块各分层作用: + +- 接口层提供打开UART设备、UART设备读取指定长度数据、UART设备写入指定长度数据、设置UART设备波特率、获取设UART设备波特率、设置UART设备属性、获取UART设备波特率、设置UART设备传输模式、关闭UART设备的接口。 +- 核心层主要提供看UART控制器的创建、移除以及管理的能力,通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 + +**图3** UART独立服务模式结构图 + +![image3](figures/独立服务模式结构图.png "UART独立服务模式结构图") + +## 开发指导 + +### 场景介绍 -4. 驱动调试 +UART模块应用比较广泛,主要用于实现设备之间的低速串行通信,例如输出打印信息,当然也可以外接各种模块,如GPS、蓝牙等。当驱动开发者需要将UART设备适配到OpenHarmony时,需要进行UART驱动适配。下文将介绍如何进行UART驱动适配。 - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如UART控制状态,中断响应情况等。 +### 接口说明 +为了保证上层在调用UART接口时能够正确的操作UART控制器,核心层在//drivers/hdf_core/framework/support/platform/include/uart/uart_core.h中定义了以下钩子函数,驱动适配者需要在适配层实现这些函数的具体功能,并与钩子函数挂接,从而完成适配层与核心层的交互。 -## 开发实例 +UartHostMethod定义: + +```c +struct UartHostMethod { + int32_t (*Init)(struct UartHost *host); + int32_t (*Deinit)(struct UartHost *host); + int32_t (*Read)(struct UartHost *host, uint8_t *data, uint32_t size); + int32_t (*Write)(struct UartHost *host, uint8_t *data, uint32_t size); + int32_t (*GetBaud)(struct UartHost *host, uint32_t *baudRate); + int32_t (*SetBaud)(struct UartHost *host, uint32_t baudRate); + int32_t (*GetAttribute)(struct UartHost *host, struct UartAttribute *attribute); + int32_t (*SetAttribute)(struct UartHost *host, struct UartAttribute *attribute); + int32_t (*SetTransMode)(struct UartHost *host, enum UartTransMode mode); + int32_t (*pollEvent)(struct UartHost *host, void *filep, void *table); +}; +``` + +**表1** UartHostMethod结构体成员的回调函数功能说明 + +| 函数 | 入参 | 出参 | 返回值 | 功能 | +| -------- | -------- | -------- | -------- | -------- | +| Init | host:结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 初始化Uart设备 | +| Deinit | host:结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 去初始化Uart设备 | +| Read | host:结构体指针,核心层UART控制器
size:uint32_t类型,接收数据大小 | data:uint8_t类型指针,接收的数据 | HDF_STATUS相关状态 | 接收数据RX | +| Write | host:结构体指针,核心层UART控制器
data:uint8_t类型指针,传入数据
size:uint32_t类型,发送数据大小 | 无 | HDF_STATUS相关状态 | 发送数据TX | +| SetBaud | host:结构体指针,核心层UART控制器
baudRate:uint32_t类型,波特率传入值 | 无 | HDF_STATUS相关状态 | 设置波特率 | +| GetBaud | host:结构体指针,核心层UART控制器 | baudRate:uint32_t类型指针,传出的波特率 | HDF_STATUS相关状态 | 获取当前设置的波特率 | +| GetAttribute | host:结构体指针,核心层UART控制器 | attribute:结构体指针,传出的属性值(见uart_if.h中UartAttribute定义) | HDF_STATUS相关状态 | 获取设备uart相关属性 | +| SetAttribute | host:结构体指针,核心层UART控制器
attribute:结构体指针,属性传入值 | 无 | HDF_STATUS相关状态 | 设置设备UART相关属性 | +| SetTransMode | host:结构体指针,核心层UART控制器
mode:枚举值(见uart_if.h中UartTransMode定义),传输模式 | 无 | HDF_STATUS相关状态 | 设置传输模式 | +| PollEvent | host:结构体指针,核心层UART控制器
filep:void类型指针file
table:void类型指针table | 无 | HDF_STATUS相关状态 | poll轮询机制 | + +### 开发步骤 -下方将以uart_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 +UART模块适配HDF框架包含以下四个步骤: -1. 驱动开发首先需要实例化驱动入口。 +- 实例化驱动入口。 +- 配置属性文件。 +- 实例化UART控制器对象。 +- 驱动调试。 - 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 +### 开发实例 - HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +下方将基于Hi3516DV300开发板以//device_soc_hisilicon/common/platform/uart/uart_hi35xx.c驱动为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 +1. 实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - UART驱动入口参考: - - ``` + UART驱动入口开发参考: + + ```c struct HdfDriverEntry g_hdfUartDevice = { .moduleVersion = 1, - .moduleName = "HDF_PLATFORM_UART",// 【必要且与HCS里面的名字匹配】 - .Bind = HdfUartDeviceBind, // 见Bind参考 - .Init = HdfUartDeviceInit, // 见Init参考 - .Release = HdfUartDeviceRelease, // 见Release参考 + .moduleName = "HDF_PLATFORM_UART", // 【必要且与HCS文件中里面的moduleName匹配】 + .Bind = HdfUartDeviceBind, // 见Bind参考 + .Init = HdfUartDeviceInit, // 见Init参考 + .Release = HdfUartDeviceRelease, // 见Release参考 }; - //调用HDF_INIT将驱动入口注册到HDF框架中 - HDF_INIT(g_hdfUartDevice); + HDF_INIT(g_hdfUartDevice); //调用HDF_INIT将驱动入口注册到HDF框架中 ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在uart_config.hcs中配置器件属性。 - - deviceNode信息与驱动入口注册相关,器件属性值与核心层UartHost成员的默认值或限制范围有密切关系。 +2. 配置属性文件。 - 本例只有一个UART控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在uart_config文件中增加对应的器件属性。 + 完成驱动入口注册之后,需要在device_info.hcs文件中添加deviceNode信息,deviceNode信息与驱动入口注册相关。本例以两个UART控制器为例,如有多个器件信息,则需要在device_info.hcs文件增加对应的deviceNode信息。器件属性值与核心层UartHost成员的默认值或限制范围有密切关系,比如UART设备端口号,需要在uart_config.hcs文件中增加对应的器件属性。 - device_info.hcs 配置参考: - - - ``` - root { - device_info { - match_attr = "hdf_manager"; - platform :: host { - hostName = "platform_host"; - priority = 50; - device_uart :: device { - device0 :: deviceNode { - policy = 1; // 驱动服务发布的策略,policy大于等于1(用户态可见为2,仅内核态可见为1)。 - priority = 40; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_UART"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 - serviceName = "HDF_PLATFORM_UART_0"; // 驱动对外发布服务的名称,必须唯一,必须要按照HDF_PLATFORM_UART_X的格式,X为UART控制器编号。 - deviceMatchAttr = "hisilicon_hi35xx_uart_0";// 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值一致。 - } - device1 :: deviceNode { - policy = 2; - permission = 0644; - priority = 40; - moduleName = "HDF_PLATFORM_UART"; - serviceName = "HDF_PLATFORM_UART_1"; - deviceMatchAttr = "hisilicon_hi35xx_uart_1"; - } - ... - } - } - } - } - ``` - + + 在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + + ```c + root { + device_info { + match_attr = "hdf_manager"; + platform :: host { + hostName = "platform_host"; + priority = 50; + device_uart :: device { + device0 :: deviceNode { + policy = 1; // 驱动服务发布的策略,policy大于等于1(用户态可见为2,仅内核态可见为1)。 + priority = 40; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "HDF_PLATFORM_UART"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 + serviceName = "HDF_PLATFORM_UART_0"; // 驱动对外发布服务的名称,必须唯一,必须要按照HDF_PLATFORM_UART_X的格式,X为UART控制器编号。 + deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值一致。 + } + device1 :: deviceNode { + policy = 2; + permission = 0644; + priority = 40; + moduleName = "HDF_PLATFORM_UART"; + serviceName = "HDF_PLATFORM_UART_1"; + deviceMatchAttr = "hisilicon_hi35xx_uart_1"; + } + ... + } + } + } + } + ``` + - uart_config.hcs 配置参考: - - - ``` - root { - platform { - template uart_controller {// 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 - match_attr = ""; - num = 0; // 【必要】设备号 - baudrate = 115200; // 【必要】波特率,数值可按需填写 - fifoRxEn = 1; // 【必要】使能接收FIFO - fifoTxEn = 1; // 【必要】使能发送FIFO - flags = 4; // 【必要】标志信号 - regPbase = 0x120a0000; // 【必要】地址映射需要 - interrupt = 38; // 【必要】中断号 - iomemCount = 0x48; // 【必要】地址映射需要 - } - controller_0x120a0000 :: uart_controller { - match_attr = "hisilicon_hi35xx_uart_0";// 【必要】必须和device_info.hcs中对应的设备的deviceMatchAttr值一致 - } - controller_0x120a1000 :: uart_controller { - num = 1; - baudrate = 9600; - regPbase = 0x120a1000; - interrupt = 39; - match_attr = "hisilicon_hi35xx_uart_1"; - } - ... - // 【可选】可新增,但需要在 device_info.hcs 添加对应的节点 - } - } - ``` - -3. 完成属性文件配置之后,下一步就是以核心层UartHost对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化UartHost成员UartHostMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - - - 自定义结构体参考 - - 从驱动的角度看,自定义结构体是参数和数据的载体,而且uart_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号等。 - - + + 在//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/uart/uart_config.hcs文件配置器件属性,其中配置参数如下: + + ```c + root { + platform { + template uart_controller { // 配置模板,如果下面节点使用时继承该模板,则节点中未声明的字段会使用该模板中的默认值 + match_attr = ""; + num = 0; // 【必要】端口号 + baudrate = 115200; // 【必要】波特率,数值可按需填写 + fifoRxEn = 1; // 【必要】使能接收FIFO + fifoTxEn = 1; // 【必要】使能发送FIFO + flags = 4; // 【必要】标志信号 + regPbase = 0x120a0000; // 【必要】地址映射需要 + interrupt = 38; // 【必要】中断号 + iomemCount = 0x48; // 【必要】地址映射需要 + } + controller_0x120a0000 :: uart_controller { + match_attr = "hisilicon_hi35xx_uart_0"; // 【必要】必须和device_info.hcs中对应的设备的deviceMatchAttr值一致 + } + controller_0x120a1000 :: uart_controller { + num = 1; + baudrate = 9600; + regPbase = 0x120a1000; + interrupt = 39; + match_attr = "hisilicon_hi35xx_uart_1"; + } + ... // 如果存在多个UART设备时【必须】添加节点,否则不用 + } + } ``` - struct UartPl011Port { // 接口相关的结构体 - int32_t enable; - unsigned long physBase; // 物理地址 - uint32_t irqNum; // 中断号 - uint32_t defaultBaudrate;// 默认波特率 - uint32_t flags; // 标志信号,下面三个宏与之相关。 + + 需要注意的是,新增uart_config.hcs配置文件后,必须在产品对应的hdf.hcs文件中将其包含如下语句所示,否则配置文件无法生效。 + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/uart/uart_config.hcs" // 配置文件相对路径 + ``` + +3. 实例化UART控制器对象。 + + 完成属性文件配置之后,下一步就是以核心层UartHost对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化UartHost成员UartHostMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + + - 驱动适配者自定义结构体参考 + + 从驱动的角度看,驱动适配者自定义结构体是参数和数据的载体,而且uart_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如端口号。 + + ```c + struct UartPl011Port { // 驱动适配者自定义管脚描述结构体 + int32_t enable; + unsigned long physBase; // 物理地址 + uint32_t irqNum; // 中断号 + uint32_t defaultBaudrate; // 默认波特率 + uint32_t flags; // 标志信号,下面三个宏与之相关 #define PL011_FLG_IRQ_REQUESTED (1 << 0) #define PL011_FLG_DMA_RX_REQUESTED (1 << 1) #define PL011_FLG_DMA_TX_REQUESTED (1 << 2) - struct UartDmaTransfer *rxUdt; // DMA传输相关 - struct UartDriverData *udd; // 见下 + struct UartDmaTransfer *rxUdt; // DMA传输相关 + struct UartDriverData *udd; }; - struct UartDriverData { // 数据传输相关的结构体 - uint32_t num; - uint32_t baudrate; // 波特率(可设置) - struct UartAttribute attr; // 数据位、停止位等传输属性相关。 - struct UartTransfer *rxTransfer; // 缓冲区相关,可理解为FIFO结构。 - wait_queue_head_t wait; // 条件变量相关的排队等待信号 - int32_t count; // 数据数量 - int32_t state; // UART控制器状态 + struct UartDriverData { // 数据传输相关的结构体 + uint32_t num; // 端口号 + uint32_t baudrate; // 波特率(可设置) + struct UartAttribute attr; // 数据位、停止位等传输属性相关 + struct UartTransfer *rxTransfer; // 缓冲区相关,可理解为FIFO结构 + wait_queue_head_t wait; // 条件变量相关的排队等待信号 + int32_t count; // 数据数量 + int32_t state; // UART控制器状态 #define UART_STATE_NOT_OPENED 0 #define UART_STATE_OPENING 1 #define UART_STATE_USEABLE 2 #define UART_STATE_SUSPENDED 3 - uint32_t flags; // 状态标志 + uint32_t flags; // 状态标志 #define UART_FLG_DMA_RX (1 << 0) #define UART_FLG_DMA_TX (1 << 1) #define UART_FLG_RD_BLOCK (1 << 2) - RecvNotify recv; // 函数指针类型,指向串口数据接收函数。 - struct UartOps *ops; // 自定义函数指针结构体,详情见device/hisilicon/drivers/uart/uart_pl011.c。 - void *private; // 一般用来存储UartPl011Port首地址,方便调用。 + RecvNotify recv; // 函数指针类型,指向串口数据接收函数 + struct UartOps *ops; // 自定义函数指针结构体 + void *private; // 私有数据 }; // UartHost是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct UartHost { - struct IDeviceIoService service; - struct HdfDeviceObject *device; - uint32_t num; - OsalAtomic atom; - void *priv; // 一般存储厂商自定义结构体首地址,方便后者被调用。 - struct UartHostMethod *method; // 核心层钩子函数,厂商需要实现其成员函数功能并实例化。 + struct IDeviceIoService service; // 驱动服务 + struct HdfDeviceObject *device; // 驱动设备对象 + uint32_t num; // 端口号 + OsalAtomic atom; // 原子量 + void *priv; // 私有数据 + struct UartHostMethod *method; // 回调函数 }; ``` - - UartHost成员回调函数结构体UartHostMethod的实例化,其他成员在Bind函数中初始化。 + - UartHost成员回调函数结构体UartHostMethod的实例化,其中的成员在Init函数中初始化。 - - ``` + ```c // uart_hi35xx.c 中的示例:钩子函数的实例化 struct UartHostMethod g_uartHostMethod = { - .Init = Hi35xxInit, - .Deinit = Hi35xxDeinit, - .Read = Hi35xxRead, - .Write = Hi35xxWrite, - .SetBaud = Hi35xxSetBaud, - .GetBaud = Hi35xxGetBaud, - .SetAttribute = Hi35xxSetAttribute, - .GetAttribute = Hi35xxGetAttribute, - .SetTransMode = Hi35xxSetTransMode, - .pollEvent = Hi35xxPollEvent, + .Init = Hi35xxInit, // 初始化 + .Deinit = Hi35xxDeinit, // 去初始化 + .Read = Hi35xxRead, // 接收数据 + .Write = Hi35xxWrite, // 发送数据 + .SetBaud = Hi35xxSetBaud, // 设置波特率 + .GetBaud = Hi35xxGetBaud, // 获取波特率 + .SetAttribute = Hi35xxSetAttribute, // 设置设备属性 + .GetAttribute = Hi35xxGetAttribute, // 获取设备属性 + .SetTransMode = Hi35xxSetTransMode, // 设置传输模式 + .pollEvent = Hi35xxPollEvent, // 轮询 }; ``` - - Bind函数参考 + - Bind函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可参见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可参见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS中HDF_STATUS定义)。 - **表2** HDF_STATUS返回值说明 - - | 状态(值) | 问题描述 | + **表2** HDF_STATUS返回值说明 + + | 状态(值) | 问题描述 | | -------- | -------- | - | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_INVALID_PARAM | 参数非法 | - | HDF_ERR_IO | I/O 错误 | - | HDF_SUCCESS | 初始化成功 | - | HDF_FAILURE | 初始化失败 | + | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_INVALID_PARAM | 参数非法 | + | HDF_ERR_IO | I/O 错误 | + | HDF_SUCCESS | 初始化成功 | + | HDF_FAILURE | 初始化失败 | 函数说明: 初始化自定义结构体对象,初始化UartHost成员。 - - ``` + ```c //uart_hi35xx.c static int32_t HdfUartDeviceBind(struct HdfDeviceObject *device) { ... - return (UartHostCreate(device) == NULL) ? HDF_FAILURE : HDF_SUCCESS;// 【必须做】调用核心层函数UartHostCreate + return (UartHostCreate(device) == NULL) ? HDF_FAILURE : HDF_SUCCESS; // 【必须】调用核心层函数UartHostCreate } + // uart_core.c核心层UartHostCreate函数说明 struct UartHost *UartHostCreate(struct HdfDeviceObject *device) { - struct UartHost *host = NULL; // 新建UartHost - ... - host = (struct UartHost *)OsalMemCalloc(sizeof(*host));//分配内存 + struct UartHost *host = NULL; // 新建UartHost + ... + host = (struct UartHost *)OsalMemCalloc(sizeof(*host)); // 分配内存 ... - host->device = device; // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 - device->service = &(host->service); // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 - host->device->service->Dispatch = UartIoDispatch; // 为service成员的Dispatch方法赋值 - OsalAtomicSet(&host->atom, 0); // 原子量初始化或者原子量设置 + host->device = device; // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 + device->service = &(host->service); // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 + host->device->service->Dispatch = UartIoDispatch; // 为service成员的Dispatch方法赋值 + OsalAtomicSet(&host->atom, 0); // 原子量初始化或者原子量设置 host->priv = NULL; host->method = NULL; return host; } ``` - - Init函数参考 + - Init函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: @@ -301,48 +336,44 @@ UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置 函数说明: - 初始化自定义结构体对象,初始化UartHost成员,调用核心层UartAddDev函数,接入VFS。 - - - ``` + 初始化自定义结构体对象,初始化UartHost成员,调用核心层UartAddDev函数,完成UART控制器的添加,接入VFS。 + + ```c int32_t HdfUartDeviceInit(struct HdfDeviceObject *device) { int32_t ret; struct UartHost *host = NULL; HDF_LOGI("%s: entry", __func__); ... - host = UartHostFromDevice(device);// 通过service成员后强制转为UartHost,赋值是在Bind函数中。 - ... - ret = Hi35xxAttach(host, device); // 完成UartHost对象的初始化,见下。 - ... - host->method = &g_uartHostMethod; // UartHostMethod的实例化对象的挂载。 + host = UartHostFromDevice(device); // 通过service成员后强制转为UartHost,赋值是在Bind函数中 + ... + ret = Hi35xxAttach(host, device); // 完成UartHost对象的初始化,见下 + ... + host->method = &g_uartHostMethod; // UartHostMethod的实例化对象的挂载 return ret; } // 完成UartHost对象的初始化。 static int32_t Hi35xxAttach(struct UartHost *host, struct HdfDeviceObject *device) { int32_t ret; - // udd和port对象是厂商自定义的结构体对象,可根据需要实现相关功能。 - struct UartDriverData *udd = NULL; + struct UartDriverData *udd = NULL; // udd和port对象是驱动适配者自定义的结构体对象,可根据需要实现相关功能 struct UartPl011Port *port = NULL; ... // 【必要】步骤【1】~【7】主要实现对udd对象的实例化赋值,然后赋值给核心层UartHost对象。 - udd = (struct UartDriverData *)OsalMemCalloc(sizeof(*udd));//【1】 + udd = (struct UartDriverData *)OsalMemCalloc(sizeof(*udd)); // 【1】 ... - port = (struct UartPl011Port *)OsalMemCalloc(sizeof(struct UartPl011Port));//【2】 + port = (struct UartPl011Port *)OsalMemCalloc(sizeof(struct UartPl011Port)); // 【2】 ... - udd->ops = Pl011GetOps(); // 【3】设备开启、关闭、属性设置、发送操作等函数挂载。 - udd->recv = PL011UartRecvNotify;// 【4】数据接收通知函数(条件锁机制)挂载 - udd->count = 0; // 【5】 - port->udd = udd; // 【6】使UartPl011Port与UartDriverData可以相互转化的前提 - ret = UartGetConfigFromHcs(port, device->property);// 将HdfDeviceObject的属性传递给厂商自定义结构体 - // 用于相关操作,示例代码见下 + udd->ops = Pl011GetOps(); // 【3】设备开启、关闭、属性设置、发送操作等函数挂载。 + udd->recv = PL011UartRecvNotify; // 【4】数据接收通知函数(条件锁机制)挂载 + udd->count = 0; // 【5】 + port->udd = udd; // 【6】使UartPl011Port与UartDriverData可以相互转化的前提 + ret = UartGetConfigFromHcs(port, device->property); // 将HdfDeviceObject的属性传递给驱动适配者自定义结构体,用于相关操作,示例代码见下 ... - udd->private = port; //【7】 - - host->priv = udd; // 【必要】使UartHost与UartDriverData可以相互转化的前提 - host->num = udd->num; // 【必要】UART设备号 - UartAddDev(host); // 【必要】核心层uart_dev.c中的函数,作用:注册一个字符设备节点到vfs,这样从用户态可以通过这个虚拟文件节点访问UART。 + udd->private = port; // 【7】 + host->priv = udd; // 【必要】使UartHost与UartDriverData可以相互转化的前提 + host->num = udd->num; // 【必要】UART设备号 + UartAddDev(host); // 【必要】核心层uart_dev.c中的函数,作用:注册一个字符设备节点到vfs,这样从用户态可以通过这个虚拟文件节点访问UART return HDF_SUCCESS; } @@ -352,7 +383,7 @@ UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置 struct UartDriverData *udd = port->udd; struct DeviceResourceIface *iface = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); ... - // 通过请求参数提取相应的值,并赋值给厂商自定义的结构体。 + // 通过请求参数提取相应的值,并赋值给驱动适配者自定义的结构体。 if (iface->GetUint32(node, "num", &udd->num, 0) != HDF_SUCCESS) { HDF_LOGE("%s: read busNum fail", __func__); return HDF_FAILURE; @@ -361,11 +392,12 @@ UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置 return 0; } ``` - - Release函数参考 + + - Release函数开发参考 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: @@ -378,18 +410,17 @@ UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 - - ``` + ```c void HdfUartDeviceRelease(struct HdfDeviceObject *device) { struct UartHost *host = NULL; ... - host = UartHostFromDevice(device);// 这里有HdfDeviceObject到UartHost的强制转化,通过service成员,赋值见Bind函数。 - ... - if (host->priv != NULL) { - Hi35xxDetach(host); // 厂商自定义的内存释放函数,见下。 - } - UartHostDestroy(host); // 调用核心层函数释放host + host = UartHostFromDevice(device); // 这里有HdfDeviceObject到UartHost的强制转化,通过service成员,赋值见Bind函数。 + ... + if (host->priv != NULL) { + Hi35xxDetach(host); // 驱动适配自定义的内存释放函数,见下。 + } + UartHostDestroy(host); // 调用核心层函数释放host } static void Hi35xxDetach(struct UartHost *host) @@ -397,18 +428,22 @@ UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置 struct UartDriverData *udd = NULL; struct UartPl011Port *port = NULL; ... - udd = host->priv; // 这里有UartHost到UartDriverData的转化 - ... - UartRemoveDev(host); // VFS注销 - port = udd->private; // 这里有UartDriverData到UartPl011Port的转化 - if (port != NULL) { - if (port->physBase != 0) { - OsalIoUnmap((void *)port->physBase);// 地址反映射 + udd = host->priv; // 这里有UartHost到UartDriverData的转化 + ... + UartRemoveDev(host); // VFS注销 + port = udd->private; // 这里有UartDriverData到UartPl011Port的转化 + if (port != NULL) { + if (port->physBase != 0) { + OsalIoUnmap((void *)port->physBase); // 地址反映射 } OsalMemFree(port); udd->private = NULL; } - OsalMemFree(udd); // 释放UartDriverData + OsalMemFree(udd); // 释放UartDriverData host->priv = NULL; } ``` + +4. 驱动调试。 + + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-watchdog-des.md b/zh-cn/device-dev/driver/driver-platform-watchdog-des.md index 6f17e2593688016478c86da65f680a59e1ad4dcd..09a16a81fb094c6d65f7a4f1dbae1104f879480b 100644 --- a/zh-cn/device-dev/driver/driver-platform-watchdog-des.md +++ b/zh-cn/device-dev/driver/driver-platform-watchdog-des.md @@ -1,284 +1,296 @@ # Watchdog - ## 概述 -看门狗(Watchdog),又叫看门狗计时器(Watchdog timer),是一种硬件的计时设备。当系统主程序发生错误导致未及时清除看门狗计时器的计时值时,看门狗计时器就会对系统发出复位信号,使系统从悬停状态恢复到正常运作状态。 +### 功能简介 +看门狗(Watchdog),又称看门狗计时器(Watchdog timer),是一种硬件计时设备。一般有一个输入,叫做喂狗,一个输出到系统的复位端。当系统主程序发生错误导致未及时清除看门狗计时器的计时值时,看门狗计时器就会对系统发出复位信号,使系统从悬停状态恢复到正常运作状态。 -## 接口说明 +Watchdog接口定义了看门狗操作的通用方法集合,包括: - **表1** 看门狗API接口功能介绍 +- 打开/关闭看门狗设备 +- 启动/停止看门狗设备 +- 设置/获取看门狗设备超时时间 +- 获取看门狗设备状态 +- 喂狗 -| 接口 | 接口描述 | -| -------- | -------- | -| WatchdogOpen | 打开看门狗 | -| WatchdogClose | 关闭看门狗 | -| WatchdogStart | 启动看门狗 | -| WatchdogStop | 停止看门狗 | -| WatchdogSetTimeout | 设置看门狗超时时间 | -| WatchdogGetTimeout | 获取看门狗超时时间 | -| WatchdogGetStatus | 获取看门狗状态 | -| WatchdogFeed | 清除看门狗定时器(喂狗) | +### 基本概念 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 本文涉及的看门狗的所有接口,仅限内核态使用,不支持在用户态使用。 +系统正常工作的时候,每隔一段时间输出一个信号到喂狗端,给看门狗清零,这个操作就叫做喂狗。如果超过规定的时间不喂狗,看门狗定时超时,就会给出一个复位信号到系统,使系统复位。 +### 运作机制 -## 使用指导 +在HDF框架中,Watchdog模块接口适配模式采用独立服务模式,如图1所示。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: -### 使用流程 +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 -使用看门狗的一般流程如下图所示。 +Watchdog模块各分层作用: - **图1** 看门狗使用流程图 +- 接口层提供打开看门狗设备、获取看门狗设备状态、启动看门狗设备、设置看门狗设备超时时间、获取看门狗设备超时时间、喂狗、停止看门狗设备超时时间、关闭看门狗设备的接口。 +- 核心层主要提供看门狗控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 - ![image](figures/看门狗使用流程图.png "看门狗使用流程图") +**图 1** Watchdog独立服务模式结构图 +![image1](figures/独立服务模式结构图.png "Watchdog独立服务模式结构图") -### 打开看门狗设备 +## 使用指导 -在操作看门狗之前,需要使用WatchdogOpen打开一个看门狗设备,一个系统可能有多个看门狗,通过ID号来打开指定的看门狗设备: +### 场景介绍 +对于无法直接观测到的软件异常,我们可以使用看门狗进行自动检测,并在异常产生时及时重置。 -``` -DevHandle WatchdogOpen(int16_t wdtId); -``` +### 接口说明 + +Watchdog模块提供的主要接口如表1所示。 - **表2** WatchdogOpen参数和返回值描述 +**表1** 看门狗API接口功能介绍 -| **参数** | **参数描述** | +| 接口名 | 描述 | | -------- | -------- | -| wdtId | 看门狗设备号 | -| **返回值** | **返回值描述** | -| NULL | 打开失败 | -| DevHandle类型指针 | 看门狗设备句柄 | +| int32_t WatchdogOpen(int16_t wdtId, DevHandle *handle) | 打开看门狗 | +| void WatchdogClose(DevHandle handle) | 关闭看门狗 | +| int32_t WatchdogStart(DevHandle handle) | 启动看门狗 | +| int32_t WatchdogStop(DevHandle handle) | 停止看门狗 | +| int32_t WatchdogSetTimeout(DevHandle handle, uint32_t seconds) | 设置看门狗超时时间 | +| int32_t WatchdogGetTimeout(DevHandle handle, uint32_t *seconds) | 获取看门狗超时时间 | +| int32_t WatchdogGetStatus(DevHandle handle, int32_t *status) | 获取看门狗状态 | +| int32_t WatchdogFeed(DevHandle handle) | 清除看门狗定时器(喂狗) | +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+> 本文涉及的看门狗的所有接口,支持内核态及用户态使用。 -``` -DevHandle handle = NULL; -handle = WatchdogOpen(0); /* 打开0号看门狗设备 */ -if (handle == NULL) { - HDF_LOGE("WatchdogOpen: failed, ret %d\n", ret); - return; -} +### 开发步骤 + +使用看门狗的一般流程如下图所示。 + +**图2** 看门狗使用流程图 + +![image2](figures/看门狗使用流程图.png "看门狗使用流程图") + +#### 打开看门狗设备 + +在操作看门狗之前,需要调用WatchdogOpen打开看门狗设备,一个系统可能有多个看门狗,通过看门狗ID号来打开指定的看门狗设备: + +```c +DevHandle WatchdogOpen(int16_t wdtId, DevHandle *handle); ``` +**表2** WatchdogOpen参数和返回值描述 -### 获取看门狗状态 +| **参数** | **参数描述** | +| -------- | -------- | +| wdtId | 看门狗设备号 | +| handle | 看门狗设备句柄 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | 打开看门狗设备成功 | +| 负数 | 打开看门狗设备失败 | +```c +int16_t wdtId = 0; +int32_t ret; +DevHandle *handle = NULL; +ret = WatchdogOpen(wdtId, handle); // 打开0号看门狗设备 +if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogOpen: open watchdog_%hd failed, ret:%d\n", wdtId, ret); + return ret; +} ``` + +#### 获取看门狗状态 + +```c int32_t WatchdogGetStatus(DevHandle handle, int32_t *status); ``` - **表3** WatchdogGetStatus参数和返回值描述 +**表3** WatchdogGetStatus参数和返回值描述 | **参数** | **参数描述** | | -------- | -------- | | handle | 看门狗设备句柄 | -| status | 获取到的看门狗状态的指针 | +| status | 获取到的看门狗状态 | | **返回值** | **返回值描述** | -| 0 | 获取成功 | -| 负数 | 获取失败 | +| HDF_SUCCESS | 获取看门狗状态成功 | +| 负数 | 获取看门狗状态失败 | - -``` +```c int32_t ret; int32_t status; -/* 获取Watchdog启动状态 */ -ret = WatchdogGetStatus(handle, &status); -if (ret != 0) { - HDF_LOGE("WatchdogGetStatus: failed, ret %d\n", ret); - return; + +ret = WatchdogGetStatus(handle, &status); // 获取Watchdog状态 +if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogGetStatus: watchdog get status failed, ret:%d\n", ret); + return ret; } ``` - -### 设置超时时间 +#### 设置超时时间 -``` +```c int32_t WatchdogSetTimeout(DevHandle *handle, uint32_t seconds); ``` - **表4** WatchdogSetTimeout参数和返回值描述 +**表4** WatchdogSetTimeout参数和返回值描述 -| **参数** | **参数描述** | +| **参数** | **参数描述** | | -------- | -------- | -| handle | 看门狗设备句柄 | -| seconds | 超时时间,单位为秒 | -| **返回值** | **返回值描述** | -| 0 | 设置成功 | -| 负数 | 设置失败 | - +| handle | 看门狗设备句柄 | +| seconds | 超时时间,单位为秒 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | 设置成功 | +| 负数 | 设置失败 | -``` +```c int32_t ret; -uint32_t timeOut = 60; -/* 设置超时时间,单位:秒 */ -ret = WatchdogSetTimeout(handle, timeOut); -if (ret != 0) { - HDF_LOGE("WatchdogSetTimeout: failed, ret %d\n", ret); - return; + +ret = WatchdogSetTimeout(handle, 2); // 设置超时时间2秒 +if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogSetTimeout: watchdog set timeOut failed, ret:%d\n", ret); + return ret; } ``` +#### 获取超时时间 -### 获取超时时间 - - -``` +```c int32_t WatchdogGetTimeout(DevHandle *handle, uint32_t *seconds); ``` - **表5** WatchdogGetTimeout参数和返回值描述 +**表5** WatchdogGetTimeout参数和返回值描述 -| **参数** | **参数描述** | +| **参数** | **参数描述** | | -------- | -------- | -| handle | 看门狗设备句柄 | -| seconds | 接收超时时间的指针,单位为秒 | -| **返回值** | **返回值描述** | -| 0 | 获取成功 | -| 负数 | 获取失败 | +| handle | 看门狗设备句柄 | +| seconds | 获取的看门狗超时时间 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | 获取看门狗超时时间成功 | +| 负数 | 获取看门狗超时时间失败 | +```c + int32_t ret; + uint32_t timeOut; + ret = WatchdogGetTimeout(handle, &timeOut); // 获取超时时间 + if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogGetTimeout: watchdog get timeOut failed, ret:%d\n", ret); + return ret; + } ``` -int32_t ret; -uint32_t timeOut; -/* 获取超时时间,单位:秒 */ -ret = WatchdogGetTimeout(handle, &timeOut); -if (ret != 0) { - HDF_LOGE("WatchdogGetTimeout: failed, ret %d\n", ret); - return; -} -``` - -### 启动看门狗 +#### 启动看门狗 - -``` +```c int32_t WatchdogStart(DevHandle handle); ``` - **表6** WatchdogStart参数和返回值描述 +**表6** WatchdogStart参数和返回值描述 -| **参数** | **参数描述** | +| **参数** | **参数描述** | | -------- | -------- | -| handle | 看门狗设备句柄 | -| **返回值** | **返回值描述** | -| 0 | 启动成功 | -| 负数 | 启动失败 | - +| handle | 看门狗设备句柄 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | 启动看门狗成功 | +| 负数 | 启动看门狗失败 | -``` +```c int32_t ret; -/* 启动看门狗 */ -ret = WatchdogStart(handle); -if (ret != 0) { - HDF_LOGE("WatchdogStart: failed, ret %d\n", ret); - return; + +ret = WatchdogStart(handle); // 启动看门狗 +if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogStart: start watchdog failed, ret:%d\n", ret); + return ret; } ``` +#### 喂狗 -### 喂狗 - - -``` +```c int32_t WatchdogFeed(DevHandle handle); ``` - **表7** WatchdogFeed参数和返回值描述 +**表7** WatchdogFeed参数和返回值描述 -| **参数** | **参数描述** | +| **参数** | **参数描述** | | -------- | -------- | -| handle | 看门狗设备句柄 | -| **返回值** | **返回值描述** | -| 0 | 喂狗成功 | -| 负数 | 喂狗失败 | - +| handle | 看门狗设备句柄 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | 喂狗成功 | +| 负数 | 喂狗失败 | -``` +```c int32_t ret; -/* 喂狗 */ -ret = WatchdogFeed(handle); -if (ret != 0) { - HDF_LOGE("WatchdogFeed: failed, ret %d\n", ret); - return; + +ret = WatchdogFeed(handle); // 喂狗 +if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogFeed: feed watchdog failed, ret:%d\n", ret); + return ret; } ``` +#### 停止看门狗 -### 停止看门狗 - - -``` +```c int32_t WatchdogStop(DevHandle handle); ``` - **表8** WatchdogStop参数和返回值描述 +**表8** WatchdogStop参数和返回值描述 -| **参数** | **参数描述** | +| **参数** | **参数描述** | | -------- | -------- | -| handle | 看门狗设备句柄 | -| **返回值** | **返回值描述** | -| 0 | 停止成功 | -| 负数 | 停止失败 | - +| handle | 看门狗设备句柄 | +| **返回值** | **返回值描述** | +| HDF_SUCCESS | 停止看门狗成功 | +| 负数 | 停止看门狗失败 | -``` +```c int32_t ret; -/* 停止看门狗 */ -ret = WatchdogStop(handle); -if (ret != 0) { - HDF_LOGE("WatchdogStop: failed, ret %d\n", ret); - return; + +ret = WatchdogStop(handle); // 停止看门狗 +if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogStop: stop watchdog failed, ret:%d\n", ret); + return ret; } ``` +#### 关闭看门狗设备 -### 关闭看门狗设备 - -当操作完毕时,使用WatchdogClose关闭打开的设备句柄: +当所有操作完毕后,调用WatchdogClose关闭打开的看门狗设备: - -``` +```c void WatchdogClose(DevHandle handle); ``` - **表9** WatchdogClose参数和返回值描述 +**表9** WatchdogClose参数和返回值描述 -| **参数** | **参数描述** | +| **参数** | **参数描述** | | -------- | -------- | -| handle | 看门狗设备句柄 | - +| handle | 看门狗设备句柄 | -``` -/* 关闭看门狗 */ -ret = WatchdogClose(handle); +```c +WatchdogClose(handle); // 关闭看门狗 ``` - ## 使用实例 -本例程提供看门狗的完整使用流程。 - -在本例程中,我们打开一个看门狗设备,设置超时时间并启动计时: +下面将基于Hi3516DV300开发板展示使用Watchdog完整操作,步骤主要如下: -- 首先定期喂狗,即按时清除看门狗定时器,确保系统不会因定时器超时而复位。 +1. 传入看门狗ID号,及空的描述句柄,打开看门狗设备并获得看门狗设备句柄。 +2. 通过看门狗设备句柄及超时时间,设置看门狗设备超时时间。 +3. 通过看门狗设备句柄及待获取超时时间,获取看门狗设备超时时间。 +4. 通过看门狗设备句柄启动看门狗设备。 +5. 通过看门狗设备句柄喂狗。 +6. 通过看门狗设备句柄停止看门狗设备。 +7. 通过看门狗设备句柄关闭看门狗设备。 -- 接着再停止喂狗,观察定时器到期后系统是否发生复位行为。 - - 示例如下: - -``` -#include "watchdog_if.h" -#include "hdf_log.h" -#include "osal_irq.h" -#include "osal_time.h" +```c +#include "watchdog_if.h" /* watchdog标准接口头文件 */ +#include "hdf_log.h" /* 标准日志打印头文件 */ +#include "osal_time.h" /* 标准延迟&睡眠接口头文件 */ #define WATCHDOG_TEST_TIMEOUT 2 #define WATCHDOG_TEST_FEED_TIME 6 @@ -287,14 +299,16 @@ static int32_t TestCaseWatchdog(void) { int32_t i; int32_t ret; + int16_t wdtId = 0; + int32_t status; uint32_t timeout; - DevHandle handle = NULL; + DevHandle *handle = NULL; /* 打开0号看门狗设备 */ - handle = WatchdogOpen(0); - if (handle == NULL) { - HDF_LOGE("Open watchdog failed!"); - return -1; + ret = WatchdogOpen(wdtId, handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("WatchdogOpen: open watchdog_%hd failed, ret:%d\n", wdtId, ret); + return ret; } /* 设置超时时间 */ @@ -305,13 +319,19 @@ static int32_t TestCaseWatchdog(void) return ret; } - /* 回读设置的超时时间值 */ + /* 获取超时时间 */ ret = WatchdogGetTimeout(handle, &timeout); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: get timeout fail! ret:%d\n", __func__, ret); WatchdogClose(handle); return ret; } + /* 比较设置与获取的超时时间是否一致*/ + if (timeout != WATCHDOG_TEST_TIMEOUT) { + HDF_LOGE("%s: set:%u, but get:%u", __func__, WATCHDOG_TEST_TIMEOUT, timeout); + WatchdogClose(handle); + return HDF_FAILURE; + } HDF_LOGI("%s: read timeout back:%u\n", __func__, timeout); /* 启动看门狗,开始计时 */ @@ -321,6 +341,19 @@ static int32_t TestCaseWatchdog(void) WatchdogClose(handle); return ret; } + /* 获取看门狗状态,是否启动*/ + status = WATCHDOG_STOP; + ret = WatchdogGetStatus(handle, &status); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get status fail! ret:%d", __func__, ret); + WatchdogClose(handle); + return ret; + } + if (status != WATCHDOG_START) { + HDF_LOGE("%s: status is:%d after start", __func__, status); + WatchdogClose(handle); + return HDF_FAILURE; + } /* 每隔1S喂狗一次 */ for (i = 0; i < WATCHDOG_TEST_FEED_TIME; i++) { @@ -336,15 +369,26 @@ static int32_t TestCaseWatchdog(void) /* 由于喂狗间隔小于超时时间,系统不会发生复位,此日志可以正常打印 */ HDF_LOGI("%s: no reset ... feeding test OK!!!\n", __func__); - /* 接下来持续不喂狗,使得看门狗计时器超时 */ - for (i = 0; i < WATCHDOG_TEST_FEED_TIME; i++) { - HDF_LOGI("%s: waiting dog buck %d times... \n", __func__, i); - OsalSleep(1); + ret = WatchdogStop(handle); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: stop fail! ret:%d", __func__, ret); + WatchdogClose(handle); + return ret; + } + /* 获取看门狗状态,是否停止*/ + status = WATCHDOG_START; + ret = WatchdogGetStatus(handle, &status); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s: get status fail! ret:%d", __func__, ret); + WatchdogClose(handle); + return ret; + } + if (status != WATCHDOG_STOP) { + HDF_LOGE("%s: status is:%d after stop", __func__, status); + WatchdogClose(handle); + return HDF_FAILURE; } - - /* 当不喂狗时间到达之前设定的超时时间的时候,系统会发生复位,理论上观察不到此日志的打印 */ - HDF_LOGI("%s: dog hasn't back!!! \n", __func__, i); WatchdogClose(handle); - return -1; + return HDF_SUCCESS; } -``` +``` \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-watchdog-develop.md b/zh-cn/device-dev/driver/driver-platform-watchdog-develop.md index 6062164ef459b842f01b316bffe88a9b74d98a1e..95f0816254de45d7855ebd9f7e7fab10eaa80aad 100755 --- a/zh-cn/device-dev/driver/driver-platform-watchdog-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-watchdog-develop.md @@ -1,230 +1,254 @@ # Watchdog - ## 概述 -看门狗(Watchdog),又叫看门狗计时器(Watchdog timer),是一种硬件的计时设备。在HDF框架中,Watchdog接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +### 功能简介 + +看门狗(Watchdog),又称看门狗计时器(Watchdog timer),是一种硬件计时设备。一般有一个输入,叫做喂狗,一个输出到系统的复位端。当系统主程序发生错误导致未及时清除看门狗计时器的计时值时,看门狗计时器就会对系统发出复位信号,使系统从悬停状态恢复到正常运作状态。 + +### 基本概念 + +系统正常工作的时候,每隔一段时间输出一个信号到喂狗端,给看门狗清零,这个操作就叫做喂狗。如果超过规定的时间不喂狗,看门狗定时超时,就会给出一个复位信号到系统,使系统复位。 + +### 运作机制 + +在HDF框架中,Watchdog接口适配模式采用独立服务模式(如图1所示)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDF设备管理器的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 + +独立服务模式下,核心层不会统一发布一个服务供上层使用,因此这种模式下驱动要为每个控制器发布一个服务,具体表现为: + +- 驱动适配者需要实现HdfDriverEntry的Bind钩子函数以绑定服务。 +- device_info.hcs文件中deviceNode的policy字段为1或2,不能为0。 + +Watchdog模块各分层作用: + +- 接口层提供打开看门狗设备、获取看门狗设备状态、启动看门狗设备、设置看门狗设备超时时间、获取看门狗设备超时时间、喂狗、停止看门狗设备超时时间、关闭看门狗设备的接口。 +- 核心层主要提供看门狗控制器的添加、移除以及管理的能力,通过钩子函数与适配层交互。 +- 适配层主要是将钩子函数的功能实例化,实现具体的功能。 + +**图 1** Watchdog独立服务模式结构图 + +![image](figures/独立服务模式结构图.png "Watchdog独立服务模式结构图") + +## 开发指导 - **图1** Watchdog独立服务模式结构图 +### 场景介绍 - ![image](figures/独立服务模式结构图.png "Watchdog独立服务模式结构图") +对于无法直接观测到的软件异常,我们可以使用看门狗进行自动检测,并在异常产生时及时重置。当驱动开发者需要将Watchdog设备适配到OpenHarmony时,需要进行Watchdog驱动适配。下文将介绍如何进行Watchdog驱动适配。 +### 接口说明 -## 接口说明 +为了保证上层在调用Watchdog接口时能够正确的操作Watchdog控制器,核心层在//drivers/hdf_core/framework/support/platform/include/watchdog/watchdog_core.h中定义了以下钩子函数,驱动适配者需要在适配层实现这些函数的具体功能,并与钩子函数挂接,从而完成适配层与核心层的交互。 WatchdogMethod定义: - -``` +```c struct WatchdogMethod { - int32_t (*getStatus)(struct WatchdogCntlr *wdt, int32_t *status); - int32_t (*setTimeout)(struct WatchdogCntlr *wdt, uint32_t seconds); - int32_t (*getTimeout)(struct WatchdogCntlr *wdt, uint32_t *seconds); - int32_t (*start)(struct WatchdogCntlr *wdt); - int32_t (*stop)(struct WatchdogCntlr *wdt); - int32_t (*feed)(struct WatchdogCntlr *wdt); - int32_t (*getPriv)(struct WatchdogCntlr *wdt); //【可选】如果WatchdogCntlr中的priv成员存在,则按需实例化 - void (*releasePriv)(struct WatchdogCntlr *wdt);//【可选】 + int32_t (*getStatus)(struct WatchdogCntlr *wdt, int32_t *status); + int32_t (*setTimeout)(struct WatchdogCntlr *wdt, uint32_t seconds); + int32_t (*getTimeout)(struct WatchdogCntlr *wdt, uint32_t *seconds); + int32_t (*start)(struct WatchdogCntlr *wdt); + int32_t (*stop)(struct WatchdogCntlr *wdt); + int32_t (*feed)(struct WatchdogCntlr *wdt); + int32_t (*getPriv)(struct WatchdogCntlr *wdt); // 【可选】如果WatchdogCntlr中的priv成员存在,则按需实例化 + void (*releasePriv)(struct WatchdogCntlr *wdt); // 【可选】 }; ``` - **表1** WatchdogMethod成员的回调函数功能说明 +**表1** WatchdogMethod成员的钩子函数功能说明 -| 成员函数 | 入参 | 出参 | 返回值 | 功能 | +| 成员函数 | 入参 | 出参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -------- | -| getStatus | wdt:结构体指针,核心层WDG控制器 | status:int32_t指针,表示狗的状态(打开或关闭) | HDF_STATUS相关状态 | 获取看门狗所处的状态 | -| start | wdt:结构体指针,核心层WDG控制器 | 无 | HDF_STATUS相关状态 | 打开看门狗 | -| stop | wdt:结构体指针,核心层WDG控制器 | 无 | HDF_STATUS相关状态 | 关闭看门狗 | -| setTimeout | wdt:结构体指针,核心层WDG控制器;seconds:时间传入值 | 无 | HDF_STATUS相关状态 | 设置看门狗超时时间,单位秒,需要保证看门狗实际运行的时间符合该值 | -| getTimeout | wdt:结构体指针,核心层WDG控制器 | seconds:uint32_t指针,传出的时间值 | HDF_STATUS相关状态 | 回读设置的超时时间值 | -| feed | wdt:结构体指针,核心层WDG控制器 | 无 | HDF_STATUS相关状态 | 喂狗 | -| getPriv | wdt:结构体指针,核心层WDG控制器 | 无 | HDF_STATUS相关状态 | 获取看门狗驱动的私有数据 | -| releasePriv | wdt:结构体指针,核心层WDG控制器 | 无 | HDF_STATUS相关状态 | 释放看门狗驱动的私有数据 | - -## 开发步骤 - -Watchdog模块适配HDF框架的四个环节是实例化驱动入口,配置属性文件,实例化Watchdog控制器对象以及驱动调试。 - -1. **实例化驱动入口:** - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 - -2. **配置属性文件:** - - 在device_info.hcs文件中添加deviceNode描述。 - - 【可选】添加watchdog_config.hcs器件属性文件。 - -3. **实例化Watchdog控制器对象:** - - 初始化WatchdogCntlr成员。 - - 实例化WatchdogCntlr成员WatchdogMethod。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
- > 实例化WatchdogCntlr成员WatchdogMethod,其定义和成员说明见[接口说明](#接口说明)。 - -4. **驱动调试:** - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,超时时间设置的成功与否等。 - - -## 开发实例 - -下方将以watchdog_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 - -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 - 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - - Watchdog驱动入口参考: - - ``` - struct HdfDriverEntry g_watchdogDriverEntry = { - .moduleVersion = 1, - .Bind = Hi35xxWatchdogBind, // 见Bind参考 - .Init = Hi35xxWatchdogInit, // 见Init参考 - .Release = Hi35xxWatchdogRelease, // 见Release参考 - .moduleName = "HDF_PLATFORM_WATCHDOG",// 【必要且与HCS文件中里面的moduleName匹配】 - }; - HDF_INIT(g_watchdogDriverEntry);// 调用HDF_INIT将驱动入口注册到HDF框架中 - ``` - -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在 watchdog_config.hcs 中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层WatchdogCntlr 成员的默认值或限制范围有密切关系。 - 本例只有一个Watchdog控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在watchdog_config文件中增加对应的器件属性。 +| getStatus | wdt:结构体指针,核心层Watchdog控制器 | status:int32_t类型指针,表示获取的看门狗的状态(打开或关闭) | HDF_STATUS相关状态 | 获取看门狗状态 | +| setTimeout | wdt:结构体指针,核心层Watchdog控制器;seconds:设置的看门狗超时时间 | 无 | HDF_STATUS相关状态 | 设置看门狗超时时间,单位秒,需要保证看门狗实际运行的时间符合该值 | +| getTimeout | wdt:结构体指针,核心层Watchdog控制器 | seconds:uint32_t类型指针,表示获取的超时时间 | HDF_STATUS相关状态 | 获取看门狗超时时间 | +| start | wdt:结构体指针,核心层Watchdog控制器 | 无 | HDF_STATUS相关状态 | 启动看门狗 | +| stop | wdt:结构体指针,核心层Watchdog控制器 | 无 | HDF_STATUS相关状态 | 停止看门狗 | +| feed | wdt:结构体指针,核心层Watchdog控制器 | 无 | HDF_STATUS相关状态 | 喂狗 | +| getPriv | wdt:结构体指针,核心层Watchdog控制器 | 无 | HDF_STATUS相关状态 | 获取看门狗驱动的私有数据 | +| releasePriv | wdt:结构体指针,核心层Watchdog控制器 | 无 | HDF_STATUS相关状态 | 释放看门狗驱动的私有数据 | + +### 开发步骤 + +Watchdog模块适配包含以下四个步骤: + +- 实例化驱动入口。 +- 配置属性文件。 +- 实例化Watchdog控制器对象。 +- 驱动调试。 + +### 开发实例 + +下方将基于Hi3516DV300开发板以//device_soc_hisilicon/common/platform/watchdog/watchdog_hi35xx.c驱动为示例,展示需要驱动适配者提供哪些内容来完整实现设备功能。 + +1. 实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 + + Watchdog驱动入口开发参考: + + ```c + struct HdfDriverEntry g_watchdogDriverEntry = { + .moduleVersion = 1, + .Bind = Hi35xxWatchdogBind, // 见Bind参考 + .Init = Hi35xxWatchdogInit, // 见Init参考 + .Release = Hi35xxWatchdogRelease, // 见Release参考 + .moduleName = "HDF_PLATFORM_WATCHDOG", // 【必要且与HCS文件中里面的moduleName匹配】 + }; + HDF_INIT(g_watchdogDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + ``` + +2. 配置属性文件。 + + 完成驱动入口注册之后,需要在device_info.hcs文件中添加deviceNode描述。deviceNode信息与驱动入口注册相关。本例以一个Watchdog控制器为例,如有多个器件信息,则需要在device_info文件增加对应的deviceNode描述。器件属性值与核心层WatchdogCntlr成员的默认值或限制范围有密切关系,比如Watchdog设备号,需要在watchdog_config.hcs文件中增加对应的器件属性。 + - device_info.hcs 配置参考: - - - ``` - root { - device_info { - match_attr = "hdf_manager"; - device_watchdog :: device { // 设备节点 - device0 :: deviceNode { // 驱动的DeviceNode节点 - policy = 1; // policy字段是驱动服务发布的策略,如果需要面向用户态,则为2 - priority = 20; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_WATCHDOG"; - // 【必要】驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 - serviceName = "HDF_PLATFORM_WATCHDOG_0"; - // 【必要且唯一】驱动对外发布服务的名称 - deviceMatchAttr = "hisilicon_hi35xx_watchdog_0"; - // 【必要】驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值相等 - } - } - } - } - ``` - + + 在//vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + + ```c + root { + device_info { + match_attr = "hdf_manager"; + device_watchdog :: device { // 设备节点 + device0 :: deviceNode { // 驱动的DeviceNode节点 + policy = 2; // policy字段是驱动服务发布的策略,如果需要面向用户态,则为2 + priority = 20; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "HDF_PLATFORM_WATCHDOG"; // 【必要】用于指定驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 + serviceName = "HDF_PLATFORM_WATCHDOG_0"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_watchdog_0"; // 【必要】用于配置控制器私有数据,必须和驱动私有数据配置表watchdog_config.hcs中的match_attr值保持一致。 + } + } + } + } + ``` + - watchdog_config.hcs 配置参考: - - - ``` - root { - platform { - template watchdog_controller {// 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 - id = 0; - match_attr = ""; - regBase = 0x12050000; // 【必要】地址映射需要 - regStep = 0x1000; // 【必要】地址映射需要 - } - controller_0x12050000 :: watchdog_controller {// 【必要】是作为设备驱动私有数据匹配的关键字 - match_attr = "hisilicon_hi35xx_watchdog_0"; // 【必要】必须和device_info.hcs中的deviceMatchAttr值一致 - } - //存在多个 watchdog 时【必须】添加,否则不用 - ... - } - } - ``` - -3. 完成驱动入口注册之后,最后一步就是以核心层WatchdogCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化WatchdogCntlr成员WatchdogMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 - - 自定义结构体参考。 - - 从驱动的角度看,自定义结构体是参数和数据的载体,而且watchdog_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层WatchdogCntlr对象,例如索引、管脚数等。 - - + + 在//device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/watchdog/watchdog_config.hcs文件配置器件属性,其中配置参数如下: + + ```c + root { + platform { + template watchdog_controller { // 【必要】配置模板,如果下面节点使用时继承该模板,则节点中未声明的字段会使用该模板中的默认值 + id = 0; // watchdog ID号 + match_attr = ""; + regBase = 0x12050000; // 【必要】地址映射需要,物理基地址 + regStep = 0x1000; // 【必要】地址映射需要,寄存器偏移步进 + } + controller_0x12050000 :: watchdog_controller { // 【必要】是作为设备驱动私有数据匹配的关键字 + match_attr = "hisilicon_hi35xx_watchdog_0"; // 【必要】必须和device_info.hcs中的deviceMatchAttr值一致 + } + // 如果存在多个watchdog设备时【必须】添加节点,否则不用 + ... + } + } ``` + + 需要注意的是,新增watchdog_config.hcs配置文件后,必须在产品对应的hdf.hcs文件中将其包含如下语句所示,否则配置文件无法生效。 + + ```c + #include "../../../../device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/watchdog/watchdog_config.hcs" // 配置文件相对路径 + ``` + +3. 实例化Watchdog控制器对象。 + + 完成驱动入口注册之后,下一步就是以核心层WatchdogCntlr对象的初始化为核心,包括驱动适配者自定义结构体(传递参数和数据),实例化WatchdogCntlr成员WatchdogMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + + - 驱动适配者自定义结构体参考。 + + 从驱动的角度看,驱动适配者自定义结构体是参数和数据的载体,而且watchdog_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层WatchdogCntlr对象,例如watchdog设备ID号。 + + ```c struct Hi35xxWatchdog { - struct WatchdogCntlr wdt; // 【必要】是链接上下层的载体,具体描述见下面 - OsalSpinlock lock; - volatile unsigned char *regBase;// 【必要】地址映射需要 - uint32_t phyBase; // 【必要】地址映射需要 - uint32_t regStep; // 【必要】地址映射需要 + struct WatchdogCntlr wdt; // 【必要】是核心层控制对象,具体描述见下面 + OsalSpinlock lock; // 【必要】驱动适配者需要基于此锁变量对watchdog设备实现对应的加锁解锁 + volatile unsigned char *regBase; // 【必要】地址映射需要,寄存器基地址 + uint32_t phyBase; // 【必要】地址映射需要,物理基址 + uint32_t regStep; // 【必要】地址映射需要,寄存器偏移步进 }; - //WatchdogCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值 - struct WatchdogCntlr { - struct IDeviceIoService service;// 驱动服务 - struct HdfDeviceObject *device; // 驱动设备 - OsalSpinlock lock; // 此变量在HDF核心层被调用来实现自旋锁功能 - struct WatchdogMethod *ops; // 接口回调函数 - int16_t wdtId; // WDG设备的识别id - void *priv; // 存储指针 + + struct WatchdogCntlr { // WatchdogCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 + struct IDeviceIoService service; // 驱动服务 + struct HdfDeviceObject *device; // 驱动设备对象 + OsalSpinlock lock; // 自旋锁 + struct WatchdogMethod *ops; // 钩子函数 + int16_t wdtId; // watchdog设备ID号 + void *priv; // 私有数据 }; ``` - - WatchdogCntlr成员回调函数结构体WatchdogMethod的实例化,其他成员在Init和Bind函数中初始化。 - - ``` - static struct WatchdogMethod g_method = { - .getStatus = Hi35xxWatchdogGetStatus, - .start = Hi35xxWatchdogStart, - .stop = Hi35xxWatchdogStop, - .setTimeout = Hi35xxWatchdogSetTimeout, - .getTimeout = Hi35xxWatchdogGetTimeout, - .feed = Hi35xxWatchdogFeed, + - WatchdogCntlr成员钩子函数结构体WatchdogMethod的实例化,其他成员在Init和Bind函数中初始化。 + + ```c + static struct WatchdogMethod g_method = { // 钩子函数实例化 + .getStatus = Hi35xxWatchdogGetStatus, // 获取看门狗状态 + .start = Hi35xxWatchdogStart, // 启动看门狗 + .stop = Hi35xxWatchdogStop, // 停止看门狗 + .setTimeout = Hi35xxWatchdogSetTimeout, // 设置看门狗超时时间 + .getTimeout = Hi35xxWatchdogGetTimeout, // 获取看门狗超时时间 + .feed = Hi35xxWatchdogFeed, // 喂狗 }; ``` - - Init函数和Bind函数参考: + - Init函数和Bind函数开发参考: 入参: - HdfDeviceObject :HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 + HdfDeviceObject:HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 返回值: - HDF_STATUS相关状态 (下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态 (下表为部分展示,如需使用其他状态,可见//drivers/hdf_core/framework/include/utils/hdf_base.h中HDF_STATUS的定义)。 - **表2** Init函数和Bind函数返回值和描述 - - | 状态(值) | 问题描述 | + **表2** Init函数和Bind函数返回值和描述 + + | 状态(值) | 问题描述 | | -------- | -------- | - | HDF_ERR_INVALID_OBJECT | 找不到 WDG 设备 | - | HDF_ERR_MALLOC_FAIL | 内存分配失败 | - | HDF_ERR_IO | I/O 错误 | - | HDF_SUCCESS | 初始化成功 | - | HDF_FAILURE | 初始化失败 | + | HDF_ERR_INVALID_OBJECT | 控制器对象非法 | + | HDF_ERR_MALLOC_FAIL | 内存分配失败 | + | HDF_ERR_IO | I/O 错误 | + | HDF_SUCCESS | 初始化成功 | + | HDF_FAILURE | 初始化失败 | 函数说明: - 初始化自定义结构体对象,初始化WatchdogCntlr成员,调用核心层WatchdogCntlrAdd函数。 + 初始化自定义结构体对象,初始化WatchdogCntlr成员,调用核心层WatchdogCntlrAdd函数,完成看门狗控制器的添加。 - - ``` - //一般而言,Init函数需要根据入参(HdfDeviceObject对象)的属性值初始化Hi35xxWatchdog结构体的成员, - //但本例中是在bind函数中实现的 + ```c + // 一般而言,Init函数需要根据入参(HdfDeviceObject对象)的属性值初始化Hi35xxWatchdog结构体的成员, + // 但watchdog_hi35xx.c示例中是在bind函数中实现的 static int32_t Hi35xxWatchdogInit(struct HdfDeviceObject *device) { - (void)device; - return HDF_SUCCESS; + (void)device; + return HDF_SUCCESS; } - + static int32_t Hi35xxWatchdogBind(struct HdfDeviceObject *device) { - int32_t ret; - struct Hi35xxWatchdog *hwdt = NULL; - ... - hwdt = (struct Hi35xxWatchdog *)OsalMemCalloc(sizeof(*hwdt));//Hi35xxWatchdog 结构体的内存申请 - ... - hwdt->regBase = OsalIoRemap(hwdt->phyBase, hwdt->regStep); //地址映射 - ... - hwdt->wdt.priv = (void *)device->property;// 【可选】此处是将设备属性的内容赋值给priv成员,但后续没有调用 priv 成员, - // 如果需要用到priv成员,需要额外实例化WatchdogMethod的getPriv和releasePriv成员函数 - hwdt->wdt.ops = &g_method; // 【必要】将实例化后的对象赋值给ops成员,就可以实现顶层调用WatchdogMethod成员函数 - hwdt->wdt.device = device; // 【必要】这是为了方便HdfDeviceObject与WatchdogcCntlr相互转化 - ret = WatchdogCntlrAdd(&hwdt->wdt); // 【必要】调用此函数初始化核心层结构体,返回成功信号后驱动才完全接入平台核心层 - if (ret != HDF_SUCCESS) { // 不成功的话,需要释放Init函数申请的资源 - OsalIoUnmap((void *)hwdt->regBase); - OsalMemFree(hwdt); - return ret; - } - return HDF_SUCCESS; + int32_t ret; + struct Hi35xxWatchdog *hwdt = NULL; + ... + hwdt = (struct Hi35xxWatchdog *)OsalMemCalloc(sizeof(*hwdt)); //Hi35xxWatchdog 结构体指针的内存申请 + ... + hwdt->regBase = OsalIoRemap(hwdt->phyBase, hwdt->regStep); //地址映射 + ... + hwdt->wdt.priv = (void *)device->property; // 【必要】此处是将设备属性的内容赋值给priv成员,但后续没有调用 priv 成员, + // 如果需要用到priv成员,需要额外实例化WatchdogMethod的getPriv和releasePriv成员函数 + hwdt->wdt.ops = &g_method; // 【必要】WatchdogMethod实例化对象的挂载 + hwdt->wdt.device = device; // 【必要】这是为了方便HdfDeviceObject与WatchdogcCntlr相互转化 + ret = WatchdogCntlrAdd(&hwdt->wdt); // 【必要】调用此函数初始化核心层结构体,返回成功信号后驱动才完全接入平台核心层 + if (ret != HDF_SUCCESS) { // 不成功的话,需要去除映射并释放Init函数申请的资源 + OsalIoUnmap((void *)hwdt->regBase); + OsalMemFree(hwdt); + return ret; + } + return HDF_SUCCESS; } ``` - - Release函数参考: + + - Release函数开发参考: 入参: @@ -236,26 +260,29 @@ Watchdog模块适配HDF框架的四个环节是实例化驱动入口,配置属 函数说明: - 该函数需要在驱动入口结构体中赋值给Release,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。该函数中需包含释放内存和删除控制器等操作。所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + 该函数需要在驱动入口结构体中赋值给Release,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。该函数中需包含释放内存和删除控制器等操作。 - - ``` + ```c static void Hi35xxWatchdogRelease(struct HdfDeviceObject *device) { - struct WatchdogCntlr *wdt = NULL; - struct Hi35xxWatchdog *hwdt = NULL; - ... - wdt = WatchdogCntlrFromDevice(device); // 这里会通过service成员将HdfDeviceObject转化为WatchdogCntlr - // return (device == NULL) ? NULL : (struct WatchdogCntlr *)device->service; - if (wdt == NULL) { - return; - } - WatchdogCntlrRemove(wdt); // 核心层函数,实际执行wdt->device->service = NULL以及cntlr->lock的释放 - hwdt = (struct Hi35xxWatchdog *)wdt; // 这里将WatchdogCntlr转化为HimciHost - if (hwdt->regBase != NULL) { // 解除地址映射 - OsalIoUnmap((void *)hwdt->regBase); - hwdt->regBase = NULL; - } - OsalMemFree(hwdt); // 释放厂商自定义对象占用的内存 + struct WatchdogCntlr *wdt = NULL; + struct Hi35xxWatchdog *hwdt = NULL; + ... + wdt = WatchdogCntlrFromDevice(device); // 【必要】通过device获取WatchdogCntlr + ... + if (wdt == NULL) { + return; + } + WatchdogCntlrRemove(wdt); // 【必要】调用WatchdogCntlrRemove函数来释放WatchdogCntlr对象的内容 + hwdt = (struct Hi35xxWatchdog *)wdt; // 这里将WatchdogCntlr转化为Hi35xxWatchdog + if (hwdt->regBase != NULL) { // 【必要】解除地址映射 + OsalIoUnmap((void *)hwdt->regBase); + hwdt->regBase = NULL; + } + OsalMemFree(hwdt); // 【必要】释放驱动适配者自定义对象占用的内存 } ``` + +4. 驱动调试。 + + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 \ No newline at end of file diff --git "a/zh-cn/device-dev/driver/figures/I3C\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" "b/zh-cn/device-dev/driver/figures/I3C\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" index 40c7088de596e771921861c727d4813f686eda40..b5ef4432398f7fe6d113774c806453def9a1f6ae 100755 Binary files "a/zh-cn/device-dev/driver/figures/I3C\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" and "b/zh-cn/device-dev/driver/figures/I3C\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" differ diff --git "a/zh-cn/device-dev/driver/figures/MIPI-CSI\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" "b/zh-cn/device-dev/driver/figures/MIPI-CSI\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" index 1e5945dde90c375947137d8b5e9161018c0700f9..5a354fb7af51f27e5c27e6efdf2b45a09aaa0325 100755 Binary files "a/zh-cn/device-dev/driver/figures/MIPI-CSI\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" and "b/zh-cn/device-dev/driver/figures/MIPI-CSI\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" differ diff --git "a/zh-cn/device-dev/driver/figures/\347\234\213\351\227\250\347\213\227\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" "b/zh-cn/device-dev/driver/figures/\347\234\213\351\227\250\347\213\227\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" index 3fa26eb23a059deb997ae31f292a6fe5fc8e75b7..b1f2dd5cc0e8ba606118923b25cc456139efdcb9 100755 Binary files "a/zh-cn/device-dev/driver/figures/\347\234\213\351\227\250\347\213\227\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" and "b/zh-cn/device-dev/driver/figures/\347\234\213\351\227\250\347\213\227\344\275\277\347\224\250\346\265\201\347\250\213\345\233\276.png" differ diff --git a/zh-cn/device-dev/guide/device-camera-control-example.md b/zh-cn/device-dev/guide/device-camera-control-example.md index bca04953d80f8c642b5d2ed062075a15fe61282e..248c80a80ccc0bd498626784465e9d1f935d0296 100644 --- a/zh-cn/device-dev/guide/device-camera-control-example.md +++ b/zh-cn/device-dev/guide/device-camera-control-example.md @@ -3,7 +3,7 @@ 本示例将运行源码中的camera示例代码,通过本示例可以实现使用开发板进行拍照、录像及预览等功能。 - 本示例源码路径为“applications/sample/camera/media/camera\_sample.cpp”。 -- 在运行本示例前需先完成编译烧录、运行镜像等步骤,相关操作请参考[小型系统快速入门](../quick-start/Readme-CN.md)。 +- 在运行本示例前需先完成编译烧录、运行镜像等步骤,相关操作请参考[小型系统快速入门](../quick-start/quickstart-overview.md)。 >![](../public_sys-resources/icon-note.gif) **说明:** >开发板启动后默认会加载launcher应用,应用的图形界面默认显示在媒体图层上方,会影响camera\_sample的演示结果,因此需要在编译或是打包时去掉launcher应用。 diff --git a/zh-cn/device-dev/guide/device-camera-visual-run.md b/zh-cn/device-dev/guide/device-camera-visual-run.md index 7eb2de2d3794931d7cf31c037f8f4b4c3ed47ecc..568daf93ad342fc2aab77d09d94aee1bb5314dc6 100644 --- a/zh-cn/device-dev/guide/device-camera-visual-run.md +++ b/zh-cn/device-dev/guide/device-camera-visual-run.md @@ -1,6 +1,6 @@ # 真机运行 -应用编译打包后即可安装到开发板。安装应用前需要先完成[DevEco Device Tool的安装配置](https://device.harmonyos.com/cn/docs/ide/user-guides/service_introduction-0000001050166905),然后将OpenHarmony烧录到开发板并运行。编译烧录、运行镜像的基本操作请参考快速入门手册:[小型系统快速入门](../quick-start/Readme-CN.md)。完成镜像运行,系统正常启动后,执行如下步骤安装或卸载三方应用。 +应用编译打包后即可安装到开发板。安装应用前需要先完成[DevEco Device Tool的安装配置](https://device.harmonyos.com/cn/docs/ide/user-guides/service_introduction-0000001050166905),然后将OpenHarmony烧录到开发板并运行。编译烧录、运行镜像的基本操作请参考快速入门手册:[小型系统快速入门](../quick-start/quickstart-overview.md)。完成镜像运行,系统正常启动后,执行如下步骤安装或卸载三方应用。 1. 将IDE编译的未签名应用安装包和安装工具(镜像文件生成目录中的dev\_tools)放在sdcard中,将sdcard插入开发板卡槽。 2. 应用安装默认要校验签名,需要执行以下命令,关闭签名校验。 diff --git a/zh-cn/device-dev/guide/device-outerdriver-demo.md b/zh-cn/device-dev/guide/device-outerdriver-demo.md index 38fe3a47a2a23eb8380f711e7ef4d9324060916a..fd46b29cf824963008e11effb17e4ccf544b76c9 100644 --- a/zh-cn/device-dev/guide/device-outerdriver-demo.md +++ b/zh-cn/device-dev/guide/device-outerdriver-demo.md @@ -25,7 +25,7 @@ Input驱动模型核心部分由设备管理层、公共驱动层、器件驱动 ## 环境搭建 -环境准备具体操作请参考[快速入门环境搭建章节](../quick-start/Readme-CN.md)。 +环境准备具体操作请参考[快速入门环境搭建章节](../quick-start/quickstart-overview.md)。 >![](../public_sys-resources/icon-notice.gif) **须知:** >本示例针对OpenHarmony轻量系统、小型系统、标准系统都适用,本文以标准系统为例。其他系统的开发者可参考对应系统的指导文档进行环境搭建。 @@ -316,7 +316,7 @@ Input模型由三层驱动组成,开发者适配一款全新触摸屏驱动只 其中touch\_gt911.o为本示例中追加的内容。 -2. 具体编译及烧录操作请参考[标准系统快速入门的编译及烧录章节](../quick-start/Readme-CN.md)。 +2. 具体编译及烧录操作请参考[标准系统快速入门的编译及烧录章节](../quick-start/quickstart-overview.md)。 ## 调试验证 diff --git a/zh-cn/device-dev/guide/device-wlan-led-control.md b/zh-cn/device-dev/guide/device-wlan-led-control.md index f5c5aa15d37ca16a1c2a3c9ea959cbd0fa15e83f..d5fe17254f18645276d9cb133e5805bd75d592cf 100644 --- a/zh-cn/device-dev/guide/device-wlan-led-control.md +++ b/zh-cn/device-dev/guide/device-wlan-led-control.md @@ -1,8 +1,5 @@ # LED外设控制 -- [概述](#section14639174516337) -- [开发](#section13857170163412) -- [验证](#section1949121910344) ## 概述 @@ -10,7 +7,7 @@ OpenHarmony WLAN模组基于Hi3861平台提供了丰富的外设操作能力, ## 开发 -1. 请先完成[轻量系统快速入门](../quick-start/Readme-CN.md)。 +1. 请先完成[轻量系统快速入门](../quick-start/quickstart-overview.md)。 LED控制参考示例存放于applications/sample/wifi-iot/app/iothardware/led\_example.c文件中。 diff --git a/zh-cn/device-dev/kernel/kernel-mini-overview.md b/zh-cn/device-dev/kernel/kernel-mini-overview.md index 4f8c132c2dcd4b8c99f7a7355208f5345b3bdf9b..7cb5cb28c7b870af88ed3ed7829599a9b8908c40 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-overview.md +++ b/zh-cn/device-dev/kernel/kernel-mini-overview.md @@ -98,7 +98,7 @@ LiteOS-M内核的编译构建系统是一个基于gn和ninja的组件化构建 ### 搭建系统基础环境 -在搭建各个开发板环境前,需要完成OpenHarmony系统基础环境搭建。系统基础环境主要是指OpenHarmony的编译环境和开发环境,详细介绍请参考官方站点[快速入门环境搭建部分](../quick-start/Readme-CN.md)。开发者需要根据环境搭建文档完成环境搭建。 +在搭建各个开发板环境前,需要完成OpenHarmony系统基础环境搭建。系统基础环境主要是指OpenHarmony的编译环境和开发环境,详细介绍请参考官方站点[快速入门环境搭建部分](../quick-start/quickstart-overview.md)。开发者需要根据环境搭建文档完成环境搭建。 ### 获取OpenHarmony源码 diff --git a/zh-cn/device-dev/porting/Readme-CN.md b/zh-cn/device-dev/porting/Readme-CN.md index 6881fa3d3f4952992005b1399383af66b7bc9498..10ab78d4c3459f5816c4b9d6a9401fb273f71313 100644 --- a/zh-cn/device-dev/porting/Readme-CN.md +++ b/zh-cn/device-dev/porting/Readme-CN.md @@ -66,3 +66,4 @@ repo init -u https://gitee.com/openharmony-sig/manifest.git -b master -m devboar - [小型设备STM32MP1芯片移植案例](porting-stm32mp15xx-on-smallsystem.md) - 标准系统芯片移植案例 - [标准系统方案之瑞芯微RK3568移植案例](porting-dayu200-on_standard-demo.md) + - [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md) 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-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/quickstart-ide-env-ubuntu.md b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md index bfda5a1b0d8e37bf4252ba381c4fa3f2943be04e..30db89994cb54da88c8d8a0a0aaa0f088426640a 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 @@ -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命令安装后续操作所需的库和工具。 + + ``` + 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/reference/hdi-apis/_input_dev_ability.md b/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md index 09a32f7c4d89e3e74b1a3a232a213e1b5be07899..fc6af49701af96bf471528f33c670fabffa8f03e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md @@ -25,7 +25,7 @@ Input设备的能力属性,存储支持事件的位图。用位的方式来表 | [ledCode](#ledcode) [[BITS_TO_UINT64](input.md#bitstouint64)(LED_CNT)] | 记录设备支持的指示灯的位图 | | [miscCode](#misccode) [[BITS_TO_UINT64](input.md#bitstouint64)(MSC_CNT)] | 记录设备支持的其他功能的位图 | | [soundCode](#soundcode) [[BITS_TO_UINT64](input.md#bitstouint64)(SND_CNT)] | 记录设备支持的声音或警报的位图 | -| [forceCode](#forcecode) [[BITS_TO_UINT64](input.md#bitstouint64)([HDF_FF_CNT](input.md#hdfffcnt))] | 记录设备支持的作用力功能的位图 | +| [forceCode](#forcecode) [[BITS_TO_UINT64](input.md#bitstouint64)([HDF_FF_CNT](input.md#hdf_ff_cnt))] | 记录设备支持的作用力功能的位图 | | [switchCode](#switchcode) [[BITS_TO_UINT64](input.md#bitstouint64)(SW_CNT)] | 记录设备支持的开关功能的位图 | | [keyType](#keytype) [[BITS_TO_UINT64](input.md#bitstouint64)(KEY_CNT)] | 按键状态的位图 | | [ledType](#ledtype) [[BITS_TO_UINT64](input.md#bitstouint64)(LED_CNT)] | LED状态的位图 | diff --git a/zh-cn/device-dev/reference/hdi-apis/_light_types_8idl.md b/zh-cn/device-dev/reference/hdi-apis/_light_types_8idl.md index 14c020c8b3154c2d9296425d9b94edfcba667635..7ba20d9db066445089a3964a8a8e83175583dd9a 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_light_types_8idl.md +++ b/zh-cn/device-dev/reference/hdi-apis/_light_types_8idl.md @@ -39,7 +39,7 @@ | 名称 | 描述 | | -------- | -------- | | [HdfLightId](light.md#hdflightid) { HDF_LIGHT_ID_BATTERY = 1, HDF_LIGHT_ID_NOTIFICATIONS = 2, HDF_LIGHT_ID_ATTENTION = 3, HDF_LIGHT_ID_BUTT = 4 } | 枚举灯类型。 | -| [HdfLightFlashMode](light.md#hdflightflashmode) { HDF_LIGHT_FLASH_NONE = 0, HDF_LIGHT_FLASH_TIMED = 1, HDF_LIGHT_FLASH_GRADIENT = 2, HDF_LIGHT_FLASH_BUTT = 2 } | 枚举灯的模式。 | +| [HdfLightFlashMode](light.md#hdflightflashmode) { HDF_LIGHT_FLASH_NONE = 0, HDF_LIGHT_FLASH_BLINK = 1, HDF_LIGHT_FLASH_GRADIENT = 2, HDF_LIGHT_FLASH_BUTT = 3 } | 枚举灯的模式。 | ### 关键字 diff --git a/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md b/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md index 77ed4834405cd20597f9a5213cb25ccbfb6aa00b..46da91de2d965b8b6655f1a9fb1362f71e31503d 100644 --- a/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md +++ b/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md @@ -55,7 +55,7 @@ | -------- | -------- | | [VGUScalar](_display.md#vguscalar) | VGU标量 | | [VGUPixelFormat](_display.md#vgupixelformat) | 像素格式。 | -| [VGUBlendType](_display.mdvgublendtype) | 混合操作类型。 | +| [VGUBlendType](_display.md#vgublendtype) | 混合操作类型。 | ### 枚举 diff --git a/zh-cn/device-dev/reference/hdi-apis/light.md b/zh-cn/device-dev/reference/hdi-apis/light.md index dd499b06f0a262abb527523c1179f53b245a78c7..adab9f4230644c23ae3c35d389ea821bd7b537bf 100644 --- a/zh-cn/device-dev/reference/hdi-apis/light.md +++ b/zh-cn/device-dev/reference/hdi-apis/light.md @@ -46,7 +46,7 @@ | 名称 | 描述 | | -------- | -------- | | [HdfLightId](#hdflightid) { HDF_LIGHT_ID_BATTERY = 1, HDF_LIGHT_ID_NOTIFICATIONS = 2, HDF_LIGHT_ID_ATTENTION = 3, HDF_LIGHT_ID_BUTT = 4 } | 枚举灯类型。 | -| [HdfLightFlashMode](#hdflightflashmode) { HDF_LIGHT_FLASH_NONE = 0, HDF_LIGHT_FLASH_TIMED = 1, HDF_LIGHT_FLASH_GRADIENT = 2, HDF_LIGHT_FLASH_BUTT = 2 } | 枚举灯的模式。 | +| [HdfLightFlashMode](#hdflightflashmode) { HDF_LIGHT_FLASH_NONE = 0, HDF_LIGHT_FLASH_BLINK = 1, HDF_LIGHT_FLASH_GRADIENT = 2, HDF_LIGHT_FLASH_BUTT = 3 } | 枚举灯的模式。 | ### 关键字 @@ -73,7 +73,7 @@ enum HdfLightFlashMode | 枚举值 | 描述 | | -------- | -------- | | HDF_LIGHT_FLASH_NONE | 常亮模式。 | -| HDF_LIGHT_FLASH_TIMED | 闪烁模式。 | +| HDF_LIGHT_FLASH_BLINK | 闪烁模式。 | | HDF_LIGHT_FLASH_GRADIENT | 渐变。 | | HDF_LIGHT_FLASH_BUTT | 无效模式。 | diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 901db72406063e38d4675440075e1b915d050bc3..2f86d43843784a3c5098eb7bb54b852167657e3f 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -8,6 +8,7 @@ - [产品配置规则](subsys-build-product.md#产品配置规则) - [子系统配置规则](subsys-build-subsystem.md#子系统配置规则) - [部件配置规则](subsys-build-component.md#部件配置规则) + - [部件编译构建规范](subsys-build-component-building-rules.md#部件编译构建规范) - [模块配置规则](subsys-build-module.md#模块配置规则) - [芯片解决方案配置规则](subsys-build-chip_solution.md#芯片解决方案配置规则) - [特性配置规则](subsys-build-feature.md#特性配置规则) @@ -18,6 +19,7 @@ - [查看NinjaTrace](subsys-build-reference.md#查看ninjatrace) - [HAP编译构建指导](subsys-build-gn-hap-compilation-guide.md) - [ 常见问题](subsys-build-FAQ.md) +- [ArkCompiler](subsys-arkcompiler-guide.md) - [分布式远程启动](subsys-remote-start.md) - 图形图像 - [图形图像概述](subsys-graphics-overview.md) diff --git a/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md b/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..513de0dc06f003d0eb327850d4c65dd37fbb42f5 --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md @@ -0,0 +1,77 @@ +# ArkCompiler开发指导 + +## 概述 +ArkCompiler是一种统一编程平台,包含编译器、工具链、运行时等关键部件,支持高级语言在多种芯片的编译与运行,并支撑应用和服务运行在手机、个人电脑、平板、电视、汽车和智能穿戴等多种设备上的需求。 + +## 编译环境配置 +推荐操作系统Ubuntu18.04及以上。 + +1. 安装依赖工具。 + ```shell + sudo apt-get update && sudo apt-get install python ruby python3-pip git-lfs gcc-multilib g++-multilib zlib1g-dev libc++1 curl nodejs + ``` +2. 安装repo工具。 + ```shell + mkdir ~/bin/ + curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > ~/bin/repo + chmod a+x ~/bin/repo + export PATH=~/bin:$PATH + pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple requests + ``` +3. 下载源码。 + ```shell + repo init -u https://gitee.com/ark-standalone-build/manifest.git -b master + repo sync -c -j8 + repo forall -c 'git lfs pull' + ``` + +4. 安装编译器及二进制工具。 + ```shell + ./prebuilts_download.sh + ``` + +## 开发步骤 + +1. 生成编译产物ark_js_vm及ts2panda。 + ```shell + python ark.py x64.release + ``` + - ark_js_vm:运行abc文件的可执行程序。 + - ts2panda:将ArkTS文件转换生成ArkCompiler字节码文件的工具。 + +2. 使用ts2panda将TypeScript文件转换为abc文件。 + ```shell + prebuilts/build-tools/common/nodejs/node-v12.18.4-linux-x64/bin/node --expose-gc out/x64.release/clang_x64/obj/arkcompiler/ets_frontend/ts2panda/build/src/index.js helloworld.ts --opt-level 0 + ``` + TypeScript用例文件helloworld.ts源码。 + ```JavaScript + declare function print(arg:any):string; + print("Hello world!"); + ``` + +3. 执行生成的abc文件。 + ```shell + out/x64.release/clang_x64/arkcompiler/ets_runtime/ark_js_vm helloworld.abc + ``` + abc文件:ArkCompiler字节码文件。 + + 执行结果: + ``` + Hello world! + ``` + +## 执行Test262测试套 +``` +python ark.py x64.release test262 +``` + +## 编译选项 + +编译模式选择,如在x64平台构建debug版本。 +``` +python ark.py x64.debug +``` +获取更多编译说明。 +``` +python ark.py --help +``` diff --git a/zh-cn/device-dev/subsystems/subsys-build-all.md b/zh-cn/device-dev/subsystems/subsys-build-all.md index 602e4e7f22a9f27c59250b2830b3be3be47abd0a..0479d4a589fcf3d0321697e1dc4ebb9bc01776e3 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-all.md +++ b/zh-cn/device-dev/subsystems/subsys-build-all.md @@ -329,7 +329,7 @@ optional arguments: ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 设备开发过程中详细的编译环境搭建及编译步骤请参考[快速入门中的环境搭建及编译章节。](../quick-start/Readme-CN.md) +> - 设备开发过程中详细的编译环境搭建及编译步骤请参考[快速入门中的环境搭建及编译章节。](../quick-start/quickstart-overview.md) > - OpenHarmony还为开发者提供了Docker编译环境,可以省略编译工具的安装,具体使用请参考[Docker编译指导。](../get-code/gettools-acquire.md) ### 新增并编译不同配置 diff --git a/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md b/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..c256505552d4f8a3e741853516e1049adcef97ca --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md @@ -0,0 +1,279 @@ +# 部件编译构建规范 + +## 前言 + +### 目的 + +编译构建是部件化设计落地的切入点,一个优秀的部件在编译态应该具备可维护、可移植、低耦合的特征。本规范用于引导部件开发人员编写符合部件化设计的编译脚本,使得部件在编译态依赖合理、可配置、可复用、可裁剪。 + +### 基本概念 + +**部件** + +部件是OpenHarmony系统能力的基本单元,以源码为划分依据,具有独立的仓和目录,在不同的设备上可实例化为不同的库或二进制文件。 + +**特性** + +部件特性为编译态可配置的编译选项,可供产品在编译时按需配置。不同的特性配置,编译出部件的不同形态,使得部件可以适应不同形态产品的差异化需求。部件特性的配置只影响部件内部功能的实现差异,不能影响部件的Public API(部件对应用提供的接口)以及inner api(部件间的接口)。 + +**依赖** + +在编译态,部件的依赖分为: + +- 有条件依赖:在特定场景下可裁剪的依赖,有条件的依赖裁剪后不影响部件的Public API 和inner api。比如音频对蓝牙的依赖。 +- 强依赖:部件间合理的必要的依赖,不可裁剪。比如syscap部件对安全库函数的依赖。 + +### 总体原则 + +部件编译构建应遵循以下几个原则: + +**独立自治** + +部件编译态应内聚,新增外部依赖时应慎重,尽量减少编译时的静态依赖。 + +**合理依赖** + +部件间的依赖都应基于部件间的接口,禁止依赖其他部件内部的模块和头文件。 + +**产品无关** + +部件在编译态应是多产品通用的,禁止在编译脚本中使用产品名称。 + +### 约定 + +**规则:** 必须遵守的约定。 + +**建议:** 必须加以考虑的约定。 + +### 看护手段 + +为了维护部件编译构建规范,门禁会对构建配置文件做一些检查。 + +预编译检查:指在预编译阶段进行检查,检测到错误将报错并停止编译。 + +静态检查:指检查工具对配置文件进行扫描检查,非编译手段。 + +### 例外 + +在不违背总体原则,经过充分考虑,有充足的理由的前提下,可以适当违背规范中约定。 + +例外破坏了代码的一致性,请尽量避免。“规则”的例外应该是极少的。 + +## 命名 + +编译脚本中的变量、编译目标(target)、模板,gni文件,以及部件描述文件中的对象和数据的命名都应采用内核风格(unix_like),单词全小写,用下划线分割。如:"startup_init"。 + +### 规则1.1 部件名格式须统一 +- 名词形式,需体现部件的功能。 +- 在系统内全局唯一。 +- 不超过63个有效英文字符。 +- 使用小写加下划线的内核风格命名,例如:unix_like。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 三方开源软件的使用对应社区的原生命名方式,比如:cJson。 + +### 规则1.2 特性名为部件名前缀+特性名称 + +特性是部件声明的可配置的编译选项,加上部件名前缀可避免系统内特性重名。示例: + +```py +declare_args() { + dsoftbus_conn_p2p = true # dsoftbus 为部件名, conn_p2p 为特性名称 + dsoftbus_conn_ble = false # dsoftbus 为部件名, conn_ble 为特性名称 +} +``` + +看护手段:预编译检查 + +### 建议1.1 编译目标名以部件名为前缀+模块名称 + +一个部件可能有多个编译目标(即模块),以“{部件名}_{模块名}”的方式命名可以根据编译产物(库、可执行文件)快速定位归属部件和避免重名。 + +反例: +```py +ohos_shared_library("data") # Bad: 不精确,过于通用,系统内易重名 +``` +正例: +```py +ohos_shared_library("cellular_data_napi") # Good +``` + +## 描述文件 + +bundle.json是定义部件的描述文件,包含了部件的根目录、名称、功能描述、版本号、接口定义和编译入口等信息,须保证其准确性。 + +### 规则2.1 部件描述文件中字段须准确 + +| 字段 | 类型 | 看护手段 | +|---|---|---| +|name|string。部件的HPM(鸿蒙包管理器)包名称,必填。命名规则:@{organization}/{component_name}。"component_name"为部件的名称,须满足规则1.1。|静态检查| +|version|string。部件版本号,必填,命名和升级跟随OpenHarmony版本号。|静态检查| +|destPath|string。部件源码的根目录,必填。部件的根目录须独立唯一,不允许存在多个根目录。|静态检查| +|component:name|string。部件名,必填。须满足规则1.1。|静态检查| +|component:subsystem|string。部件归属的子系统名称,必填,子系统名为小写英文字母组合、不使用下划线。|静态检查| +|component:syscap|string list。系统能力的描述,可选。命名规则:大驼峰,"SystemCapability.Subsystem.部件能力.子能力(可选)",如`SystemCapability.Media.Camera`,`SystemCapability.Media.Camera.Front`。|静态检查| +|component:features|string list,部件可配置的特性,可选,命名须满足规则1.2。|静态检查| +|component:adapted_system_type|string list。部件适用的系统类型,必填,值为`mini`、`small`和`standard`,可同时支持多种。|静态检查| +|component:rom|string。ROM基线值,必填,单位默认为KByte。|静态检查| +|component:ram|string。RAM基线值,必填,单位默认为KByte。|静态检查| +|component:deps|string list。deps对象描述了部件的外部依赖,必填,包括其他部件和三方开源软件,应该与部件编译脚本中依赖一致。|预编译检查| + + +### 建议2.1 部件的描述文件应存放在部件根目录下 + +部件目录是独立的,应将bundle.json文件存放到部件根目录下。 + +## 变量 + +编译目标(target)的内置变量赋值决定了编译内容、依赖和打包等信息,与实现部件化设计强相关。 + +### 规则3.1 部件编译脚本中只允许引用本部件的路径,禁止引用其他部件的绝对或相对路径 + +部件间的依赖都必须使用"externel_deps",部件编译目标的变量sources、include_dirs、configs、public_configs、deps、public_deps引用其他部件的相对和绝对路径属于非法引入依赖: + +- sources + + sources只允许包含本部件的源码,包含其他部件的源码破坏了部件源码目录独立的原则。 + +- include_dirs + + include_dirs只允许引用本部件的头文件搜索路径,编译单元对其他部件的接口的依赖都通过externel_deps自动导入。 + +- configs + + configs只允许引用本部件的配置路径,引用其他部件的configs可能会引入接口依赖。 + +- pulic_configs + + pulic_configs只允许引用本部件的配置路径,引用其他部件的configs可能会引入接口依赖。 + +- deps + + deps只允许用于部件内模块的依赖,直接引用其他部件的模块可能会导致依赖其他部件的内部模块和接口。 + + 例: + + base/foos/foo_a/BUILD.gn + + ```py + deps = [ "//base/foo/foo_b:b" ] # Bad, 绝对路径依赖其他部件 + deps = [ "../../foo_b:b" ] # Bad, 相对路径依赖其他部件 + deps = [ "a" ] # Good, 依赖当前部件内的其他模块 + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 对三方开源软件的引用除外。 + +- public_deps + + public_deps只允许用于部件内模块的依赖,直接引用其他部件的模块可能会导致依赖其他部件的内部模块和接口。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 对三方开源软件的引用除外。 + + +看护手段:静态检查 + +### 规则3.2 部件编译目标必须指定部件和子系统名 + +部件的编译单元ohos_shared_library、ohos_static_library、ohos_executable_library、ohos_source_set都必须指定"part_name"和"subsystem_name"。 + +以developtools/syscap_codec/BUILD.gn的ohos_shared_library编译单元为例: + +```py +ohos_shared_library("syscap_interface_shared") { + include_dirs = [ + "include", + "src", + ] + public_configs = [ ":syscap_interface_public_config" ] + sources = [ + "./interfaces/inner_api/syscap_interface.c", + "./src/endian_internal.c", + "./src/syscap_tool.c", + ] + deps = [ + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + ] + + subsystem_name = "developtools" # 必须指定subsystem_name + part_name = "syscap_codec" # 必须指定part_name +} +``` + +看护手段:静态检查 + +### 建议3.1 部件内部的引用使用相对路径 + +部件内的引用使用相对路径的优点: + +- 脚本更简洁 + +- 部件的编译脚本与部件的根目录解耦。 + +例: + +base/foos/foo_a/BUILD.gn + +```py +include_dirs = [ + "./include", # Good, 相对路径引用 + "//base/foo/foo_a/include" # Bad, 绝对路径引用 +] + +deps = [ + "sub_module:foo", # Good, 相对路径引用 + "base/foo/foo_a/sub_moudule:foo" # Bad, 绝对路径引用 +] +``` + +看护手段:静态检查 + +### 建议3.2 部件内部模块的可见度设置为部件内可见 + +部件内部的模块应使用`"visibility"`字段标识,防止被其他部件依赖。示例: + +base/foos/foo_a/BUILD.gn + +```py +ohos_shared_library("foo_a") { + visibility = [ "./*" ] # foo_a只在base/foo/foo_a及其子目录下可见 +} + +ohos_shared_library("foo_a") { + visibility = [ ":*" ] # foo_a只在本BUILD.gn可见 +} +``` + +## 其他 + +### 规则4.1 部件编译脚本中禁止使用产品名称变量 + +部件是通用的系统能力,与特定产品无关。编译脚本中使用产品名称,将导致部件功能与产品绑定,不具备通用性。部件不同产品形态上的差异应抽象为特性或者运行时的插件。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**例外:** vendor和device目录下三方厂商部件的编译脚本例外。 + +看护手段:静态检查 + +### 建议4.1 避免import其他部件目录下的gni文件 + +部件内的gni文件用于声明部件内部编译变量和模板,import其他部件的gni文件等同于使用其他部件内部的变量和模板,即引入对其他部件的依赖。影响多个部件的变量、args和模板应定义在编译框架的gni文件中。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**例外:** build目录下编译框架定义全局的编译选项的gni可以被所有部件import。 + +看护手段:静态检查 + +### 建议4.2 部件使用统一的编译单元模板 + +轻量、小型和标准的系统的编译单元都应使用ohos定义的模板,比如`ohos_shared_library`、`ohos_static_library`、`ohos_executable`、`ohos_source_set`等以"ohos_"为前缀的模板。 + +例如: + +```py + executable("foundation") { # Bad, 不推荐使用内置的模板 + ... + } + + ohos_executable("foundation") { # Good, 推荐使用ohos定制模板 + ... + } +``` + diff --git a/zh-cn/device-dev/subsystems/subsys-build-reference.md b/zh-cn/device-dev/subsystems/subsys-build-reference.md index 17b5add7a489fc05e5865295ba4d58ed4476b357..3279c9bb5db88525830fd336df94124412eec7e6 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-reference.md +++ b/zh-cn/device-dev/subsystems/subsys-build-reference.md @@ -77,7 +77,7 @@ } ``` -**支持的Sanitizer选项** +**支持的Sanitizer类型** 目前支持开启的Sanitizer: @@ -86,11 +86,11 @@ **发布、调测模式** -通过`debug`选项控制使用发布模式还是调测模式,默认为发布模式,使用`debug = true`显式声明开启调测模式,在发布版本的编译中不带此选项。 +通过`debug`选项控制使用发布模式还是调测模式,默认为发布模式,使用`debug = true`显式声明开启调测模式。`debug`选项仅对Sanitizer生效,且与模块是否编译为调试版本无关,但在模块发布版本的编译配置中不应带此选项,或显式地将`debug`设置为`false`,使得Sanitizer处于发布模式。 -- 调试模式:使用Sanitizer在开发时排查问题,与编译的debug版本无关。该模式下会输出产生错误相关的丰富信息来辅助定位错误,并且在发生错误后并不会直接中断程序运行,而是会恢复程序运行进一步识别后续的错误。 +- 调测模式:用于开发时排查问题。该模式下会输出产生错误相关的丰富信息来辅助定位错误,并且在发生错误后并不会直接中断程序运行,而是会恢复程序运行进一步识别后续的错误。 -- 发布模式:保护程序发生错误或被恶意攻击,在产生错误后直接中断程序不会继续执行。 +- 发布模式:保护程序不发生错误或被恶意攻击,在产生错误后直接中断程序不会继续执行。 **屏蔽名单** diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md index 331435b5f81ec543bba4016d032cebad71894e39..d0dc921dad971457087241c77ff4e71ba34b256d 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @@ -83,6 +83,31 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 当同时通过-t、-o及-n指定了相关订阅规则参数设置,则判断设置的事件标签是否为空,若不为空,则使用事件标签规则进行订阅,否则使用事件领域及事件名称订阅规则进行订阅。 +- 通过事件类型的方式实时订阅HiSysEvent事件: + + ``` + hisysevent -r -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | -------- | + | -g | 设置实时订阅的HiSysEvent事件类型,用来过滤订阅的HiSysEvent事件,有“FAULT”、“STATISTIC”、“SECURITY”及“BEHAVIOR”四种事件类型。 | + + 命令实例: + + ``` + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -g FAULT + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "POWER\w{0,8}" -n "POWER_RUNNINGLOCK" -c REGULAR -g STATISTIC + {"domain_":"POWER","name_":"POWER_RUNNINGLOCK","type_":2,"time_":1667485283785,"tz_":"+0000","pid_":538,"tid_":684,"uid_":5523,"PID":360,"UID":1001,"STATE":0,"TYPE":1,"NAME":"telRilRequestRunningLock","LOG_LEVEL":2,"TAG":"DUBAI_TAG_RUNNINGLOCK_REMOVE","MESSAGE":"token=25956496","level_":"MINOR","tag_":"PowerStats","id_":"11994072552538324655","info_":""} + # hisysevent -r -o "ACCOU\w+" -c REGULAR -g SECURITY + {"domain_":"ACCOUNT","name_":"PERMISSION_EXCEPTION","type_":3,"time_":1667484405993,"tz_":"+0000","pid_":614,"tid_":614,"uid_":3058,"CALLER_UID":1024,"CALLER_PID":523,"PERMISSION_NAME":"ohos.permission.MANAGE_LOCAL_ACCOUNTS","level_":"CRITICAL","tag_":"security","id_":"15077995598140341422","info_":""} + # hisysevent -r -o MULTIMODALINPUT -g BEHAVIOR + {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} + ``` + ## 查询历史HiSysEvent事件相关命令 @@ -139,6 +164,56 @@ {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} ``` +- 通过事件领域及事件名称的方式查询历史HiSysEvent事件: + + ``` + hisysevent -l -o -n [-c WHOLE_WORD] + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | -------- | + | -o | 设置查询历史HiSysEvent事件领域,用来过滤查询的HiSysEvent事件。 | + | -n | 设置查询历史HiSysEvent事件名称,用来过滤查询的HiSysEvent事件。 | + | -c | 设置查询历史HiSysEvent事件领域及事件名称的匹配规则,查询只支持“WHOLE_WORD”匹配规则。 | + + 命令实例: + + ``` + # hisysevent -l -n "APP_FREEZE" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "RELIABILITY" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""} + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -c WHOLE_WORD + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""} + ``` + +- 通过事件类型的方式查询历史HiSysEvent事件: + + ``` + hisysevent -l -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | -------- | + | -g | 设置查询历史HiSysEvent事件类型,用来过滤查询的HiSysEvent事件,有“FAULT”、“STATISTIC”、“SECURITY”及“BEHAVIOR”四种事件类型。 | + + 命令实例: + + ``` + # hisysevent -l -o "RELIABILITY" -g FAULT + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -l -n "POWER_RUNNINGLOCK" -c WHOLE_WORD -g STATISTIC + {"domain_":"POWER","name_":"POWER_RUNNINGLOCK","type_":2,"time_":1667485283785,"tz_":"+0000","pid_":538,"tid_":684,"uid_":5523,"PID":360,"UID":1001,"STATE":0,"TYPE":1,"NAME":"telRilRequestRunningLock","LOG_LEVEL":2,"TAG":"DUBAI_TAG_RUNNINGLOCK_REMOVE","MESSAGE":"token=25956496","level_":"MINOR","tag_":"PowerStats","id_":"11994072552538324655","info_":""} + # hisysevent -l -g SECURITY + {"domain_":"ACCOUNT","name_":"PERMISSION_EXCEPTION","type_":3,"time_":1667484405993,"tz_":"+0000","pid_":614,"tid_":614,"uid_":3058,"CALLER_UID":1024,"CALLER_PID":523,"PERMISSION_NAME":"ohos.permission.MANAGE_LOCAL_ACCOUNTS","level_":"CRITICAL","tag_":"security","id_":"15077995598140341422","info_":""} + # hisysevent -l -o MULTIMODALINPUT -g BEHAVIOR + {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} + ``` + ## 系统事件合法性校验模式 - 打开系统事件合法性校验模式 diff --git a/zh-cn/device-dev/subsystems/subsys-testguide-test.md b/zh-cn/device-dev/subsystems/subsys-testguide-test.md deleted file mode 100644 index 8077908ac54c057971c53c8ff3535682d407f2f0..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-testguide-test.md +++ /dev/null @@ -1,949 +0,0 @@ -# 测试子系统 -OpenHarmony为开发者提供了一套全面的自测试框架,开发者可根据测试需求开发相关测试用例,开发阶段提前发现缺陷,大幅提高代码质量。 - -本文从基础环境构建,用例开发,编译以及执行等方面介绍OpenHarmony测试框架如何运行和使用。 -## 基础环境构建 -- 测试框架依赖于python运行环境,在使用测试框架之前可参阅以下方式进行配置。 -- 获取源码的方式请参考[源码获取](../get-code/sourcecode-acquire.md)。 -### 环境配置 -#### 测试框架基础环境依赖 - -|环境依赖|操作系统|Linux系统扩展组件|python|python插件|NFS Server|HDC| -|------------|------------|------------|------------|------------|------------|------------| -|版本型号|Ubuntu18.04及以上|libreadline-dev|3.7.5版本及以上|pyserial 3.3及以上、paramiko2.7.1及以上、setuptools40.8.0及以上、rsa4.0及以上|haneWIN NFS Server 1.2.50及以上或者 NFS v4及以上| 1.1.0版本及以上 | -|详细说明|代码编译环境|命令行读取插件|测试框架语言 |pyserial:支持python的串口通信;paramiko:支持python使用SSH协议;setuptools:支持python方便创建和分发python包;rsa:支持python rsa加密 |支持设备通过串口连接| 支持设备通过HDC连接 | - -#### 安装流程 -1. 安装Linux扩展组件readline,安装命令如下: - ``` - sudo apt-get install libreadline-dev - ``` - 安装成功提示如下: - ``` - Reading package lists... Done - Building dependency tree - Reading state information... Done - libreadline-dev is already the newest version (7.0-3). - 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. - ``` -2. 安装setuptools插件,安装命令如下: - ``` - pip3 install setuptools - ``` - 安装成功提示如下: - ``` - Requirement already satisfied: setuptools in d:\programs\python37\lib\site-packages (41.2.0) - ``` -3. 安装paramiko插件,安装命令如下: - ``` - pip3 install paramiko - ``` - 安装成功提示如下: - ``` - Installing collected packages: pycparser, cffi, pynacl, bcrypt, cryptography, paramiko - Successfully installed bcrypt-3.2.0 cffi-1.14.4 cryptography-3.3.1 paramiko-2.7.2 pycparser-2.20 pynacl-1.4.0 - ``` -4. 安装python的rsa插件,安装命令如下: - ``` - pip3 install rsa - ``` - 安装成功提示如下: - ``` - Installing collected packages: pyasn1, rsa - Successfully installed pyasn1-0.4.8 rsa-4.7 - ``` -5. 安装串口插件pyserial,安装命令如下: - ``` - pip3 install pyserial - ``` - 安装成功提示如下: - ``` - Requirement already satisfied: pyserial in d:\programs\python37\lib\site-packages\pyserial-3.4-py3.7.egg (3.4) - ``` -6. 如果设备仅支持串口输出测试结果,则需要安装NFS Server - - Windows环境下安装,例如安装haneWIN NFS Server1.2.50。 - - Linux环境下安装,安装命令如下: - ``` - sudo apt install nfs-kernel-server - ``` - 安装成功提示如下: - ``` - Reading package lists... Done - Building dependency tree - Reading state information... Done - nfs-kernel-server is already the newest version (1:1.3.4-2.1ubuntu5.3). - 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. - ``` -7. 如果设备支持HDC连接,则需要安装HDC工具,安装流程请参考如下链接 - - https://gitee.com/openharmony/developtools_hdc_standard/blob/master/README_zh.md - -## 安装环境检查 - -| 检查项 |操作 |满足环境 | -| --- | --- | --- | -| 检查python安装成功 |命令行窗口执行命令:python --version |版本不小于3.7.5即可 | -| 检查python扩展插件安装成功 |打开test/developertest目录,执行start.bat或start.sh| 可进入提示符“>>>”界面即可 | -|检查NFS Server启动状态(被测设备仅支持串口时检测) |通过串口登录开发板,执行mount命令挂载NFS |可正常挂载文件目录即可 | -|检查HDC安装成功 |命令行窗口执行命令:hdc_std -v |版本不小于1.1.0即可 | - - - -## 测试框架目录简介 -以下是测试框架的目录层级架构,在使用测试框架过程中可在相应目录查找对应组件。 -``` -test # 测试子系统 -├── developertest # 开发者测试组件 -│ ├── aw # 测试框架的静态库 -│ ├── config # 测试框架配置 -│ │ │ ... -│ │ └── user_config.xml # 用户使用配置 -│ ├── examples # 测试用例示例 -│ ├── src # 测试框架源码 -│ ├── third_party # 测试框架依赖第三方组件适配 -│ ├── reports # 测试结果报告 -│ ├── BUILD.gn # 测试框架编译入口 -│ ├── start.bat # 开发者测试入口(Windows) -│ └── start.sh # 开发者测试入口(Linux) -└── xdevice # 测试框架依赖组件 -``` -## 测试用例编写 -### 测试用例目录规划 -使用测试框架过程中,可根据以下层级关系规划测试用例目录。 -``` -subsystem # 子系统 -├── partA # 部件A -│ ├── moduleA # 模块A -│ │ ├── include -│ │ ├── src # 业务代码 -│ │ └── test # 测试目录 -│ │ ├── unittest # 单元测试 -│ │ │ ├── common # 公共用例 -│ │ │ │ ├── BUILD.gn # 测试用例编译配置 -│ │ │ │ └── testA_test.cpp # 单元测试用例源码 -│ │ │ ├── phone # 手机形态用例 -│ │ │ ├── ivi # 车机形态用例 -│ │ │ └── liteos-a # ipcamera使用liteos内核的用例 -│ │ ├── moduletest # 模块测试 -│ │ ... -│ │ -│ ├── moduleB # 模块B -│ ├── test -│ │ └── resource # 依赖资源 -│ │ ├── moduleA # 模块A -│ │ │ ├── ohos_test.xml # 资源配置文件 -│ │ ... └── 1.txt # 资源 -│ │ -│ ├── ohos_build # 编译入口配置 -│ ... -│ -... -``` -> **注意:** 测试用例根据不同设备形态差异分为通用用例和非通用用例,建议将通用用例存放在common目录下,非通用用例存放在相应设备形态目录下。 - -### 测试用例编写 -本测试框架支持多种语言用例编写,针对不同语言提供了不同的模板以供编写参考。 - -**C++参考示例** - -- 用例源文件命名规范 - - 测试用例源文件名称和测试套内容保持一致,文件命名采用全小写+下划线方式命名,以test结尾,具体格式为:[功能]_[子功能]_test,子功能支持向下细分。 -示例: - ``` - calculator_sub_test.cpp - ``` - -- 用例示例 - ``` - /* - * Copyright (c) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #include "calculator.h" - #include - - using namespace testing::ext; - - class CalculatorSubTest : public testing::Test { - public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - }; - - void CalculatorSubTest::SetUpTestCase(void) - { - // input testsuit setup step,setup invoked before all testcases - } - - void CalculatorSubTest::TearDownTestCase(void) - { - // input testsuit teardown step,teardown invoked after all testcases - } - - void CalculatorSubTest::SetUp(void) - { - // input testcase setup step,setup invoked before each testcases - } - - void CalculatorSubTest::TearDown(void) - { - // input testcase teardown step,teardown invoked after each testcases - } - - /** - * @tc.name: integer_sub_001 - * @tc.desc: Verify the sub function. - * @tc.type: FUNC - * @tc.require: Issue Number - */ - HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) - { - // step 1:调用函数获取结果 - int actual = Sub(4,0); - - // Step 2:使用断言比较预期与实际结果 - EXPECT_EQ(4, actual); - } - ``` - 详细内容介绍: - 1. 添加测试用例文件头注释信息 - ``` - /* - * Copyright (c) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - ``` - 2. 引用测试框架头文件和命名空间 - ``` - #include - - using namespace testing::ext; - ``` - 3. 添加被测试类的头文件 - ``` - #include "calculator.h" - ``` - 4. 定义测试套(测试类) - ``` - class CalculatorSubTest : public testing::Test { - public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - }; - - void CalculatorSubTest::SetUpTestCase(void) - { - // input testsuit setup step,setup invoked before all testcases - } - - void CalculatorSubTest::TearDownTestCase(void) - { - // input testsuit teardown step,teardown invoked after all testcases - } - - void CalculatorSubTest::SetUp(void) - { - // input testcase setup step,setup invoked before each testcases - } - - void CalculatorSubTest::TearDown(void) - { - // input testcase teardown step,teardown invoked after each testcases - } - ``` - > **注意:** 在定义测试套时,测试套名称应与编译目标保持一致,采用大驼峰风格。 - - 5. 测试用例实现,包含用例注释和逻辑实现 - ``` - /** - * @tc.name: integer_sub_001 - * @tc.desc: Verify the sub function. - * @tc.type: FUNC - * @tc.require: Issue Number - */ - HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) - { - //step 1:调用函数获取结果 - int actual = Sub(4,0); - - //Step 2:使用断言比较预期与实际结果 - EXPECT_EQ(4, actual); - } - ``` - 在编写用例时,我们提供了三种用例模板供您选择。 - - | 类型 | 描述 | - | ------------| ------------| - | HWTEST(A,B,C)| 用例执行不依赖Setup&Teardown时,可选取| - | HWTEST_F(A,B,C)| 用例执行(不含参数)依赖于Setup&Teardown时,可选取| - | HWTEST_P(A,B,C)| 用例执行(含参数)依赖于Set&Teardown时,可选取| - - 其中,参数A,B,C的含义如下: - - 参数A为测试套名。 - - 参数B为测试用例名,其命名必须遵循[功能点]_[编号]的格式,编号为3位数字,从001开始。 - - 参数C为测试用例等级,具体分为门禁level0 以及非门禁level1-level4共五个等级,其中非门禁level1-level4等级的具体选取规则为:测试用例功能越重要,level等级越低。 - - **注意:** - - 测试用例的预期结果必须有对应的断言。 - - 测试用例必须填写用例等级。 - - 测试体建议按照模板分步实现。 - - 用例描述信息按照标准格式@tc.xxx value书写,注释信息必须包含用例名称,用例描述,用例类型,需求编号四项。其中用例测试类型@tc.type参数的选取,可参考下表。 - - | 测试类型名称|类型编码| - | ------------|------------| - |功能测试 |FUNC| - |性能测试 |PERF| - |可靠性测试 |RELI| - |安全测试 |SECU| - |模糊测试 |FUZZ| - - -**JavaScript参考示例** - -- 用例源文件命名规范 - - 测试用例原文件名称采用大驼峰风格,以TEST结尾,具体格式为:[功能][子功能]TEST,子功能支持向下细分。 -示例: - ``` - AppInfoTest.js - ``` - -- 用例示例 - ``` - /* - * Copyright (C) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - import app from '@system.app' - - import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - - describe("AppInfoTest", function () { - beforeAll(function() { - // input testsuit setup step,setup invoked before all testcases - console.info('beforeAll called') - }) - - afterAll(function() { - // input testsuit teardown step,teardown invoked after all testcases - console.info('afterAll called') - }) - - beforeEach(function() { - // input testcase setup step,setup invoked before each testcases - console.info('beforeEach called') - }) - - afterEach(function() { - // input testcase teardown step,teardown invoked after each testcases - console.info('afterEach called') - }) - - /* - * @tc.name:appInfoTest001 - * @tc.desc:verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - */ - it("appInfoTest001", 0, function () { - //step 1:调用函数获取结果 - var info = app.getInfo() - - //Step 2:使用断言比较预期与实际结果 - expect(info != null).assertEqual(true) - }) - }) - ``` - 详细内容介绍: - 1. 添加测试用例文件头注释信息 - ``` - /* - * Copyright (C) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - ``` - 2. 导入被测api和jsunit测试库 - ``` - import app from '@system.app' - - import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - ``` - 3. 定义测试套(测试类) - ``` - describe("AppInfoTest", function () { - beforeAll(function() { - // input testsuit setup step,setup invoked before all testcases - console.info('beforeAll called') - }) - - afterAll(function() { - // input testsuit teardown step,teardown invoked after all testcases - console.info('afterAll called') - }) - - beforeEach(function() { - // input testcase setup step,setup invoked before each testcases - console.info('beforeEach called') - }) - - afterEach(function() { - // input testcase teardown step,teardown invoked after each testcases - console.info('afterEach called') - }) - ``` - 4. 测试用例实现 - ``` - /* - * @tc.name:appInfoTest001 - * @tc.desc:verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - */ - it("appInfoTest001", 0, function () { - //step 1:调用函数获取结果 - var info = app.getInfo() - - //Step 2:使用断言比较预期与实际结果 - expect(info != null).assertEqual(true) - }) - ``` - -### 测试用例编译文件编写 -根据测试用例目录规划,当执行某一用例时,测试框架会根据编译文件逐层查找,最终找到所需用例进行编译。下面通过不同示例来讲解gn文件如何编写。 - -#### 测试用例编译配置文件 -针对不同语言,下面提供不同的编译模板以供参考。 - -- **C++用例编译配置示例** - ``` - # Copyright (c) 2022 XXXX Device Co., Ltd. - - import("//build/test.gni") - - module_output_path = "subsystem_examples/calculator" - - config("module_private_config") { - visibility = [ ":*" ] - - include_dirs = [ "../../../include" ] - } - - ohos_unittest("CalculatorSubTest") { - module_out_path = module_output_path - - sources = [ - "../../../include/calculator.h", - "../../../src/calculator.cpp", - ] - - sources += [ "calculator_sub_test.cpp" ] - - configs = [ ":module_private_config" ] - - deps = [ "//third_party/googletest:gtest_main" ] - } - - group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] - } - ``` - 详细内容如下: - - 1. 添加文件头注释信息 - ``` - # Copyright (c) 2022 XXXX Device Co., Ltd. - ``` - 2. 导入编译模板文件 - ``` - import("//build/test.gni") - ``` - 3. 指定文件输出路径 - ``` - module_output_path = "subsystem_examples/calculator" - ``` - > **说明:** 此处输出路径为部件/模块名。 - - 4. 配置依赖包含目录 - - ``` - config("module_private_config") { - visibility = [ ":*" ] - - include_dirs = [ "../../../include" ] - } - ``` - > **说明:** 一般在此处对相关配置进行设置,在测试用例编译脚本中可直接引用。 - - 5. 指定测试用例编译目标输出的文件名称 - - ``` - ohos_unittest("CalculatorSubTest") { - } - ``` - 6. 编写具体的测试用例编译脚本(添加需要参与编译的源文件、配置和依赖) - ``` - ohos_unittest("CalculatorSubTest") { - module_out_path = module_output_path - sources = [ - "../../../include/calculator.h", - "../../../src/calculator.cpp", - "../../../test/calculator_sub_test.cpp" - ] - sources += [ "calculator_sub_test.cpp" ] - configs = [ ":module_private_config" ] - deps = [ "//third_party/googletest:gtest_main" ] - } - ``` - - > **说明:根据测试类型的不同,在具体编写过程中可选择不同的测试类型:** - > - ohos_unittest:单元测试 - > - ohos_moduletest:模块测试 - > - ohos_systemtest:系统测试 - > - ohos_performancetest:性能测试 - > - ohos_securitytest:安全测试 - > - ohos_reliabilitytest:可靠性测试 - > - ohos_distributedtest:分布式测试 - - 7. 对目标测试用例文件进行条件分组 - - ``` - group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] - } - ``` - > **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 - -- **JavaScript用例编译配置示例** - - ``` - # Copyright (C) 2022 XXXX Device Co., Ltd. - - import("//build/test.gni") - - module_output_path = "subsystem_examples/app_info" - - ohos_js_unittest("GetAppInfoJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" - } - - group("unittest") { - testonly = true - deps = [ ":GetAppInfoJsTest" ] - } - ``` - - 详细内容如下: - - 1. 添加文件头注释信息 - - ``` - # Copyright (C) 2022 XXXX Device Co., Ltd. - ``` - 2. 导入编译模板文件 - - ``` - import("//build/test.gni") - ``` - 3. 指定文件输出路径 - - ``` - module_output_path = "subsystem_examples/app_info" - ``` - > **说明:** 此处输出路径为部件/模块名。 - - 4. 指定测试用例编译目标输出的文件名称 - - ``` - ohos_js_unittest("GetAppInfoJsTest") { - } - ``` - > **说明:** - >- 使用模板ohos_js_unittest定义js测试套,注意与C++用例区分。 - >- js测试套编译输出文件为hap类型,hap名为此处定义的测试套名,测试套名称必须以JsTest结尾。 - - 5. 指定hap包配置文件config.json和签名文件,两个配置为必选项 - - ``` - ohos_js_unittest("GetAppInfoJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" - } - ``` - config.json为hap编译所需配置文件,需要开发者根据被测sdk版本配置“target”项,其余项可默认,具体如下所示: - - ``` - { - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 // 根据被测sdk版本进行修改,此例为sdk5 - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication", - "name": ".MyApplication", - "deviceType": [ - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "MyApplication", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } - } - ``` - 6. 对目标测试用例文件进行条件分组 - ``` - group("unittest") { - testonly = true - deps = [ ":GetAppInfoJsTest" ] - } - ``` - > **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 - -#### 编译入口配置文件ohos.build - -当完成用例编译配置文件编写后,需要进一步编写部件编译配置文件,以关联到具体的测试用例。 -``` -"partA": { - "module_list": [ - - ], - "inner_list": [ - - ], - "system_kits": [ - - ], - "test_list": [ - "//system/subsystem/partA/calculator/test:unittest" //配置模块calculator下的test - ] - } -``` -> **说明:** test_list中配置的是对应模块的测试用例。 - -### 测试用例资源配置 -测试依赖资源主要包括测试用例在执行过程中需要的图片文件,视频文件、第三方库等对外的文件资源。 - -依赖资源文件配置步骤如下: -1. 在部件的test目录下创建resource目录,在resource目录下创建对应的模块,在模块目录中存放该模块所需要的资源文件。 - -2. 在resource目录下对应的模块目录中创建一个ohos_test.xml文件,文件内容格式如下: - ``` - - - - - - - - ``` -3. 在测试用例的编译配置文件中定义resource_config_file进行指引,用来指定对应的资源文件ohos_test.xml。 - ``` - ohos_unittest("CalculatorSubTest") { - resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" - } - ``` - >**说明:** - >- target_name: 测试套的名称,定义在测试目录的BUILD.gn中。preparer: 表示该测试套执行前执行的动作。 - >- src="res": 表示测试资源位于test目录下的resource目录下,src="out":表示位于out/release/$(部件)目录下。 - -## 测试用例执行 -在执行测试用例之前,针对用例使用设备的不同,需要对相应配置进行修改,修改完成即可执行测试用例。 - -### user_config.xml配置 -``` - - - - false - - false - - true - - - - - - - - - - - - - cmd - 115200 - 8 - 1 - 1 - - - - - - - - - - - - - - - - - - -``` ->**说明:** 在执行测试用例之前,若使用HDC连接设备,用例仅需配置设备IP和端口号即可,其余信息均默认不修改。 - -### Windows环境执行 -#### 测试用例编译 - -由于Windows环境下无法实现用例编译,因此执行用例前需要在Linux环境下进行用例编译,用例编译命令: -``` -./build.sh --product-name hispark_taurus_standard --build-target make_test -``` ->说明: ->- product-name:指定编译产品名称,例如hispark_taurus_standard。 ->- build-target:指定所需要编译的用例,make_test表示指定全部用例,实际开发中可指定特定用例。 - -编译完成后,测试用例将自动保存在out/hispark_taurus/packages/phone/tests目录下。 - -#### 搭建执行环境 -1. 在Windows环境创建测试框架目录Test,并在此目录下创建testcase目录 - -2. 从Linux环境拷贝测试框架developertest和xdevice到创建的Test目录下,拷贝编译好的测试用例到testcase目录下 - >**说明:** 将测试框架及测试用例从Linux环境移植到Windows环境,以便后续执行。 - -3. 修改user_config.xml - ``` - - - false - - - - D:\Test\testcase\tests - - ``` - >**说明:** ``标签表示是否需要编译用例;``标签表示测试用例查找路径。 - -#### 执行用例 -1. 启动测试框架 - ``` - start.bat - ``` -2. 选择产品形态 - - 进入测试框架,系统会自动提示您选择产品形态,请根据实际的开发板进行选择。例如:Hi3516DV300。 - -3. 执行测试用例 - - 当选择完产品形态,可参考如下指令执行测试用例。 - ``` - run -t UT -ts CalculatorSubTest -tc integer_sub_00l - ``` - 执行命令参数说明: - ``` - -t [TESTTYPE]: 指定测试用例类型,有UT,MST,ST,PERF等。(必选参数) - -tp [TESTPART]: 指定部件,可独立使用。 - -tm [TESTMODULE]: 指定模块,不可独立使用,需结合-tp指定上级部件使用。 - -ts [TESTSUITE]: 指定测试套,可独立使用。 - -tc [TESTCASE]: 指定测试用例,不可独立使用,需结合-ts指定上级测试套使用。 - -h : 帮助命令。 - ``` -### Linux环境执行 -#### 远程端口映射 -为了在Linux远程服务器以及Linux虚拟机两种环境下执行测试用例,需要对端口进行远程映射,以实现与设备的数据通路连接。具体操作如下: -1. HDC Server指令: - ``` - hdc_std kill - hdc_std -m -s 0.0.0.0:8710 - ``` - >**说明:** IP和端口号为默认值。 - -2. HDC Client指令: - ``` - hdc_std -s xx.xx.xx.xx:8710 list targets - ``` - >**说明:** 此处IP填写设备侧IP地址。 - -#### 执行用例 -1. 启动测试框架 - ``` - ./start.sh - ``` -2. 选择产品形态 - - 进入测试框架,系统会自动提示您选择产品形态,请根据实际的开发板进行选择。例如:Hi3516DV300。 - -3. 执行测试用例 - - 测试框架在执行用例时会根据指令找到所需用例,自动实现用例编译,执行过程,完成自动化测试。 - ``` - run -t UT -ts CalculatorSubTest -tc integer_sub_00l - ``` - 执行命令参数说明: - ``` - -t [TESTTYPE]: 指定测试用例类型,有UT,MST,ST,PERF等。(必选参数) - -tp [TESTPART]: 指定部件,可独立使用。 - -tm [TESTMODULE]: 指定模块,不可独立使用,需结合-tp指定上级部件使用。 - -ts [TESTSUITE]: 指定测试套,可独立使用。 - -tc [TESTCASE]: 指定测试用例,不可独立使用,需结合-ts指定上级测试套使用。 - -h : 帮助命令。 - ``` - -## 测试报告日志 -当执行完测试指令,控制台会自动生成测试结果,若需要详细测试报告您可在相应的数据文档中进行查找。 - -### 测试结果 -测试结果输出根路径如下: -``` -test/developertest/reports/xxxx_xx_xx_xx_xx_xx -``` ->**说明:** 测试报告文件目录将自动生成。 - -该目录中包含以下几类结果: -| 类型 | 描述| -| ------------ | ------------ | -| result/ |测试用例格式化结果| -| log/plan_log_xxxx_xx_xx_xx_xx_xx.log | 测试用例日志 | -| summary_report.html | 测试报告汇总 | -| details_report.html | 测试报告详情 | - -### 测试框架日志 -``` -reports/platform_log_xxxx_xx_xx_xx_xx_xx.log -``` - -### 最新测试报告 -``` -reports/latest -``` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/zh-cn/glossary.md b/zh-cn/glossary.md index f4598e5e23224dc24a35c485c5cf97a0cf5e2751..6b64d3dca5e379db12fa92249aecd00d21606d27 100644 --- a/zh-cn/glossary.md +++ b/zh-cn/glossary.md @@ -4,20 +4,35 @@ - ### Ability - 应用的重要组成部分,是应用所具备能力的抽象。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。 - + 应用的基本组成部分,是应用所具备能力的抽象。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。 在FA模型与Stage模型,分别定义了不同类型的Ability。 - ### AMS Ability Manager Service,Ability管理服务。 +- ### App Pack + + 上架应用市场的应用包的组织方式,包含一个或多个hap包,后缀名为.app。 + +- ### App Component + + 应用组件,每个Ability就是一个应用级组件。 + - ### ArkCompiler 方舟编译器,是OpenHarmony内置的组件化、可配置的多语言编译和运行平台,包含编译器、工具链、运行时等关键部件,支持高级语言在多种芯片平台的编译与运行,并支撑OpenHarmony标准操作系统及其应用和服务运行在手机、个人电脑、平板、电视、汽车和智能穿戴等多种设备上的需求。 +- ### ArkTS + + OpenHarmony生态的应用开发语言。它在TypeScript(简称 TS)的基础上,扩展了声明式UI、状态管理等能力,让开发者可以以更简洁、更自然的方式开发应用。 + - ### ArkUI - 方舟开发框架,是一套极简、高性能、跨设备应用设计研发的UI开发框架,支撑开发者高效地构建跨设备应用UI界面。详情可参考[方舟开发框架开发指导](application-dev/ui/arkui-overview.md)。 + OpenHarmony上原生UI框架。是一套极简、高性能、跨设备应用设计研发的UI开发框架,支撑开发者高效地构建跨设备应用UI界面。详情可参考[方舟开发框架开发指导](application-dev/ui/arkui-overview.md)。 + +- ### Atomic Service + + 原子化服务,OpenHarmony提供的一种全新应用形态。具有独立入口,用户可通过点击、碰一碰、扫一扫等方式直接触发,无需显示安装,由系统静默安装后即可使用,为用户提供便捷服务。 ## B @@ -26,9 +41,22 @@ Bundle Manager Service,包管理服务。 +## C + +- ### C API + + OpenHarmony SDK 提供的native开发接口。 + +- ### Continuation + + 流转,OpenHarmony系统提供的分布式操作,包括了跨端迁移和多端协同两种场景。 ## D +- ### Derivative Framework + + 衍生框架,指桥接到原生框架上的三方框架。 + - ### DevEco Device Tool 面向智能设备开发者,提供一站式的开发环境、一站式资源获取通道,实现了从芯片模板工程创建到开发资源挑选定制,再到编码、编译、调试、调优、烧录环节的全流程覆盖,帮助开发者实现智能硬件设备的高效开发。 @@ -37,7 +65,6 @@ Distributed Management Service,分布式管理服务。 - ## F - ### FA @@ -46,8 +73,7 @@ - ### FA模型 - Ability开发框架支持的开发模型中的一种。API Version 8及更早版本的应用开发仅支持FA模型。FA模型将Ability分为[FA(Feature Ability)](#fa)和[PA(Particle Ability)](#pa)两种类型,其中FA支持Page Ability模板,PA支持Service ability、Data ability、以及Form ability模板。详情可参考[FA模型综述](application-dev/ability/fa-brief.md)。 - + Ability框架提供的一种开发模型。API version 8及更早版本的应用开发仅支持FA模型。FA模型将Ability分为[FA(Feature Ability)](#fa)和[PA(Particle Ability)](#pa)两种类型,其中FA支持Page Ability模板,PA支持Service ability、Data ability、以及Form ability模板。详情可参考[FA模型综述](application-dev/ability/fa-brief.md)。 ## H @@ -55,6 +81,10 @@ OpenHarmony Ability Package,一个HAP文件包含应用的所有内容,由代码、资源、三方库及应用配置文件组成,其文件后缀名为.hap。 +- ### HAR + + OpenHarmony Archive文件。包含代码、资源和配置文件的中间格式。 + - ### HCS HDF Configuration Source是HDF驱动框架的配置描述语言,是为了实现配置代码与驱动代码解耦,以及便于配置的管理而设计的一种Key-Value为主体的文本格式。 @@ -80,6 +110,12 @@ Intelligent Distributed Networking,是OpenHarmony特有的分布式组网能力单元。开发者可以通过IDN获取分布式网络内的设备列表和设备状态信息,以及注册分布式网络内设备的在网状态变化信息。 +## N + +- ### Native Framework + + 原生框架,指系统自带的开发框架。非原生的框架即三方框架。 + ## P @@ -87,18 +123,41 @@ Particle Ability,是在FA模型的Ability框架下无界面的Ability,主要为Feature Ability提供服务与支持,例如作为后台服务提供计算能力,或作为数据仓库提供数据访问能力。Particle Ability有三种模板,分别为Service模板(Service Ability)、Data模板(Data Ability)、以及Form模板(Form Ability)。 - ## S +- ### SA + + System Ability的简称,这是由系统开发者编写的系统级组件。 + +- ### Secondary Framework + + 次生框架,指不依赖原生框架实现的三方开框架。 + +- ### Stage模型 + + Ability框架自API version 9提供的开发模型。Stage模型将Ability分为UIAbility和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility。 + - ### Super virtual device,超级虚拟终端 亦称超级终端,通过分布式技术将多个终端的能力进行整合,存放在一个虚拟的硬件资源池里,根据业务需要统一管理和调度终端能力,来对外提供服务。 -- ### Stage模型 +- ### SysCap - Ability开发框架支持的开发模型中的一种。从API Version 9起应用开发开始支持Stage模型。Stage模型将Ability分为Ability和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility。 + 全称是System Capability,指OpenHarmony中每个相对独立的特性,如蓝牙,WiFi,NFC,摄像头等,都是系统能力之一。每个系统能力对应多个API,每个API定义上包含了相应的SysCap标签。 - ### System Type,系统类型 - - MiniSystem,轻量系统:面向MCU(Microcontroller Unit,微控制单元)类处理器,例如ARM Cortex-M、RISC-V 32位的设备,资源极其有限,参考内存≥128KiB,提供丰富的近距连接能力以及丰富的外设总线访问能力。典型产品有智能家居领域的联接类模组、传感器设备等。 + - Mini System,轻量系统:面向MCU(Microcontroller Unit,微控制单元)类处理器,例如ARM Cortex-M、RISC-V 32位的设备,资源极其有限,参考内存≥128KiB,提供丰富的近距连接能力以及丰富的外设总线访问能力。典型产品有智能家居领域的联接类模组、传感器设备等。 - Small System,小型系统:面向应用处理器,例如Arm Cortex-A的设备,参考内存≥1MiB,提供更高的安全能力,提供标准的图形框架,提供视频编解码的多媒体能力。典型产品有智能家居领域的IPCamera、电子猫眼、路由器以及智慧出行域的行车记录仪等。 - Standard System,标准系统:面向应用处理器,例如Arm Cortex-A的设备,参考内存≥128MiB,提供增强的交互能力,提供3D GPU以及硬件合成能力,提供更多控件以及动效更丰富的图形能力,提供完整的应用框架。典型产品有高端的冰箱显示屏等。 + +## U + +- ### UI Component + + UI组件,组成用户界面的一部分,可提供用户交互的能力。 + +## X + +- ### XComponent + + ArkUI提供的组件接口,满足开发者自渲染的需求。 diff --git a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md index 219299721d153e1bef8724a85e7ca96145e7dcec..514bbb14842b9aa7846e18e4aa209d2b699f86bd 100644 --- a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md +++ b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md @@ -8,79 +8,74 @@ ## 简介 -方舟编译器\(ArkCompiler\)是OpenHarmony内置的组件化、可配置的多语言编译和运行平台,包含编译器、工具链、运行时等核心部件,支持高级编程语言在多种芯片平台上编译与运行,并支撑OpenHarmony标准操作系统及其应用和服务运行在手机、个人电脑、平板、电视、汽车和智能穿戴等多种设备上的需求。开源的ArkCompiler JS Runtime提供的能力是在OpenHarmony操作系统中编译和运行JavaScript语言\(本文后面简称JS\)。 +方舟编译器\(ArkCompiler\)是为支持多种编程语言、多种芯片平台的联合编译、运行而设计的统一编译运行时平台。它支持包括动态类型和静态类型语言在内的多种编程语言,如JS、TS、ArkTS;它是支撑鸿蒙系统成为打通手机、PC、平板、电视、车机和智能穿戴等多种设备的操作系统的编译运行时底座。 -ArkCompiler JS Runtime分成两个部分,分别是JS编译工具链与JS运行时。JS工具链将JS源码编译成方舟字节码\(ArkCompiler Bytecode\),JS运行时负责执行生成的方舟字节码\(后续如无特殊说明,字节码特指方舟字节码\)。 - -**图1** JS编译工具链架构: +ArkCompiler主要分成两个部分:编译工具链与运行时. +**图1** 编译工具链架构 ![](figures/zh-cn_image_ark_frontend.png) -ArkCompiler JS Runtime的源码编译器接收JS源码的输入,再由ts2abc(将JavaScript文件转换为字节码的工具)生成abc文件。 +ArkCompiler的编译工具链以ArkTS/TS/JS源码作为输入,将其编译生成为abc(ArkCompiler Bytecode,即方舟字节码)文件。 -**图2** JS运行时\(Ark-JS-Runtime\)架构: +**图2** 运行时架构 -![](figures/zh-cn_image_ark-js-arch.png) +![](figures/zh-cn_image_ark-ts-arch.png) -ArkCompiler JS Runtime以方舟字节码文件作为输入并直接运行字节码文件,实现对应的JS语义逻辑。 +ArkCompiler运行时直接运行字节码文件,实现对应语言规范的语义逻辑。 -JS Runtime主要由四个子系统组成: +主要由四个子系统组成: - Core Subsystem - Core Subsystem主要由与语言无关的基础运行库组成,包括承载字节码的ArkCompiler File组件、支持Debugger的Tooling组件、负责对应系统调用的ArkCompiler Base库组件等。 + Core Subsystem主要由与语言无关的基础运行库组成,包括承载字节码的File组件、支持Debugger的Tooling组件、负责适配系统调用的Base库组件等。 -- JS Execution Subsystem +- Execution Subsystem - 执行引擎包含执行字节码的解释器、缓存隐藏类和内联缓存、以及剖析记录运行时类型的Profiler。 + Execution Subsystem包含执行字节码的解释器、快速路径内联缓存、以及抓取运行时信息的Profiler。 -- JS Compiler Subsystem +- Compiler Subsystem - 编译子系统包含Stub编译器、基于Circuit IR的优化编译框架和代码生成器。 + Compiler Subsystem包含Stub编译器、基于IR的编译优化框架和代码生成器。 -- JS Runtime subsystem +- Runtime subsystem - 运行时子系统包含了各种JS运行相关的模块: + Runtime Subsystem包含了ArkTS/TS/JS运行相关的模块。 - 内存管理:对象分配器与垃圾回收器\(并发标记和部分内存压缩的CMS-GC和Partial-Compressing-GC\) - 分析工具:DFX工具、cpu和heap的profiling工具 - 并发管理:actor并发模型中的abc文件管理器 - 标准库:Ecmascript规范定义的标准库、高效的container容器库与对象模型 - 其他:异步工作队列、TypeScript类型加载、跟C++交互的JSNAPI接口等。 -**ArkCompiler-JS的设计特点:** - -- ArkCompiler JS Runtime的主要设计目标: +**ArkCompiler eTS Runtime的设计特点:** - 为OpenHarmony操作系统提供JavaScript/TypeScript应用程序执行引擎,而不是作为浏览器中的JavaScript执行引擎。 +- 原生支持类型 + 目前业界引擎执行TS的方式是先把TS转化为JS,再运行JS源码来完成对应的语义逻辑。ArkCompiler的编译工具链编译TS源码时,会分析推导TS的类型信息并将其传递给运行时。运行时直接使用类型信息在运行前预生成内联缓存(Inline Cache)以加速字节码执行。另外,TSAOT (Ahead-of-Time) Compiler,可以利用字节码文件中的类型信息,直接编译生成优化机器码,使得应用可以直接运行优化机器码,获得高性能运行体验。 -- 为了提升应用的执行性能和安全性: +- 并发:并发模型优化与并发API - ArkCompiler JS Runtime选择将JavaScript/TypeScript程序预先静态编译为方舟字节码(带上静态类型信息),从而减少运行时的编译和类型信息收集开销。另外出于安全性和性能的考虑,ArkCompiler JS Runtime选择不支持eval和只支持strict模式的代码。 + ArkCompiler eTS Runtime选择将ArkTS程序预先静态编译为方舟字节码\(带上静态类型信息\),从而减少运行时的编译和类型信息收集开销。另外出于安全性和性能的考虑,ArkCompiler eTS Runtime选择不支持eval和只支持strict模式的代码。 - 原生支持TypeScript: + ECMAScript规范没有提供并发语义表述;业界引擎,如浏览器或者Node.js,通常会提供基于Actor并发模型的Worker API来支持多线程开发。Actor模型下执行体之间不共享任何数据对象,通过消息机制进行通信。因此Web引擎或者Node.js引擎的Worker都有启动速度慢、内存占用高这些缺陷。 针对这些缺陷,ArkCompiler的运行时已经实现了Actor实例中的不可变或者不易变的对象(方法和字节码)的共享,较大程度地优化了Actor的启动性能和启动内存。 + 方舟编译运行时不只提供了业界通用的Worker API,还提供了TaskPool作为并发API的增强。TaskPool是一个支持优先级调度、工作线程自动扩缩容的任务池功能库。开发者无需关心并发实例的生命周期,也无需关心任务负载变化时需要创建或者销毁并发实例,极大地简化了高性能多线程鸿蒙应用的开发。 - 目前业界通用的执行方式是把TS转化为JS,再通过JS运行时来执行。ArkJS规划在ts2abc编译TS源码时,会推导分析TS的类型信息并传递给ArkCompiler JS运行时。运行时直接利用类型信息静态生成内联缓存(inline caching)从而加速字节码执行。另外,ArkJS规划中的TSAOT \(Ahead-of-Time\) Compiler,可以利用ts2abc传递的类型信息,直接编译生成高质量的机器码,使得应用可以直接以机器码形式运行,提升运行性能。 - -- 轻量级Actor并发模型: - ECMAScript没有提供并发规范,业界JS引擎的实现中常用Actor并发模型。此模型下执行体之间不共享任何数据,通过消息机制进行通信。业界当前实现的JS Actor模型(web-worker)有启动速度慢、内存占用高这些缺陷。为了利用设备的多核能力获得更好的性能提升,ArkCompiler JS Runtime需要提供启动快、内存占用少的Actor实现。目前ArkCompiler JS运行时已经实现在Actor内存隔离模型的基础上,共享actor实例中的不可变或者不易变的对象(方法和字节码),后续继续共享内建代码块、常量字符串等等,来提升JS Actor的启动性能和节省内存开销,达到实现轻量级Actor并发模型的目标。 - -- TypeScript/C++的跨语言交互: - - 在OpenHarmony操作系统平台API实现中,通常需要面临C/C++代码访问和操作TS对象的场景。对这个业务场景,Ark-JS规划可以根据TS程序中的class声明和运行时约定,静态生成包含TS对象布局描述的C/C++头文件,以及操作这些TS对象的C/C++实现库。在C/C++代码中,通过包含TS对象描述头文件以及链接对应实现库,实现直接操作TS对象的效果。由于TS类型或其内在布局并非总是固定不变的,因此在TS对象操作的代码实现中,会插入类型检查,如果对象类型或布局在运行时发生变化,则回退执行通用的慢速路径。 +- 安全 + ArkCompiler前端编译工具链将ArkTS/TS/JS程序预先静态编译为方舟字节码,并且还提供了多重混淆能力的增强,有效地提升了开发者代码资产的安全强度。另外出于安全的考虑,ArkCompiler不支持sloppy模式的JS代码,也不支持eval等运行动态字符串的功能。 ## 目录 ``` -/ark -├── ets_runtime # JS运行时组件 +/arkcompiler +├── ets_runtime # ArkTS运行时组件 ├── runtime_core # 运行时公共组件 -└── ets_frontend # JS语言的前端工具 +├── ets_frontend # ArkTS语言的前端工具 +└── toolchain # ArkTS工具链 ``` ## 使用指南 -[方舟运行时使用指南](https://gitee.com/openharmony/ark_js_runtime/blob/master/docs/ARK-Runtime-Usage-Guide-zh.md) +[方舟运行时使用指南](https://gitee.com/openharmony/arkcompiler_ets_runtime/blob/master/docs/ARK-Runtime-Usage-Guide-zh.md) ## 相关仓 @@ -88,4 +83,6 @@ JS Runtime主要由四个子系统组成: [arkcompiler\_ets\_runtime](https://gitee.com/openharmony/arkcompiler_ets_runtime) -[arkcompiler\_ets\_frontend](https://gitee.com/openharmony/arkcompiler_ets_frontend) \ No newline at end of file +[arkcompiler\_ets\_frontend](https://gitee.com/openharmony/arkcompiler_ets_frontend) + +[arkcompiler\_toolchain](https://gitee.com/openharmony/arkcompiler_toolchain) \ No newline at end of file diff --git a/zh-cn/readme/figures/zh-cn_image_ark-js-arch.png b/zh-cn/readme/figures/zh-cn_image_ark-js-arch.png deleted file mode 100644 index 4e34094c9c82cd80881078df9b5e5904dbe98a61..0000000000000000000000000000000000000000 Binary files a/zh-cn/readme/figures/zh-cn_image_ark-js-arch.png and /dev/null differ diff --git a/zh-cn/readme/figures/zh-cn_image_ark-ts-arch.png b/zh-cn/readme/figures/zh-cn_image_ark-ts-arch.png new file mode 100644 index 0000000000000000000000000000000000000000..37e189f25c9e0f491e94356baa497e314ab289c1 Binary files /dev/null and b/zh-cn/readme/figures/zh-cn_image_ark-ts-arch.png differ diff --git a/zh-cn/readme/figures/zh-cn_image_ark_frontend.png b/zh-cn/readme/figures/zh-cn_image_ark_frontend.png index e8e9951f3f2dc5b566a3d9b36229def46c41aecd..bfd39d9ddfd5f0566331e0447fea05b9ecbba177 100644 Binary files a/zh-cn/readme/figures/zh-cn_image_ark_frontend.png and b/zh-cn/readme/figures/zh-cn_image_ark_frontend.png differ diff --git "a/zh-cn/readme/figures/\346\225\260\346\215\256\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237\346\236\266\346\236\204\345\233\276.png" "b/zh-cn/readme/figures/\346\225\260\346\215\256\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237\346\236\266\346\236\204\345\233\276.png" index 74db74f7798c6216f95084ae5acb590c8130980b..7ee06bcc037d95009a4a4b3f3d5055420493ec49 100644 Binary files "a/zh-cn/readme/figures/\346\225\260\346\215\256\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237\346\236\266\346\236\204\345\233\276.png" and "b/zh-cn/readme/figures/\346\225\260\346\215\256\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237\346\236\266\346\236\204\345\233\276.png" differ diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md new file mode 100644 index 0000000000000000000000000000000000000000..c2cb5e5f9bc6f025538a0d3a3ceca64b3d782dff --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md @@ -0,0 +1,137 @@ +# OpenHarmony 3.1.4 Release + + +## 版本概述 + +当前版本在OpenHarmony 3.1.3 Release的基础上,修复了linux kernel等开源组件的已知漏洞,增强了系统安全性。更新配套的SDK版本,修复了预览器相关的问题。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.1.4 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.9.7 (API Version 8 Relese) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.1.9.7 (API Version 8 Release) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
DevEco Studio 3.0 Beta4版本起,通过DevEco Studio获取的SDK默认为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 3.1 Preview for OpenHarmony | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.4-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二** + +通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.4-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + +**表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/code-v3.1.4-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/code-v3.1.4-Release.tar.gz.sha256) | +| Hi3516标准系统解决方案(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_hi3516.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_hi3516.tar.gz.sha256) | +| RK3568标准系统解决方案(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_rk3568.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_rk3568.tar.gz.sha256) | +| Hi3861轻量系统解决方案(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_pegasus.tar.gz.sha256) | +| Hi3516小型系统解决方案-LiteOS(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus.tar.gz.sha256) | +| Hi3516小型系统解决方案-Linux(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus_linux.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-public.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony 3.1.3 Release的基础上有如下变更。 + + +### 特性变更 + +本次版本无新增特性及变更。 + +### API变更 + +3.1.4 Release对比3.1.3 Release API接口无变更。 + + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +### 修复缺陷列表 + +**表3** 修复缺陷issue列表 + +| 子系统 | 问题描述 | +| --------- | ------------------------------------------------------------ | +| SDK子系统 | 解决了预览器相关的一些问题([I59433](https://gitee.com/openharmony/arkui_ace_engine/issues/I59433)、[I5K6B1](https://gitee.com/openharmony/arkui_ace_engine/issues/I5K6B1)、[I5C9XJ](https://gitee.com/openharmony/arkui_ace_engine/issues/I5C9XJ)、[I5AVZT](https://gitee.com/openharmony/arkui_ace_engine/issues/I5AVZT)) | +| Demo应用 | 修复小型系统退出设置后应用无法再进入的问题([I5KTI8](https://gitee.com/openharmony/applications_sample_camera/issues/I5KTI8)) | + + + + +### 修复安全漏洞列表 + +**表4** 修复安全问题列表 + +| ISSUE | 问题描述 | 修复链接 | +| -------- | -------- | -------- | +| I5SD5S | 修复组件expat上的CVE-2022-40674安全漏洞 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/20) | +| I5XTS9 | 修复组件expat上的CVE-2022-43680安全漏洞 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/23) | +| I5VNM9 | 修复组件skia上的CVE-2022-27405安全漏洞 | [PR](https://gitee.com/openharmony/third_party_skia/pulls/24) | +| I5VGM0 | 修复组件kernel_linux_5.10上的CVE-2022-20421、CVE-2022-42719、CVE-2022-42720、CVE-2022-42721、CVE-2022-42722、CVE-2022-41674、CVE-2022-3535、CVE-2022-3521、CVE-2022-3565、CVE-2022-3594、CVE-2022-3435、CVE-2022-41849、CVE-2022-3524、CVE-2022-3542、CVE-2022-3534安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/502) | +| I5SBWK | 修复组件kernel_linux_5.10上的CVE-2022-3202、CVE-2022-40307安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/463) | +| I5QBUR | 修复组件kernel_linux_5.10上的CVE-2022-1184安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/474) | +| I5WSJ5 | 修复组件chromium上的CVE-2022-3199、CVE-2022-3046、CVE-2022-3041、CVE-2022-3040、CVE-2022-3039、CVE-2022-3038、CVE-2022-3057、CVE-2022-3195、CVE-2022-3054、CVE-2022-3075安全漏洞,并同步更新webview hap包 | [PR](https://gitee.com/openharmony/web_webview/pulls/349) | +| I5UF8Z | 修复标准系统上的dhd_linux.c中泄露MAC地址的安全问题 | [PR](https://gitee.com/openharmony/kernel_linux_patches/pulls/315) | +| I5VISW | 修复标准系统上的蓝牙日志中存在明文打印Mac地址的安全问题 | [PR](https://gitee.com/openharmony/communication_bluetooth/pulls/626) | +| I5WJU0 | 修复标准系统上的分布式组网日志中出现设备udid敏感信息的安全问题 | [PR](https://gitee.com/openharmony/security_access_token/pulls/761) | diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md index 16c8318d068221441622c4b6ac881424c84c6bde..bce32409ccfa09ce39eea9e5fb40328696426947 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md @@ -53,8 +53,8 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | 软件 | 版本 | 备注 | | -------- | -------- | -------- | | OpenHarmony | 3.2 Beta3 | NA | -| Public SDK | Ohos_sdk_public 3.2.7.5 (API Version 9 Beta3) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
通过DevEco Studio默认获取的SDK为Public SDK。 | -| Full SDK | Ohos_sdk_full 3.2.7.5 (API Version 9 Beta3) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](../application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.2.7.5 (API Version 9 Beta3)
Ohos_sdk_public 3.2.7.6 (API Version 9 Beta3) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
通过DevEco Studio默认获取的SDK为Public SDK。 | +| Full SDK | Ohos_sdk_full 3.2.7.5 (API Version 9 Beta3)
Ohos_sdk_full 3.2.7.6 (API Version 9 Beta3) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](../application-dev/quick-start/full-sdk-switch-guide.md)。 | | HUAWEI DevEco Studio(可选) | 3.0 Release | OpenHarmony应用开发推荐使用 | | HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用 | @@ -137,6 +137,10 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | 标准系统Full SDK包(Windows\Linux) | 3.2.7.5 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-full.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-full.tar.gz.sha256) | | 标准系统Public SDK包(Mac) | 3.2.7.5 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-mac-public.tar.gz.sha256) | | 标准系统Public SDK包(Windows\Linux) | 3.2.7.5 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/ohos-sdk-windows_linux-public.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.2.7.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/mac-sdk-full.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/mac-sdk-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.2.7.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/ohos-sdk-full.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/ohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.2.7.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/mac-sdk-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/mac-sdk-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.2.7.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/ohos-sdk-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/sdk-patch/ohos-sdk-public.tar.gz.sha256) | @@ -167,7 +171,7 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | 语言编译运行时子系统 | 前端编译性能提升,如es2abc。
运行时性能提升优化,如ISA重构优化、汇编解释器、TSAOT等。
新增功能,如支持严格模式的ES2021、模块化支持、Runtime 调试调优增强、字节码热重载等。
具体如下:
I5MYM9 【新增规格】运行时多模块单abc文件合并适配
I59TAQ【新增规格】支持TSAOT优化编译器标准编译lowering和优化pass(规格)描述
I5OJ8Q【新增规格】IDE属性查看功能补齐已支持的2021规范定义的类型
I5ODV4 【新增特性】 支持字节码补丁文件卸载功能
I5OXSC 【新增特性】 支持字节码补丁文件加载功能
I5HNNZ 【新增特性】使能加载器的命名空间
I5HVQE  【新增特性】线程stacksize根据产品配置,增加stack pageguard保护
I5MCUF【增强特性】libc增加CAPI接口,支持pthread等符号
I5HVNH【新增特性】RM.006.增强动态库符号管理
I5HVQ0 【新增特性】RM.008.musl支持fortify功能
I5KT7X 【新增特性】RM.002.提供API头文件API检测功能
I5TB3Y 【新增特性】ABI默认使用emutls特性
I5R119  【增强特性】拆分加载器与libc内存使用
支持clang工具链的开源构建
I5MYM9【新增规格】前端编译工具链支持模块化编译
I5IKO1【新增规格】前端abc支持commonjs模块
I5RRAJ【新增规格】补丁文件源码识别工具
I5PRFT【新增规格】补丁字节码编译工具
I5RHDH【新增规格】支持方舟字节码热加载
I5RA7C【新增规格】支持strict模式2021
I5HRUY【新增规格】es2abc支持js转换方舟字节码 | NA | | 帐号&程序访问控制子系统 | 帐号服务新增用户身份认证服务;权限服务新增支持精准定位或模糊定位,以及其他能力增强;新增隐私管理服务。
主要涉及如下需求:
I5N90B【新增规格】应用帐号适配沙箱应用
I5N90O【新增规格】帐号子系统新增用户身份认证服务
I5NOQI【新增特性】权限服务支持精准定位或模糊定位
I5NT1X【新增特性】权限使用记录管理增强
I5NU8U【新增特性】权限弹框UX界面增强
I5P4IU【新增特性】新增隐私管理服务
I5P530【新增特性】位置服务使用状态管理 | NA | | 全球化子系统 | 新增支持翻译伪本地化能力。
涉及如下需求:
I4WLSJ 【新增特性】翻译伪本地化能力 | NA | -| Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持设备级的跨设备剪贴板开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | +| Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持剪贴板插件加载开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | | ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。
主要涉及如下需求:
I5IZZ7 【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius
I5JQ1R 【ace_engine_standard部件】支持图片复制粘贴
I5JQ3F 【ace_engine_standard部件】输入框能力增强
I5JQ3J 【ace_engine_standard部件】stack组件新增事件拓传机制
I5JQ54 【ace_engine_standard部件】指定控件获取焦点
I5MX7J 【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果
I5MWS0 【ace_engine_standard部件】panel组件弹出高度通知给开发者
I5IZVY 【ace_engine_standard部件】键鼠接入时支持组件刷新
I5JQ5Y 【ace_engine_standard部件】走焦能力增强
I5IY7K 【新增需求】【ace_engine_standard部件】主题能力支持
I5MWTB 【ace_engine_standard部件】媒体查询支持vp查询
I5IZU9 【ace_engine_standard部件】ui_service常驻内存优化
I5JQ26 【ace_engine_standard部件】Vsync请求机制流程优化
I5JQ2O 【ace_engine部件】公共资源预加载
I5JQ2D 【ace_engine_standard部件】Move事件重采样优化
I5IZXS 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZYG 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZX0 【toolchain部件】编译支持解析$r新增bundleName和moduleName参数
I5J09I 【toolchain部件】\@Builder 支持export导出 | NA | API变更请参考: @@ -188,7 +192,7 @@ API变更请参考: | -------- | -------- | -------- | -------- | | ArkUI | [HealthyDiet:健康饮食](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/HealthyDiet) | 这是一个记录饮食和查看食物信息的应用,主要用于管理饮食健康。可以添加饮食信息,包括食物的种类、重量以及用餐时间,如早餐、 午餐、晚餐和夜宵,并能统计得到相应用餐时间的总热量值、总蛋白质、总脂肪和总碳水值,并且用柱状图的形式展示出来。 | eTS | | ArkUI | [MusicAlbum:一多音乐专辑主页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum) | 本示例展示了音乐专辑主页,使用一次开发多端部署中介绍的自适应布局能力和响应式布局能力进行多设备(或多窗口尺寸)适配,保证应用在不同设备或不同窗口尺寸下可以正常显示。 | eTS | -| 元能力、文件管理 | [Share:分享](https://gitee.com/openharmony/applications_app_samples/tree/master/Share/Share) | 分享的主要工作是实现:发送方将文本,链接,图片文件三种类型分享给三方应用,同时能够在三方应用中分别呈现出来。 | eTS | +| 元能力、文件管理 | [Share:分享](https://gitee.com/openharmony/applications_app_samples/tree/master/Share/CustomShare) | 分享的主要工作是实现:发送方将文本,链接,图片文件三种类型分享给三方应用,同时能够在三方应用中分别呈现出来。 | eTS | | 元能力 | [GalleryForm:图库卡片](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm) | 本示例是模拟图库卡片,实现对图库中的照片在卡片中显示,定时刷新卡片内容等功能。 | eTS | | ArkUI | [AppMarket:一多应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket) | 本示例展示了应用市场首页,页面中包括Tab栏、运营横幅、精品应用、精品游戏等。 | eTS | | ArkUI | [Weather:一多天气](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather) | 本示例展示一个天气应用界面,包括首页、城市管理、添加城市、更新时间弹窗,体现一次开发,多端部署的能力。 | eTS | diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index 36430bb2fd1f920166bfe0f29e88ac42d02c5035..984e715246614522f5be8011bed7a25195794ab0 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -5,6 +5,7 @@ - [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) - [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) - [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) + - [OpenHarmony v3.1.4 Release (2022-11-02)](OpenHarmony-v3.1.4-release.md) - [OpenHarmony v3.1.3 Release (2022-09-30)](OpenHarmony-v3.1.3-release.md) - [OpenHarmony v3.1.2 Release (2022-08-24)](OpenHarmony-v3.1.2-release.md) - [OpenHarmony v3.1.1 Release (2022-05-31)](OpenHarmony-v3.1.1-release.md)