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/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 1446d4fcef22eb94e6c4796be4e55fd0968c8e69..b0496b23ece03d1698df3b88f1002908bd033797 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -68,13 +68,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) @@ -96,6 +96,7 @@ - [@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) @@ -284,3 +285,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/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-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-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-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-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-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/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/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-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/contribute/introducing-third-party-open-source-software.md b/en/contribute/introducing-third-party-open-source-software.md index a0b35543246aff22d2d6ad693f1553add5932457..9d035a952d283b41604c492639eb2f0f52c37a88 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. @@ -40,6 +40,22 @@ For easier maintenance and evolution, comply with the following principles when 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". - The inter-component dependencies between software introduction and dependency software are resolved via external_deps. +13. OpenHarmony's archiving directory requirements for third-party software introduction. + - If you don't have a really good reason to store it elsewhere and under one of the permitted licenses belongs in third_party. + - For the dedicated third-party software introduction which belongs to the specail devboard, and is is not suitable introduced into the OpenHarmony platform, you could apply to store it in the following locations, Naming it in the format of **softwareName**, where **softwareName** must be an official name, and create README.OpenSource description file in the corresponding directory; Creating BUILD.gn to build it independently to support the automatic collection of open source obligation declaration. + + ``` + 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 pre-compiled binary or toolchain, which needs to store the corresponding source code in the OpenHarmony community, and provide the corresponding build guide, and provide open source obligation statement guide; + - Third-party software introduction for precompiled binary or toolchain, need to meet the principles 1 ~ 13; + - The [prebuilt toolchain's description documentation](./prebuilts-readme-template.md): including source code acquisition address, build instructions, update methods, archived in the toolchain root directory with the toolchain build; + - The root directory corresponding to the pre-compiled binary or toolchain needs to provide notice file of the full open source obligation statement; + - If the precompiled binary files come from upstream service platform (e.g. npm packages, etc.). We need to provide the following information in the place where the binary is archived, first we need to provide a general description with the name **README**, include the following information: background description of the introduction and official website; next we need to provide a opensource obligation statement file with the name **NOTICE**, include the following information: software name, version, copyrights, and license information of every third-party open-source software. ### 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/prebuilts-readme-template.md b/en/contribute/prebuilts-readme-template.md new file mode 100644 index 0000000000000000000000000000000000000000..d106f08a850bc065e5be5d2c597058d82996fc22 --- /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/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..de4a7106e7f80f5ea921ae7263bbb7ddcfd6eba7 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,138 @@ 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%E6%A8%A1%E5%9E%8B%E5%92%8Ccontext%E8%AF%A6%E7%BB%86%E4%BB%8B%E7%BB%8D)。 + +## 如何在应用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. 必须要使用系统的返回按键才能触发效果。 + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-bundle.md b/zh-cn/application-dev/faqs/faqs-bundle.md new file mode 100644 index 0000000000000000000000000000000000000000..1a6dd935511aa94a8ce19e937584ce0cd9ac3eb2 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-bundle.md @@ -0,0 +1,33 @@ +# 应用程序包管理开发常见问题 + +## 如何获取应用配置的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#%E5%B1%9E%E6%80%A7)、[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,则是系统应用,否则为非系统应用。 + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-connectivity.md b/zh-cn/application-dev/faqs/faqs-connectivity.md index baa3514733cb5f61627b7b90362bafac9fa9f16d..70ae807faed016ac0758f9d847d1763469295a2f 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) +参考文档:[开发指南](../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) ## \@ohos.net.http.d.ts的response错误码返回6是什么意思? @@ -28,4 +26,81 @@ 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%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)或者[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)) +}) +``` + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-data-management.md b/zh-cn/application-dev/faqs/faqs-data-management.md index 99893fe1a8388fe32310b17dea4561e162b3e754..34cbf014a6c03b27112f004bfb62a76fbb08f74f 100644 --- a/zh-cn/application-dev/faqs/faqs-data-management.md +++ b/zh-cn/application-dev/faqs/faqs-data-management.md @@ -16,6 +16,60 @@ 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) + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-development-board.md b/zh-cn/application-dev/faqs/faqs-development-board.md index 3ab491c0dc6b42b0ca2e91e7a55965f51f9d34ad..9cb08327acb47e58f2c5172b4c7abc9fddc92da1 100644 --- a/zh-cn/application-dev/faqs/faqs-development-board.md +++ b/zh-cn/application-dev/faqs/faqs-development-board.md @@ -27,6 +27,7 @@ 适用于:IDE 3.0.0.991 1. 给预览器新建Profile + ![zh-cn_image_0000001361254285](figures/zh-cn_image_0000001361254285.png) 2. 新建Profile的具体参数可参考如下配置: @@ -49,3 +50,4 @@ 连接需要认证的网络后,用浏览器打开任意网址就可以进入认证页面。 如果开发板上没有浏览器,可以安装[浏览器Sample应用](https://gitee.com/openharmony/app_samples/tree/master/device/Browser)。 + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-device-management.md b/zh-cn/application-dev/faqs/faqs-device-management.md index 7a1ca35602e3be567b3afeceb91054f86cf9f0cb..bf7e0c554ff06ce77f78ccde357af7a589266e62 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,32 @@ 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) + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-dfx.md b/zh-cn/application-dev/faqs/faqs-dfx.md new file mode 100644 index 0000000000000000000000000000000000000000..7a61473320168cb5b17a6c2854ff6c1e907a1b2f --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-dfx.md @@ -0,0 +1,55 @@ +# 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 + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-event-notification.md b/zh-cn/application-dev/faqs/faqs-event-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..3a24c9932f390125c1f72fad4841485da0ffc1cc --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-event-notification.md @@ -0,0 +1,49 @@ +# 公共事件与通知开发常见问题 + +## 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: "发送成功" }) +} +``` + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-file-management.md b/zh-cn/application-dev/faqs/faqs-file-management.md index a6caa4a7064430e4b0c2a2fb49523a8a433ec564..3f96dd3a98da89cf07518a831e4d6bc6184c49ef 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,23 @@ 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属性进行排序。 + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-graphics.md b/zh-cn/application-dev/faqs/faqs-graphics.md index f72711aefb13db79150b749d9a3e6ed470597d0c..e477c759a33339ba7c66c4602a135247e16fe679 100644 --- a/zh-cn/application-dev/faqs/faqs-graphics.md +++ b/zh-cn/application-dev/faqs/faqs-graphics.md @@ -1,7 +1,5 @@ # 图形图像开发常见问题 - - ## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -13,3 +11,81 @@ 适用于: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}`) +}) +``` + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-hdc-std.md b/zh-cn/application-dev/faqs/faqs-hdc-std.md index 5caf5db008a993bca4cbeb8e49f0e0495d716f05..cc59cedda4c59675291082d4bf347907d19a5442 100644 --- a/zh-cn/application-dev/faqs/faqs-hdc-std.md +++ b/zh-cn/application-dev/faqs/faqs-hdc-std.md @@ -1,7 +1,5 @@ # hdc_std命令使用常见问题 - - ## 日志的常用命令 适用于:OpenHarmony SDK 3.2.2.5版本 @@ -26,19 +24,7 @@ 执行完命令后重启DevEco Studio。 -## 应用如何打印日志是使用hilog还是console,hilog接口参数domain的设置范围是什么? - -适用于:OpenHarmony SDK 3.2.2.5版本 - -推荐使用[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)。 - -## hilog日志打印长度限制是多少,是否可以配置 - -适用于:OpenHarmony SDK 3.2.2.5版本 - -日志打印的长度限制为1024个字符,该长度不能配置。 - -## 为什么有时候直接用IDE安装HAP包到开发板上无法打开? +## 用IDE安装HAP包到开发板上无法打开 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -50,14 +36,53 @@ 可以使用hdc_std file send上传文件。 -## 如何让RK3568开发板不熄屏? +## 如何让RK3568开发板不熄屏 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 输入命令hdc_std shell "power-shell setmode 602" -## 如何通过命令启动Ability? +## 如何通过命令启动Ability 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 输入命令hdc_std shell aa start -a AbilityName -b bundleName -m moduleName + +## 如何修改开发板中文件目录为可读写权限 + +适用于: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 uninstall [-k] [package_name] + +## 如何查看系统是32位还是64位 + +适用于:OpenHarmony SDK 3.2.5.5版本 + +使用命令:hdc_std shell getconf LONG_BIT + +若返回64则为64位系统,否则为32位系统。 + +## 如何查看组件树结构 + +适用于:OpenHarmony SDK 3.2.5.5版本 + +1. 使用命令hdc_std shell 进入命令行界面。 + +2. 输入 aa dump -a 找到abilityID。 + +3. aa dump -i [abilityID] -c -render 查看组件树。 + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-ide.md b/zh-cn/application-dev/faqs/faqs-ide.md index c9b32df07511cccbb9c1607d5bb121b635372457..ae44f51ed4cc29b12acac31e812683678ef8be52 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,74 @@ 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) + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-international.md b/zh-cn/application-dev/faqs/faqs-international.md new file mode 100644 index 0000000000000000000000000000000000000000..7b7cb4d62b7119e5bf998c85d30485543164b9c6 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-international.md @@ -0,0 +1,20 @@ +# 国际化开发常见问题 + +## 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文件中不支持使用$引用常量。 + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-language.md b/zh-cn/application-dev/faqs/faqs-language.md new file mode 100644 index 0000000000000000000000000000000000000000..80ebc349c6d1cbf5e93bad3d130332fa5e31fc7f --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-language.md @@ -0,0 +1,288 @@ +# 开发语言常见问题 + +## 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进行全局变量管理。 + +参考文档:[应用程序的数据存储](../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.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数据管理](../ui/ts-other-states-observed-objectlink.md) + +## 如何实现字符串编解码 + +适用于: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..7067465b3a6806fe302aa743985cf548df415e4a --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-media.md @@ -0,0 +1,130 @@ +# 媒体开发常见问题 + +## 如何设置前置拍照 + +适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 + +1. 设置相机位置camera.CameraPosition.CAMERA_POSITION_FRONT + +2. 根据相机位置和类型创建CameraInput实例 + +参考文档:[相机管理](../reference/apis/js-apis-camera.md#%E7%9B%B8%E6%9C%BA%E7%AE%A1%E7%90%86) + +示例: + +``` +//默认设置后置相机,通过设置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个媒体播放实例。 + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-native.md b/zh-cn/application-dev/faqs/faqs-native.md index c71a09dc54f5d04d2bae295c17fe5e1e9af62dba..dd433fa987244614294652e0ed41f4fc68f877ae 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,11 @@ 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) + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-third-party-library.md b/zh-cn/application-dev/faqs/faqs-third-party-library.md index 758305d4aca128e8d39001b2176c3f820f2302e2..5397dc2a81320f16c23a95050855832d6aed7eb3 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,75 @@ # 三四方库使用常见问题 +## 报错“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'; + ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-ui-ets.md b/zh-cn/application-dev/faqs/faqs-ui-ets.md index 46cbe5907ec7734d20b6a37719ca49e7bbd014a3..14ed099e0a8f705ab2c574bddd8f10d283e5c108 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),内部嵌套子组件可保持居中显示,参考[栅格布局](../ui/ui-ts-layout-grid-container.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,432 @@ 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模型 + +gesture的属性distance默认值是5,把gesture的属性distance设成1就可以解决。 -通过WebController中runJavaScript方法异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果。注意:runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 +## 如何获取组件的高度 -参考文档:[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模型 -## 在容器组件嵌套的场景下,如何解决手势拖拽事件出现错乱的问题? +组件宽高变化可通过onAreaChange组件区域变化事件获取。 -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 +示例: -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/#%E7%A4%BA%E4%BE%8B)在当前页面和目标页面中定义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/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高度 + +## backgroundImage设置CenterCrop + +适用于:OpenHarmony SDK3.0, API9 Stage模型 + +CenterCrop是android中imageView,scaletype的设置,主要保证图片等比缩放裁剪,位置保持居中,可以使用通用属性backgroundImageSize(ImageSize.cover)和backgroundImagePosition(Alignment.Center)达到使用效果 + +## 输入框组件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模型 + +支持使用[条件渲染](../ui/ts-rending-control-syntax-if-else.md)和[循环渲染](../ui/ts-rending-control-syntax-foreach.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#%E7%A4%BA%E4%BE%8B2) + +## 鸿蒙的list组件怎么实现类似安卓sticky header的效果? + +适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 + +可以使用ListItemGroup组件来实现。 + +参考:[ListItemGroup](../reference/arkui-ts/ts-container-listitemgroup.md) + +## 能否去除自定义弹窗组件的白色背景 + +适用于: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。 + +参考文档:[自定义弹窗](../arkui-ts/ts-methods-custom-dialog-box.md) + + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-ui-js.md b/zh-cn/application-dev/faqs/faqs-ui-js.md index 90ec607864c46ecfbeba21b7ac327ffe8c3e3ae1..afe4133d3825eeae618ef107457a11d36c60e948 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,41 @@ export default class DateTimeUtil{ return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}` } } + +``` + +## scroller如何判断回弹动画的结束误差 + +适用于:OpenHarmony SDK 3.2.5.3版本,API8 FA模型 + +目前可以在触摸结束之后,计算同方向的变化,如果变化方向相反,说明出现回弹了,就规避不处理了。 + + +## 如何实现应用数据持久化存储 + +通过PersistentStorage类实现管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据。 + +参考文档:[持久化数据管理](../ui/ts-application-states-apis-persistentstorage.md) + +示例: + + +``` +AppStorage.Link('varA') +PersistentStorage.PersistProp("varA", "111"); +@Entry +@Componentstruct Index { + @StorageLink('varA') varA: string = '' + build() { + Column() { + Text('varA: ' + this.varA).fontSize(20) + Button('Set').width(100).height(100).onClick(() => { + this.varA += '333' + }) + } + .width('100%') + .height('100%') + } +} ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-web-arkts.md b/zh-cn/application-dev/faqs/faqs-web-arkts.md new file mode 100644 index 0000000000000000000000000000000000000000..78a123e45d698948dfca66a0044123c3217a5721 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-web-arkts.md @@ -0,0 +1,82 @@ +# 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) + + \ No newline at end of file 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..98d06c159904f39eb2293ca27d9db653c48b77a2 100644 --- a/zh-cn/application-dev/media/audio-playback.md +++ b/zh-cn/application-dev/media/audio-playback.md @@ -35,6 +35,7 @@ AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../ref ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' +import featureAbility from '@ohos.ability.featureAbility' // 打印码流轨道信息 function printfDescription(obj) { @@ -105,8 +106,14 @@ 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'; + // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 + let path = '' + var context = featureAbility.getContext(); + await context.getFilesDir().then((fileDir) => { + console.info("case file dir is" + JSON.stringify(fileDir)); + path = fileDir + '/01.mp3'; + console.info("case path is" + path); + }); await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -124,6 +131,8 @@ async function audioPlayerDemo() { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' +import featureAbility from '@ohos.ability.featureAbility' + export class AudioDemo { // 设置播放器回调函数 setCallBack(audioPlayer) { @@ -145,8 +154,14 @@ 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'; + // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 + let path = '' + var context = featureAbility.getContext(); + await context.getFilesDir().then((fileDir) => { + console.info("case file dir is" + JSON.stringify(fileDir)); + path = fileDir + '/01.mp3'; + console.info("case path is" + path); + }); await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -165,6 +180,8 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' +import featureAbility from '@ohos.ability.featureAbility' + export class AudioDemo { // 设置播放器回调函数 private isNextMusic = false; @@ -191,8 +208,14 @@ 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'; + // path路径的码流可通过"hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 + let nextpath = '' + var context = featureAbility.getContext(); + await context.getFilesDir().then((fileDir) => { + console.info("case file dir is" + JSON.stringify(fileDir)); + nextpath = fileDir + '/02.mp3'; + console.info("case path is" + nextpath); + }); await fileIO.open(nextpath).then((fdNumber) => { nextFdPath = nextFdPath + '' + fdNumber; console.info('open fd success fd is' + nextFdPath); @@ -208,8 +231,14 @@ 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'; + // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 + let path = '' + var context = featureAbility.getContext(); + await context.getFilesDir().then((fileDir) => { + console.info("case file dir is" + JSON.stringify(fileDir)); + path = fileDir + '/01.mp3'; + console.info("case path is" + path); + }); await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -228,6 +257,8 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' +import featureAbility from '@ohos.ability.featureAbility' + export class AudioDemo { // 设置播放器回调函数 setCallBack(audioPlayer) { @@ -245,8 +276,14 @@ 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'; + // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 + let path = '' + var context = featureAbility.getContext(); + await context.getFilesDir().then((fileDir) => { + console.info("case file dir is" + JSON.stringify(fileDir)); + path = fileDir + '/01.mp3'; + console.info("case path is" + path); + }); 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..63686d8842829834e58cc92e6b95ff3a0db754db 100644 --- a/zh-cn/application-dev/media/audio-renderer.md +++ b/zh-cn/application-dev/media/audio-renderer.md @@ -25,32 +25,244 @@ 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."); + ``` - var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 - } +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 audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('Renderer started'); + } else { + console.error('Renderer start failed'); + } } + ``` + 启动完成后,渲染器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 + - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); +3. 调用write()方法向缓冲区写入数据。 + + 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 + + ```js + import fileio from '@ohos.fileio'; + + async function writeBuffer(buf) { + let state = audioRenderer.state; + // 写入数据时,渲染器的状态必须为STATE_RUNNING + if (state != audio.AudioState.STATE_RUNNING) { + console.error('Renderer is not running, do not write'); + this.isPlay = false; + return; + } + + let writtenbytes = await audioRenderer.write(buf); + + console.info(`Actual written bytes: ${writtenbytes} `); + if (writtenbytes < 0) { + console.error('Write buffer failed. check the state of renderer'); + } + } + + // 此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + const bufferSize = await audioRenderer.getBufferSize(); + const path = '/data/file_example_WAV_2MG.wav'; // 需要渲染的音乐文件 + let ss = fileio.createStreamSync(path, 'r'); + const totalSize = fileio.statSync(path).size; // 音乐文件大小 + let discardHeader = new ArrayBuffer(bufferSize); + ss.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + let id = setInterval(() => { + if (this.isRelease) { // 如果渲染器状态为release,停止渲染 + ss.closeSync(); + stopRenderer(); + clearInterval(id); + } + if (this.isPlay) { + if (rlen >= totalSize) { // 如果音频文件已经被读取完,停止渲染 + ss.closeSync(); + stopRenderer(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + writeBuffer(buf); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 ``` -2. 使用on('interrupt')方法订阅音频中断事件。 +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会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 + + ```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); + ``` + +9. (可选)使用on('audioInterrupt')方法订阅渲染器音频中断事件,使用off('audioInterrupt')取消订阅事件。 当优先级更高或相等的Stream-B请求激活并使用输出设备时,Stream-A被中断。 @@ -59,42 +271,36 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 在音频中断的情况下,应用可能会碰到音频数据写入失败的问题。所以建议不感知、不处理中断的应用在写入音频数据前,使用audioRenderer.state检查播放器状态。而订阅音频中断事件,可以获取到更多详细信息,具体可参考[InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9)。 ```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,63 @@ 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()方法向缓冲区写入数据。 - - 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 - - ```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); +10. (可选)使用on('markReach')方法订阅渲染器标记到达事件,使用off('markReach')取消订阅事件。 - console.info('Actual written bytes: ' + writtenbytes); - if (writtenbytes < 0) { - console.error('Write buffer failed. check the state of renderer'); - } - } + 注册markReach监听后,当渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 - // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. - const bufferSize = await audioRenderer.getBufferSize(); - const path = '/data/file_example_WAV_2MG.wav'; - let ss = fileio.createStreamSync(path, 'r'); - const totalSize = 2146166; // file_example_WAV_2MG.wav - let rlen = 0; - let discardHeader = new ArrayBuffer(44); - ss.readSync(discardHeader); - rlen += 44; - - var id = setInterval(() => { - if (isPlay || isRelease) { - if (rlen >= totalSize || isRelease) { - ss.closeSync(); - stopRenderer(); - clearInterval(id); - } - let buf = new ArrayBuffer(bufferSize); - rlen += ss.readSync(buf); - console.info('Total bytes read from file: ' + rlen); - writeBuffer(buf); - } else { - console.info('check after next interval'); - } - } , 30); // interval to be set based on audio file format - ``` + ```js + audioRenderer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The renderer reached frame: ${reachNumber}`); + }); -5. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 + audioRenderer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + ``` - ```js - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } - } - ``` +11. (可选)使用on('periodReach')方法订阅渲染器区间标记到达事件,使用off('periodReach')取消订阅事件。 -6. 任务完成,调用release()方法释放相关资源。 + 注册periodReach监听后,**每当**渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioRenderer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the renderer reached frame: ${reachNumber} `); + }); - AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 + audioRenderer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + ``` - ```js - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } +12. (可选)使用on('stateChange')方法订阅渲染器音频状态变化事件。 - await audioRenderer.release(); + 注册stateChange监听后,当渲染器的状态发生改变时,会触发回调并返回当前渲染器的状态。 + + ```js + audioRenderer.on('stateChange', (audioState) => { + console.info('State change event Received'); + console.info(`Current renderer state is: ${audioState}`); + }); + ``` - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } +13. (可选)对on()方法的异常处理。 - } - ``` \ No newline at end of file + 在使用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异常 + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-routing-manager.md b/zh-cn/application-dev/media/audio-routing-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..4d5f07047ccd27952945dbc61bc7a37fcb8a0bbe --- /dev/null +++ b/zh-cn/application-dev/media/audio-routing-manager.md @@ -0,0 +1,112 @@ +# 路由、设备管理开发指导 + +## 简介 + +AudioRoutingManager提供了音频路由、设备管理的方法。开发者可以通过本指导了解应用如何通过AudioRoutingManager获取当前工作的输入、输出音频设备,监听音频设备的连接状态变化,激活通信设备等。 + +## 运作机制 + +该模块提供了路由、设备管理模块常用接口 + +**图1** 音量管理常用接口 + +![zh-ch_image_audio_routing_manager](figures/zh-ch_image_audio_routing_manager.png) + +**说明:** AudioRoutingManager主要接口有:获取设备列表信息、监听与取消监听设备连接状态、激活通信设备、查询通信设备激活状态。更多介绍请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + +## 开发指导 + +详细API含义可参考:[音频路由、设备管理API文档AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9) + +1. 创建AudioRoutingManager实例。 + + 在使用AudioRoutingManager的API前,需要使用getRoutingManager创建一个AudioRoutingManager实例。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + + ``` + +2. (可选)获取设备列表信息、监听设备链接状态变化。 + + 如果开发者需要获取设备列表信息(输入、输出、分布式输入、分布式输出等),或者监听音频设备的链接状态变化时,可参考并调用以下接口。 + + ```js + import audio from '@ohos.multimedia.audio'; + //创建AudioRoutingManager实例 + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + //获取全部音频设备信息(开发者可以根据自身需要填入适当的DeviceFlag) + async getDevices() { + await loadAudioRoutingManager(); + await audioRoutingManager.getDevices(audio.DeviceFlag.ALL_DEVICES_FLAG).then((data) => { + console.info(`getDevices success and data is: ${JSON.stringify(data)}.`); + }); + } + //监听音频设备状态变化 + async onDeviceChange() { + await loadAudioRoutingManager(); + await audioRoutingManager.on('deviceChange', audio.DeviceFlag.ALL_DEVICES_FLAG, (deviceChanged) => { + console.info('on device change type : ' + deviceChanged.type); + console.info('on device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } + //取消监听音频设备状态变化 + async offDeviceChange() { + await loadAudioRoutingManager(); + await audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('off device change type : ' + deviceChanged.type); + console.info('off device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } + //综合调用:先查询所有设备,设置监听,然后开发者手动变更设备连接(例如有线耳机),再次查询所有设备,最后取消设备状态变化的监听。 + async test(){ + await getDevices(); + await onDeviceChange()(); + //开发者手动断开/连接设备 + await getDevices(); + await offDeviceChange(); + } + ``` + +3. (可选)设置通信设备激活并查询激活状态。 + + ```js + import audio from '@ohos.multimedia.audio'; + //创建AudioRoutingManager实例 + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + //设置通信设备激活状态 + async setCommunicationDevice() { + await loadAudioRoutingManager(); + await audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('setCommunicationDevice true is success.'); + }); + } + //查询通信设备激活状态 + async isCommunicationDeviceActive() { + await loadAudioRoutingManager(); + await audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`CommunicationDevice state is: ${value}.`); + }); + } + //综合调用:先设置设备激活,然后查询设备状态。 + async test(){ + await setCommunicationDevice(); + await isCommunicationDeviceActive(); + } + ``` + diff --git a/zh-cn/application-dev/media/audio-volume-manager.md b/zh-cn/application-dev/media/audio-volume-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..d26175b8822b49aafd9a5e7a0e26b009a1e8d451 --- /dev/null +++ b/zh-cn/application-dev/media/audio-volume-manager.md @@ -0,0 +1,127 @@ +# 音量管理开发指导 + +## 简介 + +AudioVolumeManager提供了音量管理的方法。开发者可以通过本指导了解应用如何通过AudioVolumeManager获取指定流音量信息、监听铃声模式变化、设置麦克风静音等。 + +## 运作机制 + +该模块提供了音量管理模块常用接口 + +**图1** 音量管理常用接口 + +![zh-ch_image_audio_volume_manager](figures/zh-ch_image_audio_volume_manager.png) + +**说明:** AudioVolumeManager包含音量变化监听处理和音频音量组管理相关(AudioVolumeGroupManager),开发者调用AudioVolumeGroupManager的相关方法,需要先调用getVolumeGroupManager方法创建AudioVolumeGroupManager实例,从而调用对应的接口实现相应的功能,主要接口有:获取指定流的音量、设置麦克风静音、监听麦克风状态变化等。更多介绍请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + +## 约束与限制 + +开发者在进行麦克风管理开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE),如果要设置麦克风状态,则需要配置音频管理配置权限(ohos.permission.MANAGE_AUDIO_CONFIG),需注意该权限为系统级别权限。权限配置相关内容可参考:[访问控制授权申请指导](../security/accesstoken-guidelines.md) + +## 开发指导 + +详细API含义可参考:[音量管理API文档AudioVolumeManager](../reference/apis/js-apis-audio.md#audiovolumemanager9) + +1. 创建AudioVolumeGroupManager实例。 + + 在使用AudioVolumeGroupManager的API前,需要使用getVolumeGroupManager创建一个AudioStreamManager实例。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.error('audioVolumeGroupManager create success.'); + } + + ``` + +2. (可选)获取音量信息、铃声模式。 + + 如果开发者需要获取指定音频流的音量信息(铃声、语音电话、媒体、语音助手等),或者获取当前设备是静音、震动、响铃模式,可参考并调用以下接口。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + + //获取指定流的当前音量(范围为0 ~ 15) + async getVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getVolume success and volume is: ${value}.`); + }); + } + //获取指定流的最小音量 + async getMinVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getMinVolume success and volume is: ${value}.`); + }); + } + //获取指定流的最大音量 + async getMaxVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getMaxVolume success and volume is: ${value}.`); + }); + } + //获取当前铃声模式: 静音(0)| 震动(1) | 响铃(2) + async getRingerMode() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`getRingerMode success and RingerMode is: ${value}.`); + }); + } + ``` + +3. (可选)查询、设置、监听麦克风状态。 + + 如果开发者需要获取、设置麦克风状态,或者监听麦克风状态变化等信息,可参考并调用以下接口。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + + async on() { //监听麦克风状态变化 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); + }); + } + + async isMicrophoneMute() { //查询麦克风是否静音 + await audioVolumeGroupManager.audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`isMicrophoneMute is: ${value}.`); + }); + } + + async setMicrophoneMuteTrue() { //设置麦克风静音 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('setMicrophoneMute to mute.'); + }); + } + + async setMicrophoneMuteFalse() { //取消麦克风静音 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(false).then(() => { + console.info('setMicrophoneMute to not mute.'); + }); + } + async test(){ //综合调用:先设置监听,然后查询麦克风状态,设置麦克风静音后再查询状态,最后取消麦克风静音。 + await on(); + await isMicrophoneMute(); + await setMicrophoneMuteTrue(); + await isMicrophoneMute(); + await setMicrophoneMuteFalse(); + } + ``` + diff --git a/zh-cn/application-dev/media/camera.md b/zh-cn/application-dev/media/camera.md index 617c4107faa983dc2231c80578405be95cf93e1c..12c785c1d5cd84044cc43466661e515673fcb66c 100644 --- a/zh-cn/application-dev/media/camera.md +++ b/zh-cn/application-dev/media/camera.md @@ -89,22 +89,22 @@ if (!cameraOutputCap) { console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); } -let previewProfilesArray = cameraOutputCap.previewProfiles; +let previewProfilesArray = cameraOutputCap.GetPreviewProfiles(); if (!previewProfilesArray) { console.error("createOutput previewProfilesArray == null || undefined") } -let photoProfilesArray = cameraOutputCap.photoProfiles; +let photoProfilesArray = cameraOutputCap.GetPhotoProfiles(); if (!photoProfilesArray) { console.error("createOutput photoProfilesArray == null || undefined") } -let videoProfilesArray = cameraOutputCap.videoProfiles; +let videoProfilesArray = cameraOutputCap.GetVideoProfiles(); if (!videoProfilesArray) { console.error("createOutput videoProfilesArray == null || undefined") } -let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; +let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType(); if (!metadataObjectTypesArray) { console.error("createOutput metadataObjectTypesArray == null || undefined") } @@ -115,7 +115,7 @@ if (!previewOutput) { console.error("Failed to create the PreviewOutput instance.") } -// 创建ImageReceiver对象,并设置照片参数 +// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) // 获取照片显示SurfaceId let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() @@ -188,7 +188,7 @@ build() { controller: this.mXComponentController }) .onload(() => { // 设置onload回调 - // 设置Surface宽高(1920*1080) + // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) // 获取Surface ID globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png new file mode 100644 index 0000000000000000000000000000000000000000..710679f6cac0c30d06dffa97b0e80b3cebe80f79 Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_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/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..f2249cb4417dce2228fa045e7c90304e92ebf3a1 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -61,6 +61,7 @@ - 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) @@ -202,6 +203,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 +221,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) 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-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-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-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 0fddf9e9588d7165b64047f31cc65001127b671b..633b9aff701fdfc7309aeb6aaf1a84f1b3ed31a4 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,7 +709,7 @@ async function createTonePlayer(){ **系统接口:** 该接口为系统接口 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Volume | 名称 | 默认值 | 描述 | | :------------------------------ | :----- | :--------------------- | @@ -739,7 +746,7 @@ async function createTonePlayer(){ import audio from '@ohos.multimedia.audio'; async function getVolumeGroupInfos(){ - let volumegroupinfos = await audio.getAudioManager().getVolumeGroups(audio.LOCAL_NETWORK_ID); + let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) } getVolumeGroupInfos(); @@ -811,889 +818,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 + +setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void -getRoutingManager(callback: AsyncCallback<AudioRoutingManager>): void +音频参数设置,使用callback方式异步返回结果。 -获取AudioRoutingManager对象,使用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 -getRoutingManager(): Promise<AudioRoutingManager> +setAudioParameter(key: string, value: string): Promise<void> -获取AudioRoutingManager对象,使用Promise方式异步返回结果。 +音频参数设置,使用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 +### getAudioScene8+ -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -获取指定流的最小音量,使用Promise方式异步返回结果。 - -**系统能力:** 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+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -获取音频设备列表,使用callback方式异步返回结果。 +设置指定音量流静音,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY + +仅设置铃声(即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+ + +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +设置指定音量流静音,使用Promise方式异步返回结果。 -获取音频设备列表,使用Promise方式异步返回结果。 +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -**系统能力:** SystemCapability.Multimedia.Audio.Device +仅设置铃声(即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 +1791,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 +1800,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 +1825,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 +1847,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 +1856,13 @@ audioManager.isMicrophoneMute((err, value) => { }); ``` -### isMicrophoneMute +### isMicrophoneMute9+ isMicrophoneMute(): Promise<boolean> 获取麦克风静音状态,使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.MICROPHONE - -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Volume **返回值:** @@ -1790,20 +1872,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 +1892,4120 @@ on(type: 'volumeChange', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'volumeChange'(系统音量变化事件,检测到系统音量改变时,触发该事件)。 | -| callback | Callback<[VolumeEvent](#volumeevent8)> | 是 | 回调方法。 | - -**示例:** - -```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} `); -}); -``` - -### on('ringerModeChange')8+ - -on(type: 'ringerModeChange', callback: Callback\): void - -监听铃声模式变化事件。 - -**系统接口:** 该接口为系统接口 +| type | string | 是 | 事件回调类型,支持的事件为:'micStateChange'(系统麦克风状态变化事件,检测到系统麦克风状态改变时,触发该事件)。 | +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | 是 | 回调方法,返回变更后的麦克风状态。 | -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**错误码:** -**参数:** +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。 | -| callback | Callback<[AudioRingMode](#audioringmode)> | 是 | 回调方法。 | +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```js -audioManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); }); ``` -### on('deviceChange') +## AudioStreamManager9+ -on(type: 'deviceChange', callback: Callback): void +管理音频流。在使用AudioStreamManager的API前,需要使用[getStreamManager](#getstreammanager9)获取AudioStreamManager实例。 -设备更改。音频设备连接状态变化。 +### getCurrentAudioRendererInfoArray9+ -**系统能力:** SystemCapability.Multimedia.Audio.Device +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void + +获取当前音频渲染器的信息。使用callback异步回调。 + +**系统能力**: SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数,返回当前音频渲染器的信息。 | **示例:** ```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} `); +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}`); + } + } + } + } }); ``` -### off('deviceChange') +### getCurrentAudioRendererInfoArray9+ -off(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.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); -}); +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}`); + }); +} ``` -### on('interrupt') +### getCurrentAudioCapturerInfoArray9+ -on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void -请求焦点并开始监听音频打断事件(当应用程序的音频被另一个播放事件中断,回调通知此应用程序) +获取当前音频采集器的信息。使用callback异步回调。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。 | -| interrupt | AudioInterrupt | 是 | 音频打断事件类型的参数。 | -| callback | Callback<[InterruptAction](#interruptaction)> | 是 | 音频打断事件回调方法。 | +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数,返回当前音频采集器的信息。 | **示例:** ```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} `); +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}`); + } + } + } } }); ``` -### off('interrupt') +### getCurrentAudioCapturerInfoArray9+ -off(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.off('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to release the audio focus starts.'); - console.info(`Focus release 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}`); + }); +} ``` -### setAudioScene8+ - -setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void +### on('audioRendererChange')9+ -设置音频场景模式,使用callback方式异步返回结果。 +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void -**系统接口:** 该接口为系统接口 +监听音频渲染器更改事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :----------------------------------- | :--- | :------------------- | -| scene | AudioScene | 是 | 音频场景模式。 | -| callback | AsyncCallback | 是 | 用于返回结果的回调。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------- | --------- | ------------------------------------------------------------------------ | +| type | string | 是 | 事件类型,支持的事件`'audioRendererChange'`:当音频渲染器发生更改时触发。 | +| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```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('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}`); + } } - console.info('Callback invoked to indicate a successful setting of the audio scene mode.'); }); ``` -### setAudioScene8+ - -setAudioScene\(scene: AudioScene\): Promise +### off('audioRendererChange')9+ -设置音频场景模式,使用Promise方式返回异步结果。 +off(type: "audioRendererChange"): void -**系统接口:** 该接口为系统接口 +取消监听音频渲染器更改事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----------------------------------- | :--- | :------------- | -| scene | AudioScene | 是 | 音频场景模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ---------------- | +| type | string | 是 | 事件类型,支持的事件`'audioRendererChange'`:音频渲染器更改事件。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| :------------- | :------------------- | -| Promise | 用于返回结果的回调。 | +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```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('audioRendererChange'); +console.info('######### RendererChange Off is called #########'); ``` -### getAudioScene8+ +### on('audioCapturerChange')9+ -getAudioScene\(callback: AsyncCallback\): void +on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void -获取音频场景模式,使用callback方式返回异步结果。 +监听音频采集器更改事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :-------------------------------------------------- | :--- | :--------------------------- | -| callback | AsyncCallback<AudioScene> | 是 | 用于返回音频场景模式的回调。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | +| type | string | 是 | 事件类型,支持的事件`'audioCapturerChange'`:当音频采集器发生更改时触发。 | +| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getAudioScene((err, value) => { - if (err) { - console.error(`Failed to obtain 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 that the audio scene mode is obtained ${value}.`); }); ``` +### off('audioCapturerChange')9+ -### getAudioScene8+ - -getAudioScene\(\): Promise +off(type: "audioCapturerChange"): void; -获取音频场景模式,使用Promise方式返回异步结果。 +取消监听音频采集器更改事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Communication +**系统能力:** SystemCapability.Multimedia.Audio.Capturer -**返回值:** +**参数:** -| 类型 | 说明 | -| :-------------------------------------------- | :--------------------------- | -| Promise<AudioScene> | 用于返回音频场景模式的回调。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |是 | 事件类型,支持的事件`'audioCapturerChange'`:音频采集器更改事件。 | **示例:** ```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.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); -### getVolumeGroups9+ +``` -getVolumeGroups(networkId: string, callback: AsyncCallback\): void +### isActive9+ -获取音量组信息列表,使用callback方式异步返回结果。 +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -**系统接口:** 该接口为系统接口 +获取指定音量流是否为活跃状态,使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | 是 | 设备的网络id。本地设备audio.LOCAL_NETWORK_ID ,也可以通过getRoutingManager().getDevices()获取全部networkId。 | -| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | 是 | 回调,返回音量组信息列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调返回流的活跃状态,true为活跃,false为不活跃。 | **示例:** + ```js -let audioManager = audio.getAudioManager(); -audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => { +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); + console.error(`Failed to obtain the active status of the stream. ${err}`); return; } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### getVolumeGroups9+ - -getVolumeGroups(networkId: string\): Promise +### isActive9+ -获取音量组信息列表,使用promise方式异步返回结果。 +isActive(volumeType: AudioVolumeType): Promise<boolean> -**系统接口:** 该接口为系统接口 +获取指定音量流是否为活跃状态,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | 是 | 设备的网络id。本地设备audio.LOCAL_NETWORK_ID ,也可以通过getRoutingManager().getDevices()获取全部networkId。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | 音量组信息列表。 | +| 类型 | 说明 | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise回调返回流的活跃状态,true为活跃,false为不活跃。 | **示例:** ```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)) -} +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +}); ``` -### getGroupManager9+ +## AudioRoutingManager9+ -getGroupManager(groupId: number, 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 **参数:** | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| groupId | number | 是 | 音量组id。 | -| callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | 是 | 回调,返回一个音量组实例。 | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回设备列表。 | **示例:** ```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.'); - }); +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.'); +}); ``` -### getGroupManager9+ - -getGroupManager(groupId: number\): Promise +### getDevices9+ -获取音频组管理器,使用promise方式异步返回结果。 +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -**系统接口:** 该接口为系统接口 +获取音频设备列表,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------------------- | ---- | ---------------- | -| groupId | number | 是 | 音量组id。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise< [AudioGroupManager](#audiogroupmanager9) > | 音量组实例。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise回调返回设备列表。 | **示例:** ```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.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); +}); ``` -### getStreamManager9+ +### on9+ -getStreamManager(callback: AsyncCallback\): void +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -获取音频流管理器实例。使用callback方式异步返回结果。 +设备更改。音频设备连接状态变化。 -**系统能力:** SystemCapability.Multimedia.Audio.Core +**系统能力:** SystemCapability.Multimedia.Audio.Device **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | 是 | 返回音频流管理器实例。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **示例:** ```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; - } +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+ + +off(type: 'deviceChange', callback?: Callback): void -getStreamManager(): Promise +取消订阅音频设备连接变化事件。 -获取音频流管理器实例。使用Promise方式异步返回结果。 +**系统能力:** SystemCapability.Multimedia.Audio.Device -**系统能力:** SystemCapability.Multimedia.Audio.Core +**参数:** -**返回值:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../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 +let outputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} +``` + +### selectOutputDeviceByFilter9+ + +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void + +**系统接口:** 该接口为系统接口 + +根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | +| callback | AsyncCallback<void> | 是 | 回调,返回获取输出设备结果。 | + +**示例:** +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +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'); } + }); +} +``` + +### selectOutputDeviceByFilter9+ + +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> + +**系统接口:** 该接口为系统接口 + +根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------------- | +| Promise<void> | Promise返回选择输出设备结果。 | + +**示例:** + +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +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}`); + }) +} +``` + +## AudioRendererChangeInfo9+ + +描述音频渲染器更改信息。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | +| streamId | number | 是 | 否 | 音频流唯一id。 | +| clientUid | number | 是 | 否 | 音频渲染器客户端应用程序的Uid。
此接口为系统接口。 | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 是 | 否 | 音频渲染器信息。 | +| rendererState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口。| + +## AudioRendererChangeInfoArray9+ + +AudioRenderChangeInfo数组,只读。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**示例:** + +```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}`); + } 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}`); + 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}`); + } + } +}); +``` + +## AudioCapturerChangeInfo9+ + +描述音频采集器更改信息。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Capturer + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | +| streamId | number | 是 | 否 | 音频流唯一id。 | +| clientUid | number | 是 | 否 | 音频采集器客户端应用程序的Uid。
此接口为系统接口。 | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 否 | 音频采集器信息。 | +| capturerState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口。| + +## AudioCapturerChangeInfoArray9+ + +AudioCapturerChangeInfo数组,只读。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + +**示例:** + +```js +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +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}`); + } + } +}); +``` + +## AudioDeviceDescriptor + +描述音频设备。 + +**系统能力:** 以下各项对应的系统能力均为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。
此接口为系统接口。 | + +## AudioDeviceDescriptors + +设备属性数组类型,为[AudioDeviceDescriptor](#audiodevicedescriptor)的数组,只读。 + +**示例:** + +```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实例。 + +**系统接口:** 该接口为系统接口 + +| 名称 | 类型 | 必填 | 说明 | +| -------------| ---------------------------------------- | ---- | -------------- | +| 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 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------------------------------------------- | :--- | :--------------------- | +| 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<[AudioRendererInfo](#audiorendererinfo8)\> | 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}`) +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +}); +``` + +### 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 -audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value}.`); +audioRenderer.start().then(() => { + console.info('Renderer started'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### getMinVolume9+ - -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### pause8+ -获取指定流的最小音量,使用callback方式异步返回结果。 +pause(callback: AsyncCallback\): void -**系统接口:** 该接口为系统接口 +暂停渲染。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回最小音量。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | **示例:** ```js -audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioRenderer.pause((err) => { if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); - return; + console.error('Renderer pause failed'); + } else { + console.info('Renderer paused.'); } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` -### getMinVolume9+ - -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -获取指定流的最小音量,使用Promise方式异步返回结果。 - -**系统接口:** 该接口为系统接口 +### pause8+ -**系统能力:** SystemCapability.Multimedia.Audio.Volume +pause(): Promise\ -**参数:** +暂停渲染。使用Promise方式异步返回结果。 -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------- | -| Promise<number> | Promise回调返回最小音量。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | **示例:** ```js -audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); +audioRenderer.pause().then(() => { + console.info('Renderer paused'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### getMaxVolume9+ - -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### drain8+ -获取指定流的最大音量,使用callback方式异步返回结果。 +drain(callback: AsyncCallback\): void -**系统接口:** 该接口为系统接口 +检查缓冲区是否已被耗尽。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ---------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<number> | 是 | 回调返回最大音量大小。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | **示例:** ```js -audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioRenderer.drain((err) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; + console.error('Renderer drain failed'); + } else { + console.info('Renderer drained.'); } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getMaxVolume9+ +### drain8+ -getMaxVolume(volumeType: AudioVolumeType): Promise<number> +drain(): Promise\ -获取指定流的最大音量,使用Promise方式异步返回结果。 +检查缓冲区是否已被耗尽。使用Promise方式异步返回结果。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**返回值:** -**参数:** +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +**示例:** -**返回值:** +```js +audioRenderer.drain().then(() => { + console.info('Renderer drained successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); +``` -| 类型 | 说明 | -| --------------------- | ----------------------------- | -| Promise<number> | Promise回调返回最大音量大小。 | +### stop8+ + +stop(callback: AsyncCallback\): void + +停止渲染。使用callback方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | **示例:** ```js -audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); +audioRenderer.stop((err) => { + if (err) { + console.error('Renderer stop failed'); + } else { + console.info('Renderer stopped.'); + } }); ``` -### mute9+ +### stop8+ -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void +stop(): Promise\ -设置指定音量流静音,使用callback方式异步返回结果。 +停止渲染。使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +**返回值:** -**系统接口:** 该接口为系统接口 +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**示例:** + +```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 **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | -| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 返回回调的结果。 | **示例:** ```js -audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioRenderer.release((err) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); - return; + console.error('Renderer release failed'); + } else { + console.info('Renderer released.'); } - console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### mute9+ +### release8+ -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> +release(): Promise\ -设置指定音量流静音,使用Promise方式异步返回结果。 +释放渲染器。使用Promise方式异步返回结果。 -**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY +**系统能力:** SystemCapability.Multimedia.Audio.Renderer -仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 +**返回值:** -**系统接口:** 该接口为系统接口 +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise方式异步返回结果。 | -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**示例:** + +```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 **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| mute | boolean | 是 | 静音状态,true为静音,false为非静音。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | --------------------------------------------------- | +| 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}`); + } +}); +``` + +### write8+ + +write(buffer: ArrayBuffer): Promise\ + +写入缓冲区。使用Promise方式异步返回结果。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **返回值:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<void> | Promise回调表示成功还是失败。 | +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise返回结果,如果成功,返回写入的字节数,否则返回errorcode。 | **示例:** ```js -audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); +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}`); }); ``` -### isMute9+ - -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### getAudioTime8+ -获取指定音量流是否被静音,使用callback方式异步返回结果。 +getAudioTime(callback: AsyncCallback\): void -**系统接口:** 该接口为系统接口 +获取时间戳(从 1970 年 1 月 1 日开始)。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Volume +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | -| callback | AsyncCallback<boolean> | 是 | 回调返回流静音状态,true为静音,false为非静音。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | 是 | 回调返回时间戳。 | **示例:** ```js -audioGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the mute status. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); +audioRenderer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -### isMute9+ - -isMute(volumeType: AudioVolumeType): Promise<boolean> - -获取指定音量流是否被静音,使用Promise方式异步返回结果。 - -**系统接口:** 该接口为系统接口 +### getAudioTime8+ -**系统能力:** SystemCapability.Multimedia.Audio.Volume +getAudioTime(): Promise\ -**参数:** +获取时间戳(从 1970 年 1 月 1 日开始)。使用Promise方式异步返回结果。 -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **返回值:** -| 类型 | 说明 | -| ---------------------- | ------------------------------------------------------ | -| Promise<boolean> | Promise回调返回流静音状态,true为静音,false为非静音。 | +| 类型 | 描述 | +| ---------------- | ----------------------- | +| Promise\ | Promise回调返回时间戳。 | **示例:** ```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().then((timestamp) => { + console.info(`Current timestamp: ${timestamp}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -## AudioStreamManager9+ - -管理音频流。在使用AudioStreamManager的API前,需要使用[getStreamManager](#getstreammanager9)获取AudioStreamManager实例。 - -### getCurrentAudioRendererInfoArray9+ +### getBufferSize8+ -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +getBufferSize(callback: AsyncCallback\): void -获取当前音频渲染器的信息。使用callback异步回调。 +获取音频渲染器的最小缓冲区大小。使用callback方式异步返回结果。 -**系统能力**: SystemCapability.Multimedia.Audio.Renderer +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | -------- | --------------------------- | -| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | 是 | 回调函数,返回当前音频渲染器的信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 回调返回缓冲区大小。 | **示例:** ```js -audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); +let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { 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}`); - } - } - } + console.error('getBufferSize error'); } }); ``` -### getCurrentAudioRendererInfoArray9+ +### getBufferSize8+ -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +getBufferSize(): Promise\ -获取当前音频渲染器的信息。使用Promise异步回调。 +获取音频渲染器的最小缓冲区大小。使用Promise方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **返回值:** -| 类型 | 说明 | -| ---------------------------------------------------------------------------------| --------------------------------------- | -| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise对象,返回当前音频渲染器信息。 | +| 类型 | 说明 | +| ---------------- | --------------------------- | +| Promise\ | promise回调返回缓冲区大小。 | **示例:** ```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().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +}); ``` -### getCurrentAudioCapturerInfoArray9+ +### setRenderRate8+ -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void -获取当前音频采集器的信息。使用callback异步回调。 +设置音频渲染速率。使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | -| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | 是 | 回调函数,返回当前音频采集器的信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | 是 | 渲染的速率。 | +| callback | AsyncCallback\ | 是 | 用于返回执行结果的回调。 | **示例:** ```js -audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { if (err) { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + console.error('Failed to set params'); } else { - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - } -}); -``` - -### getCurrentAudioCapturerInfoArray9+ - -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> - -获取当前音频采集器的信息。使用Promise异步回调。 - -**系统能力:** SystemCapability.Multimedia.Audio.Renderer - -**返回值:** - -| 类型 | 说明 | -| -----------------------------------------------------------------------------| ----------------------------------- | -| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise对象,返回当前音频渲染器信息。 | - -**示例:** - -```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}`); - }); -} + 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+ -### on9+ - -on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void +setVolume(volume: number, callback: AsyncCallback\): void -设备更改。音频设备连接状态变化。 +设置应用的音量。使用Callback回调返回执行结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| deviceFlag | [DeviceFlag](#deviceflag) | 是 | 设备类型的flag。 | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -----------| ------ | -------------- | +|volume | number | 是 | 音量值。| +|callback | AsyncCallback\ | 是 |回调返回执行结果。| **示例:** ```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); - }); +audioRenderer.setVolume(10, (err, data)=>{ + if(err){ + console.error(`setVolume Fail: ${err}`); } + console.info('setVolume Success!'); }); ``` -### off9+ +### on('audioInterrupt')9+ -off(type: 'deviceChange', callback?: Callback): void +on(type: 'audioInterrupt', callback: Callback\): void -取消订阅音频设备连接变化事件。 +监听音频中断事件。使用callback获取中断事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Interrupt **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| 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.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); - }); +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; + } } }); ``` -### selectInputDevice9+ - -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### on('markReach')8+ -选择音频输入设备,当前只能选择一个输入设备,使用callback方式异步返回结果。 +on(type: "markReach", frame: number, callback: Callback<number>): void -**系统接口:** 该接口为系统接口 +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输入设备类。 | -| callback | AsyncCallback<void> | 是 | 回调,返回选择输入设备结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :---------------------------------------- | +| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | +| callback | Callback\ | 是 | 触发事件时调用的回调。 | **示例:** -```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.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); + } +}); ``` -### on('micStateChange')9+ -on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void +### off('markReach') 8+ -监听系统麦克风状态更改事件 +off(type: 'markReach'): void -目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。 +取消订阅标记事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'micStateChange'(系统麦克风状态变化事件,检测到系统麦克风状态改变时,触发该事件)。 | -| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | 是 | 回调方法,返回变更后的麦克风状态。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :------------------------------------------------ | +| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'markReach'。 | **示例:** ```js -let audioManager = audio.getAudioManager(); -audioManager.getRoutingManager.on('micStateChange', (micStateChange) => { - console.info(`Current microphone status is: ${micStateChange.mute} `); -}); +audioRenderer.off('markReach'); ``` -### selectInputDevice9+ - -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> +### on('periodReach') 8+ -**系统接口:** 该接口为系统接口 +on(type: "periodReach", frame: number, callback: Callback<number>): void -选择音频输入设备,当前只能选择一个输入设备,使用Promise方式异步返回结果。 +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,触发回调并返回设定的值。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输入设备类。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------- | -| Promise<void> | Promise返回选择输入设备结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'periodReach'。 | +| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | +| callback | Callback\ | 是 | 触发事件时调用的回调。 | **示例:** ```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}`); - }); - }); -} +audioRenderer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); + } +}); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### off('periodReach') 8+ -选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。 +off(type: 'periodReach'): void -**系统接口:** 该接口为系统接口 +取消订阅标记事件。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Renderer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | -| callback | AsyncCallback<void> | 是 | 回调,返回获取输出设备结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| :----- | :----- | :--- | :-------------------------------------------------- | +| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'periodReach'。 | **示例:** -```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'); } - }); - }); -} +```js +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> +### getCapturerInfo8+ -**系统接口:** 该接口为系统接口 +getCapturerInfo(callback: AsyncCallback): void -根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。 +获取采集器信息。使用callback方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Device +**系统能力:** SystemCapability.Multimedia.Audio.Capturer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | 是 | 过滤条件类。 | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 输出设备类。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------------- | -| Promise<void> | Promise返回选择输出设备结果。 | - -**示例:** - -```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; +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :-------------------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回采集器信息。 | -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}`); - }) - }); -} +**示例:** + +```js +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+ + +start(): Promise -获取当前被创建的音频渲染器的信息,使用Promise方式异步返回结果。 +启动音频采集器。使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** 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\ | 是 | 返回回调的结果。 | - -**示例:** - -```js -audioRenderer.stop((err) => { - if (err) { - console.error('Renderer stop failed'); - } else { - console.info('Renderer stopped.'); +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :--------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区大小。 | + +**示例:** + +```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}`); + }); } }); ``` -### 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+ +## ToneType 9+ -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异步回调。 +### release9+ -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +release(callback: AsyncCallback<void>): void -**参数:** +释放与此TonePlay对象关联的资源。使用callback方式异步返回结果。 -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------------- | ------ | ---------- | -| mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。 | +**系统能力:** SystemCapability.Multimedia.Audio.Tone -**返回值:** +**参数:** -| 类型 | 说明 | -| ------------------- | ----------------------------- | -| Promise<void> | 以Promise对象返回结果,设置成功时返回undefined,否则返回error。 | +| 参数名 | 类型 | 必填 | 说明 | +| :------- | :------------------- | :--- | :---------------------------- | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** ```js -let mode = 0; -audioRenderer.setInterruptMode(mode).then(data=>{ - console.info('setInterruptMode Success!'); -}).catch((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 '); + } }); ``` -### setInterruptMode9+ -setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void +### release9+ -设置应用的焦点模型。使用Callback回调返回执行结果。 +release(): Promise<void> -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +释放与此TonePlay对象关联的资源。使用Promise方式异步返回结果。 -**参数:** +**系统能力:** SystemCapability.Multimedia.Audio.Tone -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ----------------------------------- | ------ | -------------- | -|mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。| -|callback | AsyncCallback\ | 是 |回调返回执行结果。| +**返回值:** + +| 类型 | 说明 | +| :------------- | :---------------------------- | +| Promise | 使用Promise方式异步返回结果。 | **示例:** ```js -let mode = 1; -audioRenderer.setInterruptMode(mode, (err, data)=>{ - if(err){ - console.error(`setInterruptMode Fail: ${err}`); - } - console.info('setInterruptMode Success!'); +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); }); ``` -### on('interrupt')9+ -on(type: 'interrupt', callback: Callback\): void +## ActiveDeviceType(deprecated) -监听音频中断事件。使用callback获取中断事件。 - -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +枚举,活跃设备类型。 -**参数:** +> **说明:** +> 从 API version 9 开始废弃,建议使用[CommunicationDeviceType](#communicationdevicetype9)替代。 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件为:'interrupt'(中断事件被触发,音频播放被中断。) | -| callback | Callback<[InterruptEvent](#interruptevent9)> | 是 | 被监听的中断事件的回调。 | +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device -**示例:** +| 名称 | 默认值 | 描述 | +| ------------- | ------ | ---------------------------------------------------- | +| SPEAKER | 2 | 扬声器。 | +| BLUETOOTH_SCO | 7 | 蓝牙设备SCO(Synchronous Connection Oriented)连接。 | -```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; - } - } -}); -``` +## InterruptActionType(deprecated) -### on('markReach')8+ +枚举,中断事件返回类型。 -on(type: "markReach", frame: number, callback: Callback<number>): void +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 -订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +| 名称 | 默认值 | 描述 | +| -------------- | ------ | ------------------ | +| TYPE_ACTIVATED | 0 | 表示触发焦点事件。 | +| TYPE_INTERRUPT | 1 | 表示音频打断事件。 | -**参数:** +## AudioInterrupt(deprecated) -| 参数名 | 类型 | 必填 | 说明 | -| :------- | :----------------------- | :--- | :---------------------------------------- | -| type | string | 是 | 事件回调类型,支持的事件为:'markReach'。 | -| frame | number | 是 | 触发事件的帧数。 该值必须大于 0。 | -| callback | Callback\ | 是 | 触发事件时调用的回调。 | +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 -**示例:** +音频监听事件传入的参数。 -```js -audioRenderer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } -}); -``` +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer +| 名称 | 类型 | 必填 | 说明 | +| --------------- | --------------------------- | ---- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | 是 | 音频流使用类型。 | +| contentType | [ContentType](#contenttype) | 是 | 音频打断媒体类型。 | +| pauseWhenDucked | boolean | 是 | 音频打断时是否可以暂停音频播放(true表示音频播放可以在音频打断期间暂停,false表示相反)。 | -### off('markReach') 8+ +## InterruptAction(deprecated) -off(type: 'markReach'): void +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃。 -取消订阅标记事件。 +音频打断/获取焦点事件的回调方法。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer -**参数:** +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontype) | 是 | 事件返回类型。TYPE_ACTIVATED为焦点触发事件,TYPE_INTERRUPT为音频打断事件。 | +| type | [InterruptType](#interrupttype) | 否 | 打断事件类型。 | +| hint | [InterruptHint](#interrupthint) | 否 | 打断事件提示。 | +| activated | boolean | 否 | 获得/释放焦点。true表示焦点获取/释放成功,false表示焦点获得/释放失败。 | -| 参数名 | 类型 | 必填 | 说明 | -| :----- | :----- | :--- | :------------------------------------------------ | -| type | string | 是 | 要取消订阅事件的类型。支持的事件为:'markReach'。 | +### setVolume(deprecated) -**示例:** +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void -```js -audioRenderer.off('markReach'); -``` +设置指定流的音量,使用callback方式异步返回结果。 -### on('periodReach') 8+ +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setVolume](#setvolume9)替代。 -on(type: "periodReach", frame: number, callback: Callback<number>): void +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被循环调用。 +仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。 -**系统能力:** SystemCapability.Multimedia.Audio.Renderer +**系统能力:** 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) -getStreamInfo(): Promise +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -获取采集器流信息。使用Promise方式异步返回结果。 +获取指定流的最大音量,使用Promise方式异步返回结果。 -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[getMaxVolume](#getmaxvolume9)替代。 -**返回值:** +**系统能力:** SystemCapability.Multimedia.Audio.Volume -| 类型 | 说明 | -| :--------------------------------------------- | :------------------------------ | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | 使用Promise方式异步返回流信息。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | 是 | 音量流类型。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ----------------------------- | +| 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+ - -read(size: number, isBlockingRead: boolean): Promise - -读入缓冲区。使用Promise方式异步返回结果。 +setRingerMode(mode: AudioRingMode): Promise<void> -**系统能力:** SystemCapability.Multimedia.Audio.Capturer +设置铃声模式,使用Promise方式异步返回结果。 -**参数:** +> **说明:** +> 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的[setRingerMode](#setringermode9)替代。 -| 参数名 | 类型 | 必填 | 说明 | -| :------------- | :------ | :--- | :--------------- | -| size | number | 是 | 读入的字节数。 | -| isBlockingRead | boolean | 是 | 是否阻塞读操作。 | +**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY -**返回值:** +仅在静音和非静音状态切换时需要该权限。 -| 类型 | 说明 | -| :-------------------- | :----------------------------------------------------- | -| Promise | 如果操作成功,返回读取的缓冲区数据;否则返回错误代码。 | +**系统能力:** SystemCapability.Multimedia.Audio.Communication -**示例:** +**参数:** -```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}`); +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | 是 | 音频铃声模式。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| 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.'); }); ``` +### 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 +> **说明:** +> 从 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-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md new file mode 100644 index 0000000000000000000000000000000000000000..144887f76d9d62e5eda6ea2790bff6a2e38c4c24 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-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.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +var 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.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +var 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.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +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.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +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.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +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.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +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-bundle-defaultAppManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md index 1508fd7c192fc20c0c38699176d3fe0b6c1206c3..202f1042a292d31e6882f77383e71cc1a936cd33 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @@ -9,7 +9,7 @@ ## 导入模块 ``` -import defaultAppMgr from '@ohos.bundle.defaultAppManager' +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; ``` ## defaultAppMgr.ApplicationType 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-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-resultset.md b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md index 19648104db323d6f2c89f71ce52e027cf317e7c8..221f6ae908a9831104324c9579232c191e29595b 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 @@ -124,7 +124,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) => { @@ -157,7 +157,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) => { @@ -185,7 +185,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) => { @@ -212,7 +212,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) => { @@ -239,7 +239,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) => { @@ -266,7 +266,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) => { @@ -417,7 +417,7 @@ close(): void ```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-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-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-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-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..96022038df5110f77024b83733eec4c9e126267e 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,20 @@ 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 powerKeyCode = 18; try { - inputConsumer.on(inputConsumer.SubscribeType.KEY, keyOptions, callback); + inputConsumer.on("key", {preKeys: [], finalKey: powerKeyCode, 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 +51,7 @@ try { off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void -停止监听组合按键事件。 +取消订阅组合按键。 **系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer @@ -61,35 +59,49 @@ 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 callback = function (keyOptions) { + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); +} +let keyOption = {preKeys: [], finalKey: powerKeyCode, isFinalKeyDown: true, finalKeyDownDuration: 0}; +try { + inputConsumer.on("key", keyOption, callback); + inputConsumer.off("key", keyOption, callback); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` +```js +// 取消订阅所有回调函数 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: [], finalKey: powerKeyCode, isFinalKeyDown: true, finalKeyDownDuration: 0}; try { - inputConsumer.off(inputConsumer.SubscribeType.KEY, keyOptions, callback); + inputConsumer.on("key", keyOption, callback); + inputConsumer.off("key", keyOption); } 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-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..08383f51ffe342900ed135280352af89b4b31b0f 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'}, (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'}).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,391 @@ 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" +} +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" +} +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" +} +let inputMethodSubProperty = { + id: "com.example.kikainput", + label: "ServiceExtAbility" +} +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 +597,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 +620,13 @@ InputMethodController.showSoftKeyboard((err) => { }) ``` - -### showSoftKeyboard9+ ### +### showSoftKeyboard9+ showSoftKeyboard(): Promise<void> -显示软键盘,使用Promise异步回调。参数个数为0,否则抛出异常。 +显示软键盘,使用Promise异步回调。 + +**需要权限:** ohos.permission.CONNECT_IME_ABILITY **系统能力:** SystemCapability.MiscServices.InputMethodFramework @@ -264,21 +636,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 +669,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 +692,14 @@ InputMethodController.hideSoftKeyboard((err) => { }) ``` - -### hideSoftKeyboard9+ ### +### hideSoftKeyboard9+ hideSoftKeyboard(): Promise<void> 隐藏软键盘,使用Promise异步回调。参数个数为0,否则抛出异常。 +**需要权限:** ohos.permission.CONNECT_IME_ABILITY + **系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -315,54 +708,356 @@ 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' +} +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', +} +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 +1065,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 +1198,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 +1222,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 +1256,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 +1278,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..d98281b3b4215925417165965c8982f2723f0164 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,194 @@ 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 = inputMethodAbility.getInputMethodAbility(); +``` + +## inputMethodEngine.getKeyboardDelegate9+ + +getKeyboardDelegate(): KeyboardDelegate + +获取客户端监听实例。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------- | ---------------- | +| [KeyboardDelegate](#keyboarddelegate) | 客户端监听实例。 | + +**示例:** + +```js +let KeyboardDelegate = inputMethodAbility.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.off('inputStart', (kbController, textInputClient) => { - console.log('delete inputStart notification.'); - }); - ``` +```js +inputMethodEngine.getInputMethodEngine().off('inputStart', (kbController, textInputClient) => { + console.log('delete inputStart notification.'); +}); +``` ### on('inputStop')9+ on(type: 'inputStop', callback: () => void): void -订阅停止输入法应用事件,使用callback回调。 +订阅停止输入法应用事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -161,19 +210,19 @@ on(type: 'inputStop', callback: () => void): void **示例:** - ```js -InputMethodEngine.getInputMethodEngine().on('inputStop', () => { +```js +inputMethodEngine.getInputMethodEngine().on('inputStop', () => { console.log('inputMethodEngine inputStop'); }); - ``` +``` ### off('inputStop')9+ off(type: 'inputStop', callback: () => void): void -取消订阅停止输入法应用事件。使用callback回调。 +取消订阅停止输入法应用事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -184,65 +233,65 @@ off(type: 'inputStop', callback: () => void): void **示例:** - ```js -InputMethodEngine.getInputMethodEngine().off('inputStop', () => { +```js +inputMethodEngine.getInputMethodEngine().off('inputStop', () => { console.log('inputMethodEngine 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) => { +```js +inputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => { console.log('inputMethodEngine 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', () => { +```js +inputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => { console.log('inputMethodEngine delete setCallingWindow notification.'); }); - ``` +``` ### on('keyboardShow'|'keyboardHide') on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -订阅输入法事件。参数个数为2,参数1为napi_string,参数2为napi_function,否则抛出异常。 +订阅输入法事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -253,22 +302,217 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void **示例:** - ```js - InputMethodEngine.on('keyboardShow', () => { - console.log('inputMethodEngine keyboardShow.'); - }); - InputMethodEngine.on('keyboardHide', () => { - console.log('inputMethodEngine keyboardHide.'); - }); - ``` +```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 -取消订阅输入法事件。参数个数不为1或2抛出异常。若为1,参数不为napi_string抛出异常;若为2,参数1不为napi_string,参数2不为napi_function抛出异常。参数若为1,取消此类型所有监听;参数若为2,取消此类型当前监听。 +取消订阅输入法事件。使用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.getInputMethodAbility().off('inputStart', (kbController, inputClient) => { + console.log('delete inputStart notification.'); +}); +``` + +### on('inputStop')9+ + +on(type: 'inputStop', callback: () => void): void + +订阅停止输入法应用事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘inputStop’时表示订阅停止输入法应用事件。 | +| callback | void | 是 | 回调函数。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().on('inputStop', () => { + console.log('inputMethodAbility inputStop'); +}); +``` + +### off('inputStop')9+ + +off(type: 'inputStop', callback: () => void): void + +取消订阅停止输入法应用事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘inputStop’时表示订阅停止输入法应用事件。 | +| callback | void | 是 | 回调函数。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().off('inputStop', () => { + console.log('inputMethodAbility delete inputStop notification.'); +}); +``` + +### on('setCallingWindow')9+ + +on(type: 'setCallingWindow', callback: (wid:number) => void): void + +订阅设置调用窗口事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘setCallingWindow’时表示订阅设置调用窗口事件。 | +| callback | number | 是 | 回调函数,返回调用方window id。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().on('setCallingWindow', (wid) => { + console.log('inputMethodAbility setCallingWindow'); +}); +``` + +### off('setCallingWindow')9+ + +off(type: 'setCallingWindow', callback: (wid:number) => void): void + +取消订阅设置调用窗口事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘setCallingWindow’时表示订阅设置调用窗口事件。 | +| callback | number | 是 | 回调函数,返回调用方window id。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().off('setCallingWindow', () => { + console.log('inputMethodAbility delete setCallingWindow notification.'); +}); +``` + +### on('keyboardShow'|'keyboardHide')9+ + +on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void + +订阅输入法事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为'keyboardShow',表示订阅输入法显示。
- type为'keyboardHide',表示订阅输入法隐藏。 | +| callback | void | 否 | 回调函数。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().on('keyboardShow', () => { + console.log('InputMethodAbility keyboardShow.'); +}); +inputMethodEngine.getInputMethodAbility().on('keyboardHide', () => { + console.log('InputMethodAbility keyboardHide.'); +}); +``` + +### off('keyboardShow'|'keyboardHide')9+ + +off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void + +取消订阅输入法事件。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -279,101 +523,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异步回调。 -## KeyboardDelegate +**系统能力:** SystemCapability.MiscServices.InputMethodFramework -下列API示例中都需使用[createKeyboardDelegate](#createKeyboardDelegate)回调获取到KeyboardDelegate实例,再通过此实例调用对应方法。 +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
- type为'setSubtype',表示取消订阅输入法子类型设置。
- type为'keyboardHide',表示订阅输入法隐藏。 | +| callback | InputMethodSubtype | 是 | 回调函数,返回调用方的输入法子类型。 | + +**示例:** + +```js +inputMethodEngine.getInputMethodAbility().off('setSubtype', () => { + console.log('InputMethodAbility delete setSubtype notification.'); +}); +``` + +## 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 +671,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 +694,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 +720,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 +744,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 +767,138 @@ 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 + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** + +```js +async function InputMethodEngine() { + await KeyboardController.hide().then(() => { + console.info('hide success.'); + }).catch((err) => { + console.info('hide err: ' + JSON.stringify(err)); + }); +} +``` + +### hideKeyboard(deprecated) + +hideKeyboard(callback: AsyncCallback<void>): void + +隐藏输入法。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[hide](#hide9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback<void> | 否 | 回调函数。当输入法隐藏成功,err为undefined,否则为错误对象。 | + +**示例:** + +```js +KeyboardController.hideKeyboard((err) => { + if (err === undefined) { + console.error('hideKeyboard err: ' + JSON.stringify(err)); + return; + } + console.log('hideKeyboard success.'); +}); +``` + +### hideKeyboard(deprecated) + +hideKeyboard(): Promise<void> + +隐藏输入法。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[hide](#hide9-1)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** @@ -549,52 +911,785 @@ hideKeyboard(): Promise<void> ```js async function InputMethodEngine() { await KeyboardController.hideKeyboard().then(() => { - console.info('hideKeyboard promise.'); + console.info('hideKeyboard success.'); + }).catch((err) => { + console.info('hideKeyboard err: ' + JSON.stringify(err)); + }); +} +``` + +## InputClient9+ + +下列API示例中都需使用[on('inputStart')](#oninputstart9)回调获取到InputClient实例,再通过此实例调用对应方法。 + +### sendKeyFunction9+ + +sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void + +发送功能键。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + + **参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| action | number | 是 | 编辑框属性。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当功能键发送成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + + **示例:** + +```js +try { + InputClient.sendKeyFunction(keyFunction, (err, result) => { + if (err) { + console.error('sendKeyFunction err: ' + JSON.stringify(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异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| action | number | 是 | 编辑框属性。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示功能键发送成功;返回false表示功能键发送失败。| + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** + +```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)); +} +``` + +### getForward9+ + +getForward(length:number, callback: AsyncCallback<string>): void + +获取光标前固定长度的文本。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| 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 +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异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise对象,返回光标前固定长度的文本。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** + +```js +async function InputMethodAbility() { + let length = 1; + try { + await InputClient.getForward(length).then((text) => { + console.info('getForward resul: ' + text); + }).catch((err) => { + console.error('getForward err: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('getForward err: ' + JSON.stringify(err)); + } +} +``` + +### getBackward9+ + +getBackward(length:number, callback: AsyncCallback<string>): void + +获取光标后固定长度的文本。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| 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 +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)); +} +``` + +### getBackward9+ + +getBackward(length:number): Promise<string> + +获取光标后固定长度的文本。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| length | number | 是 | 文本长度。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise对象,返回光标后固定长度的文本。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** + +```js +async function InputMethodAbility() { + let length = 1; + try { + await InputClient.getBackward(length).then((text) => { + console.info('getBackward result: ' + text); + }).catch((err) => { + console.error('getBackward err: ' + JSON.stringify(err)); + }); + } catch (err) { + 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 InputMethodAbility() { + let length = 1; + try { + await InputClient.deleteForward(length).then((result) => { + if (result) { + console.info('Success to deleteForward. '); + } else { + console.error('Failed to deleteForward. '); + } + }).catch((err) => { + console.error('deleteForward err: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('deleteForward err: ' + JSON.stringify(err)); + } +} +``` + +### deleteBackward9+ + +deleteBackward(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.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)); +} +``` + +### deleteBackward9+ + +deleteBackward(length:number): Promise<boolean> + +删除光标后固定长度的文本。使用callback异步回调。 + +**系统能力:** 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 InputMethodAbility() { + let length = 1; + await InputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Success to deleteBackward. '); + } else { + console.error('Failed to deleteBackward. '); + } + }).catch((err) => { + console.error('deleteBackward err: ' + JSON.stringify(err)); + }); +} +``` + +### insertText9+ + +insertText(text:string, callback: AsyncCallback<boolean>): void + +插入文本。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| text | string | 是 | 文本。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当文本插入成功,err为undefined,data为true;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +InputClient.insertText('test', (err, result) => { + if (err) { + console.error('insertText err: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Success to insertText. '); + } else { + console.error('Failed to insertText. '); + } +}); +``` + +### insertText9+ + +insertText(text:string): Promise<boolean> + +插入文本。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| text | string | 是 | 文本。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示插入文本成功;返回false表示插入文本失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +async function InputMethodAbility() { + try { + await InputClient.insertText('test').then((result) => { + if (result) { + console.info('Success to insertText. '); + } else { + console.error('Failed to insertText. '); + } + }).catch((err) => { + console.error('insertText err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.error('insertText err: ' + JSON.stringify(err)); + } +} +``` + +### getEditorAttribute9+ + +getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void + +获取编辑框属性值。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| callback | AsyncCallback<[EditorAttribute](#editorattribute)> | 是 | 回调函数。当编辑框属性值获取成功,err为undefined,data为编辑框属性值;否则为错误对象。| + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** + +```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)); +}); +``` + +### getEditorAttribute9+ + +getEditorAttribute(): Promise<EditorAttribute> + +获取编辑框属性值。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<[EditorAttribute](#editorattribute)> | Promise对象,返回编辑框属性值。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** + +```js +async function InputMethodEngine() { + await InputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); }).catch((err) => { - console.info('hideKeyboard promise err: ' + err.msg); + console.error('getEditorAttribute err: ' + JSON.stringify(err)); + }); +} +``` + +### moveCursor9+ + +moveCursor(direction: number, callback: AsyncCallback<void>): void + +移动光标。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | -------------- | +| direction | number | 是 | 光标移动方向。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当光标移动成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** + +```js +try { + InputClient.moveCursor(inputMethodAbility.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异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | -------------- | +| direction | number | 是 | 光标移动方向。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**示例:** + +```js +async function InputMethodAbility() { + try { + await InputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then((err) => { + if (err) { + console.log('moveCursor err: ' + JSON.stringify(err)); + return; + } + console.log('moveCursor success'); + }).catch((err) => { + console.error('moveCursor success err: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('moveCursor err: ' + JSON.stringify(err)); + } } ``` -## TextInputClient +## EditorAttribute + +编辑框属性值。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------------ | -------- | ---- | ---- | ------------------ | +| enterKeyType | number | 是 | 否 | 编辑框的功能属性。 | +| inputPattern | number | 是 | 否 | 编辑框的文本属性。 | + +## KeyEvent + +按键属性值。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| --------- | -------- | ---- | ---- | ------------ | +| keyCode | number | 是 | 否 | 按键的键值。 | +| keyAction | number | 是 | 否 | 按键的状态。 | -下列API示例中都需使用[inputStart](#inputStart)回调获取到TextInputClient实例,再通过此实例调用对应方法。 +## TextInputClient(deprecated) -### getForward +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[InputClient](#inputclient9)替代。 + +下列API示例中都需使用[on('inputStart')](#oninputstart)回调获取到TextInputClient实例,再通过此实例调用对应方法。 + +### getForward(deprecated) getForward(length:number, callback: AsyncCallback<string>): void -获取光标前固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +获取光标前固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getForward](#getforward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | length | number | 是 | 文本长度。 | -| callback | AsyncCallback<string> | 是 | 返回文本。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当光标前固定长度的文本获取成功,err为undefined,data为获取到的文本;否则为错误对象。| **示例:** - ```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); - }); - ``` +```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 +### getForward(deprecated) getForward(length:number): Promise<string> -获取光标前固定长度的文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +获取光标前固定长度的文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getForward](#getforward9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -606,56 +1701,64 @@ getForward(length:number): Promise<string> | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | 返回文本。 | +| Promise<string> | 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 +async function InputMethodEngine() { + let length = 1; + await TextInputClient.getForward(length).then((text) => { + console.info('getForward result---res: ' + text); + }).catch((err) => { + console.error('getForward err: ' + JSON.stringify(err)); + }); +} +``` -### getBackward +### getBackward(deprecated) getBackward(length:number, callback: AsyncCallback<string>): void -获取光标后固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +获取光标后固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getBackward](#getbackward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | length | number | 是 | 文本长度。 | -| callback | AsyncCallback<string> | 是 | 返回文本。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当光标后固定长度的文本获取成功,err为undefined,data为获取到的文本;否则为错误对象。 | **示例:** - ```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); - }); - ``` +```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 +### getBackward(deprecated) getBackward(length:number): Promise<string> -获取光标后固定长度的文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +获取光标后固定长度的文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getBackward](#getbackward9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -667,59 +1770,68 @@ getBackward(length:number): Promise<string> | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | 返回文本。 | +| Promise<string> | Promise对象,返回光标后固定长度的文本。 | **示例:** - ```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 +async function InputMethodEngine() { + let length = 1; + await TextInputClient.getBackward(length).then((text) => { + console.info('getBackward result---res: ' + text); + }).catch((err) => { + console.error('getBackward err: ' + JSON.stringify(err)); + }); +} +``` -### deleteForward +### deleteForward(deprecated) deleteForward(length:number, callback: AsyncCallback<boolean>): void -删除光标前固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +删除光标前固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteForward](#deleteforward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | length | number | 是 | 文本长度。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当光标前固定长度的文本删除成功,err为undefined,data为true;否则为错误对象。 | **示例:** - ```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 +```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形式返回结果。参数个数为1,否则抛出异常。 +删除光标前固定长度的文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteForward](#deleteforward9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -731,64 +1843,72 @@ deleteForward(length:number): Promise<boolean> | 类型 | 说明 | | ---------------------- | -------------- | -| Promise<boolean> | 操作成功与否。 | +| Promise<boolean> | Promise对象。返回true表示删除光标前固定长度的文本成功;返回false表示删除光标前固定长度的文本失败。| **示例:** ```js async function InputMethodEngine() { - var length = 1; + let length = 1; await TextInputClient.deleteForward(length).then((result) => { if (result) { - console.info('Success to deleteForward.(promise) '); + console.info('Success to deleteForward. '); } else { - console.error('Failed to deleteForward.(promise) '); + console.error('Failed to deleteForward. '); } }).catch((err) => { - console.error('deleteForward promise err: ' + err.msg); + console.error('deleteForward err: ' + JSON.stringify(err)); }); } ``` -### deleteBackward +### deleteBackward(deprecated) deleteBackward(length:number, callback: AsyncCallback<boolean>): void -删除光标后固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +删除光标后固定长度的文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteBackward](#deletebackward9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | -------------- | | length | number | 是 | 文本长度。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当光标后固定长度的文本删除成功,err为undefined,data为true;否则为错误对象。| **示例:** ```js -var length = 1; +let length = 1; TextInputClient.deleteBackward(length, (err, result) => { if (err === undefined) { - console.error('deleteBackward callback result---err: ' + err.msg); + console.error('deleteBackward err: ' + JSON.stringify(err)); return; } if (result) { - console.info('Success to deleteBackward.(callback) '); + console.info('Success to deleteBackward. '); } else { - console.error('Failed to deleteBackward.(callback) '); + console.error('Failed to deleteBackward. '); } }); ``` -### deleteBackward +### deleteBackward(deprecated) deleteBackward(length:number): Promise<boolean> -删除光标后固定长度的文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +删除光标后固定长度的文本。使用callback异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[deleteBackward](#deletebackward9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -800,62 +1920,70 @@ deleteBackward(length:number): Promise<boolean> | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | 操作成功与否。 | +| Promise<boolean> | Promise对象。返回true表示删除光标后固定长度的文本成功;返回false表示删除光标后固定长度的文本失败。| **示例:** ```js async function InputMethodEngine() { - var length = 1; + let length = 1; await TextInputClient.deleteBackward(length).then((result) => { if (result) { - console.info('Success to deleteBackward.(promise) '); + console.info('Success to deleteBackward. '); } else { - console.error('Failed to deleteBackward.(promise) '); + console.error('Failed to deleteBackward. '); } }).catch((err) => { - console.error('deleteBackward promise err: ' + err.msg); + console.error('deleteBackward err: ' + JSON.stringify(err)); }); } ``` -### sendKeyFunction +### sendKeyFunction(deprecated) sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void -发送功能键。使用callback形式返回结果。参数个数为2,否则抛出异常。 +发送功能键。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[sendKeyFunction](#sendkeyfunction9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | action | number | 是 | 编辑框属性。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当功能键发送成功,err为undefined,data为true;否则为错误对象。 | **示例:** ```js TextInputClient.sendKeyFunction(keyFunction, (err, result) => { if (err === undefined) { - console.error('sendKeyFunction callback result---err: ' + err.msg); + console.error('sendKeyFunction err: ' + JSON.stringify(err)); return; } if (result) { - console.info('Success to sendKeyFunction.(callback) '); + console.info('Success to sendKeyFunction. '); } else { - console.error('Failed to sendKeyFunction.(callback) '); + console.error('Failed to sendKeyFunction. '); } }); ``` -### sendKeyFunction +### sendKeyFunction(deprecated) sendKeyFunction(action:number): Promise<boolean> -发送功能键。使用promise形式返回结果。参数个数为1,否则抛出异常。 +发送功能键。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[sendKeyFunction](#sendkeyfunction9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -867,62 +1995,70 @@ sendKeyFunction(action:number): Promise<boolean> | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | 操作成功与否。 | +| Promise<boolean> | Promise对象。返回true表示发送功能键成功;返回false表示发送功能键失败。 | **示例:** - ```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 +async function InputMethodEngine() { + await client.sendKeyFunction(keyFunction).then((result) => { + if (result) { + console.info('Success to sendKeyFunction. '); + } else { + console.error('Failed to sendKeyFunction. '); + } + }).catch((err) => { + console.error('sendKeyFunction err:' + JSON.stringify(err)); + }); +} +``` + +### insertText(deprecated) insertText(text:string, callback: AsyncCallback<boolean>): void -插入文本。使用callback形式返回结果。参数个数为2,否则抛出异常。 +插入文本。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[insertText](#inserttext9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | text | string | 是 | 文本。 | -| callback | AsyncCallback<boolean> | 是 | 操作成功与否。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当文本插入成功,err为undefined,data为true;否则为错误对象。 | **示例:** ```js TextInputClient.insertText('test', (err, result) => { if (err === undefined) { - console.error('insertText callback result---err: ' + err.msg); + 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 +### insertText(deprecated) insertText(text:string): Promise<boolean> -插入文本。使用promise形式返回结果。参数个数为1,否则抛出异常。 +插入文本。使用promise异步回调。 + +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[insertText](#inserttext9)替代。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** @@ -934,155 +2070,82 @@ insertText(text:string): Promise<boolean> | 类型 | 说明 | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | 操作成功与否。 | +| Promise<boolean> | Promise对象。返回true表示插入文本成功;返回false表示插入文本失败。 | **示例:** - ```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 +async function InputMethodEngine() { + await TextInputClient.insertText('test').then((result) => { + if (result) { + console.info('Success to insertText. '); + } else { + console.error('Failed to insertText. '); + } + }).catch((err) => { + console.error('insertText err: ' + JSON.stringify(err)); + }); +} +``` + +### getEditorAttribute(deprecated) getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void -获取编辑框属性值。使用callback形式返回结果。参数个数为1,否则抛出异常。 +获取编辑框属性值。使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getEditorAttribute](#geteditorattribute9)替代。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework **参数:** | 参数名 | 类型 | 必填 | 说明 | | ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| callback | AsyncCallback<[EditorAttribute](#EditorAttribute)> | 是 | 编辑框属性值。 | - -**示例:** - - ```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)); - }); - ``` - -### getEditorAttribute - -getEditorAttribute(): Promise<EditorAttribute> - -获取编辑框属性值。使用promise形式返回结果。参数个数为0,否则抛出异常。 - -**系统能力**: SystemCapability.MiscServices.InputMethodFramework - -**返回值:** - -| 类型 | 说明 | -| ------------------------------- | ------------------------------------------------------------ | -| Promise<[EditorAttribute](#EditorAttribute)> | 返回编辑框属性值。 | - -**示例:** - - ```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); - }); - } - ``` - -### moveCursor9+ - -moveCursor(direction: number, callback: AsyncCallback<void>): void - -移动光标。使用callback形式返回结果。参数个数为1,否则抛出异常。 - -**系统能力**: SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | -------------- | -| direction | number | 是 | 光标移动方向。 | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<[EditorAttribute](#editorattribute)> | 是 | 回调函数。当编辑框的属性值获取成功,err为undefined,data为编辑框属性值;否则为错误对象。| **示例:** ```js -TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { +TextInputClient.getEditorAttribute((err, editorAttribute) => { if (err === undefined) { - console.error('moveCursor callback result---err: ' + err.msg); + console.error('getEditorAttribute err: ' + JSON.stringify(err)); return; } + console.log('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); }); ``` -### moveCursor9+ - -moveCursor(direction: number): Promise<void> +### getEditorAttribute(deprecated) -移动光标。使用promise形式返回结果。参数个数为1,否则抛出异常。 +getEditorAttribute(): Promise<EditorAttribute> -**系统能力**: SystemCapability.MiscServices.InputMethodFramework +获取编辑框属性值。使用promise异步回调。 -**参数:** +> **说明:** +> +> 从API version 8开始支持,API version 9开始废弃, 建议使用[getEditorAttribute](#geteditorattribute9)替代。 -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | -------------- | -| direction | number | 是 | 光标移动方向。 | +**系统能力:** SystemCapability.MiscServices.InputMethodFramework -**返回值:** +**返回值:** -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<[EditorAttribute](#editorattribute)> | Promise对象,返回编辑框属性值。 | **示例:** - ```js +```js async function InputMethodEngine() { - await TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then(async (err) => { - console.log('moveCursor success'); + await TextInputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); }).catch((err) => { - console.error('moveCursor success err: ' + err.msg); + console.error('getEditorAttribute err: ' + JSON.stringify(err)); }); } - ``` - -## EditorAttribute - -编辑框属性值。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework - -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ------------ | -------- | ---- | ---- | ------------------ | -| enterKeyType | number | 是 | 否 | 编辑框的功能属性。 | -| inputPattern | number | 是 | 否 | 编辑框的文本属性。 | - -## KeyEvent - -按键属性值。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.InputMethodFramework - -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------- | -------- | ---- | ---- | ------------ | -| keyCode | number | 是 | 否 | 按键的键值。 | -| keyAction | number | 是 | 否 | 按键的状态。 | - +``` \ 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..06de18434c1f9fe4d721e5db79cd185dcebcd684 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,36 @@ off(type: "touch", receiver?: TouchEventReceiver): void **参数:** | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“touch”。 | -| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 触摸输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“touch”。 | +| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | **示例:** ```js -// 取消所有监听。 +// 取消监听单个回调函数 +callback: function(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; +}, try { - inputMonitor.off("touch"); + inputMonitor.on("touch", this.callback); + inputMonitor.off("touch", this.callback); } 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)}`); +``` + +```js +// 取消监听所有回调函数 +callback: function(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; }, try { - inputMonitor.on("touch", this.callback); -} catch (error) { - console.info("onTouchMonitor " + error.code + " " + error.message) -}, -try { - inputMonitor.off("touch",this.callback); + inputMonitor.on("touch", this.callback); + inputMonitor.off("touch"); } catch (error) { - console.info("offTouchMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -129,39 +134,40 @@ off(type: "mouse", receiver?: Callback<MouseEvent>): void | 参数 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“mouse”。 | -| receiver | Callback<MouseEvent> | 否 | 鼠标输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“mouse”。 | +| receiver | Callback<MouseEvent> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | **示例:** ```js -// 取消所有监听。 +// 取消监听单个回调函数 +callback: function(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); +}, try { - inputMonitor.off("mouse"); + inputMonitor.on("mouse", this.callback); + inputMonitor.off("mouse", this.callback); } 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)}`); +``` + +```js +// 取消监听所有回调函数 +callback: function(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); }, try { - inputMonitor.on("mouse", this.callback); + inputMonitor.on("mouse", this.callback); + inputMonitor.off("mouse"); } catch (error) { - console.info("onMouseMonitor " + error.code + " " + error.message) -}, -try { - inputMonitor.off("mouse", this.callback); -} 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 +176,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-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-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-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-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-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-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-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..e1f7466c26078eb038818c28a30e8ee71530f3a9 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -27,7 +27,7 @@ printf(format: string, ...args: Object[]): string | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | format | string | 是 | 式样化字符串。 | -| ...args | Object[] | 否 | 待式样化数据。 | +| ...args | Object[] | 否 | 替换式样化字符串通配符的数据。 | **返回值:** 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..8b74f1843c10dcc4f3c767f44b08c464372a2b07 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 **示例:** @@ -61,8 +60,7 @@ postMessageEvent(message: string): void 发送消息。完整示例代码参考[postMessage](#postmessage) -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -114,8 +112,7 @@ onMessageEvent(callback: (result: string) => void): void 注册回调函数,接收HTML5侧发送过来的消息。完整示例代码参考[postMessage](#postmessage) -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -178,8 +175,7 @@ loadUrl(url: string | Resource, headers?: Array\): void 加载指定的URL。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -196,7 +192,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 +227,7 @@ loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, his 加载指定的数据。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -289,8 +284,7 @@ accessForward(): boolean 当前页面是否可前进,即当前页面是否有前进历史记录。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -340,8 +334,7 @@ forward(): void 按照历史栈,前进一个页面。一般结合accessForward一起使用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -384,8 +377,7 @@ accessBackward(): boolean 当前页面是否可后退,即当前页面是否有返回历史记录。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -435,8 +427,7 @@ backward(): void 按照历史栈,后退一个页面。一般结合accessBackward一起使用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -479,8 +470,7 @@ onActive(): void 调用此接口通知Web组件进入前台激活状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -523,8 +513,7 @@ onInactive(): void 调用此接口通知Web组件进入未激活状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -566,8 +555,7 @@ refresh(): void 调用此接口通知Web组件刷新网页。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -610,8 +598,7 @@ accessStep(step: number): boolean 当前页面是否可前进或者后退给定的step步。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -668,8 +655,7 @@ clearHistory(): void 删除所有前进后退记录。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -712,8 +698,7 @@ getHitTest(): HitTestTypeV9 获取当前被点击区域的元素类型。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -763,8 +748,7 @@ registerJavaScriptProxy(object: object, name: string, methodList: Array\ 注入JavaScript对象到window对象中,并在window对象中调用该对象的方法。注册后,须调用[refresh](#refresh)接口生效。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -824,8 +808,7 @@ runJavaScript(script: string, callback : AsyncCallback\): void 异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果。runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -888,8 +871,7 @@ runJavaScript(script: string): Promise\ 异步执行JavaScript脚本,并通过Promise方式返回脚本执行的结果。runJavaScript需要在loadUrl完成后,比如onPageEnd中调用。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -953,8 +935,7 @@ deleteJavaScriptRegister(name: string): void 删除通过registerJavaScriptProxy注册到window上的指定name的应用侧JavaScript对象。删除后立即生效,无须调用[refresh](#refresh)接口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1005,8 +986,7 @@ zoom(factor: number): void 调整当前网页的缩放比例。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1021,8 +1001,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 +1037,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 +1091,7 @@ clearMatches(): void 清除所有通过[searchAllAsync](#searchallasync)匹配到的高亮字符查找结果。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -1157,8 +1134,7 @@ searchNext(forward: boolean): void 滚动到下一个匹配的查找结果并高亮。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1207,8 +1183,7 @@ clearSslCache(): void 清除Web组件记录的SSL证书错误事件对应的用户操作行为。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -1251,8 +1226,7 @@ clearClientAuthenticationCache(): void 清除Web组件记录的客户端证书请求事件对应的用户操作行为。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码:** @@ -1295,8 +1269,7 @@ struct WebComponent { 创建Web消息端口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1347,8 +1320,7 @@ postMessage(name: string, ports: Array\, uri: string): void 发送Web消息端口到HTML5。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1472,8 +1444,7 @@ requestFocus(): void 使当前web页面获取焦点。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -1516,8 +1487,7 @@ zoomIn(): void 调用此接口将当前网页进行放大,比例为20%。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -1527,7 +1497,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 +1531,7 @@ zoomOut(): void 调用此接口将当前网页进行缩小,比例为20%。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -1573,7 +1541,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 +1575,7 @@ getHitTestValue(): HitTestValue 获取当前被点击区域的元素信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1660,8 +1626,7 @@ getWebId(): number 获取当前Web组件的索引值,用于多个Web组件的管理。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1711,8 +1676,7 @@ getUserAgent(): string 获取当前默认用户代理。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1762,8 +1726,7 @@ getTitle(): string 获取文件选择器标题。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1813,8 +1776,7 @@ getPageHeight(): number 获取当前网页的页面高度。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -1864,8 +1826,7 @@ storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\ 以Promise方式异步保存当前页面。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -1991,8 +1951,7 @@ getUrl(): string 获取当前页面的url地址。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2042,8 +2001,7 @@ stop(): void 停止页面加载。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **错误码**: @@ -2086,8 +2044,7 @@ backOrForward(step: number): void 按照历史栈,前进或者后退指定步长的页面,当历史栈中不存在对应步长的页面时,不会进行页面跳转。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2102,7 +2059,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 +2098,7 @@ static getCookie(url: string): string 获取指定url对应cookie的值。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2198,8 +2153,7 @@ static setCookie(url: string, value: string): void 为指定url设置单个cookie的值。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2250,8 +2204,7 @@ static saveCookieAsync(callback: AsyncCallback\): void 将当前存在内存中的cookie异步保存到磁盘中。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2297,8 +2250,7 @@ static saveCookieAsync(): Promise\ 将当前存在内存中的cookie以Promise方法异步保存到磁盘中。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2345,8 +2297,7 @@ static putAcceptCookieEnabled(accept: boolean): void 设置WebCookieManager实例是否拥有发送和接收cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2387,8 +2338,7 @@ static isCookieAllowed(): boolean 获取WebCookieManager实例是否拥有发送和接收cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2426,8 +2376,7 @@ static putAcceptThirdPartyCookieEnabled(accept: boolean): void 设置WebCookieManager实例是否拥有发送和接收第三方cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2468,8 +2417,7 @@ static isThirdPartyCookieAllowed(): boolean 获取WebCookieManager实例是否拥有发送和接收第三方cookie的权限。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2507,8 +2455,7 @@ static existCookie(): boolean 获取是否存在cookie。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2546,8 +2493,7 @@ static deleteEntireCookie(): void 清除所有cookie。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -2578,8 +2524,7 @@ static deleteSessionCookie(): void 清除所有会话cookie。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -2614,8 +2559,7 @@ static deleteOrigin(origin : string): void 清除指定源所使用的存储。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2629,7 +2573,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2667,8 +2611,7 @@ static getOrigins(callback: AsyncCallback\>) : void 以回调方式异步获取当前使用Web SQL数据库的所有源的信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2682,7 +2625,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100012 | Invalid web storage origin. | **示例:** @@ -2729,8 +2672,7 @@ static getOrigins() : Promise\> 以Promise方式异步获取当前使用Web SQL数据库的所有源的信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -2744,7 +2686,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100012 | Invalid web storage origin. | **示例:** @@ -2791,8 +2733,7 @@ static getOriginQuota(origin : string, callback : AsyncCallback\) : void 使用callback回调异步获取指定源的Web SQL数据库的存储配额,配额以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2807,7 +2748,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2851,8 +2792,7 @@ static getOriginQuota(origin : string) : Promise\ 以Promise方式异步获取指定源的Web SQL数据库的存储配额,配额以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2872,7 +2812,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2916,8 +2856,7 @@ static getOriginUsage(origin : string, callback : AsyncCallback\) : void 以回调方式异步获取指定源的Web SQL数据库的存储量,存储量以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2932,7 +2871,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2976,8 +2915,7 @@ static getOriginUsage(origin : string) : Promise\ 以Promise方式异步获取指定源的Web SQL数据库的存储量,存储量以字节为单位。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -2997,7 +2935,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ----------------------------------------------------- | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3041,8 +2979,7 @@ static deleteAllData(): void 清除Web SQL数据库当前使用的所有存储。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -3082,8 +3019,7 @@ static getHttpAuthCredentials(host: string, realm: string): Array\ 检索给定主机和域的HTTP身份验证凭据,该方法为同步方法。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3138,8 +3074,7 @@ static saveHttpAuthCredentials(host: string, realm: string, username: string, pa 保存给定主机和域的HTTP身份验证凭据,该方法为同步方法。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3185,8 +3120,7 @@ static existHttpAuthCredentials(): boolean 判断是否存在任何已保存的HTTP身份验证凭据,该方法为同步方法。存在返回true,不存在返回false。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -3227,8 +3161,7 @@ static deleteHttpAuthCredentials(): void 清除所有已保存的HTTP身份验证凭据,该方法为同步方法。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -3267,8 +3200,7 @@ static allowGeolocation(origin: string): void 允许指定来源使用地理位置接口。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3281,7 +3213,7 @@ SystemCapability.Web.Webview.Core 以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3317,8 +3249,7 @@ static deleteGeolocation(origin: string): void 清除指定来源的地理位置权限状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3332,7 +3263,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3368,8 +3299,7 @@ static getAccessibleGeolocation(origin: string, callback: AsyncCallback\ 以Promise方式异步获取指定源的地理位置权限状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3447,7 +3376,7 @@ SystemCapability.Web.Webview.Core | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3488,8 +3417,7 @@ static getStoredGeolocation(callback: AsyncCallback\>): void 以回调方式异步获取已存储地理位置权限状态的所有源信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **参数:** @@ -3537,8 +3465,7 @@ static getStoredGeolocation(): Promise\> 以Promise方式异步获取已存储地理位置权限状态的所有源信息。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **返回值:** @@ -3585,8 +3512,7 @@ static deleteAllGeolocation(): void 清除所有来源的地理位置权限状态。 -**系统能力:** -SystemCapability.Web.Webview.Core +**系统能力:** SystemCapability.Web.Webview.Core **示例:** @@ -3615,9 +3541,10 @@ struct WebComponent { } ``` ## HeaderV9 - Web组件返回的请求/响应头对象。 +**系统能力:** SystemCapability.Web.Webview.Core + | 名称 | 类型 | 说明 | | ----------- | ------ | :------------------- | | headerKey | string | 请求/响应头的key。 | @@ -3625,6 +3552,8 @@ Web组件返回的请求/响应头对象。 ## HitTestTypeV9 +**系统能力:** SystemCapability.Web.Webview.Core + | 名称 | 描述 | | ------------- | ----------------------------------------- | | EditText | 可编辑的区域。 | @@ -3640,6 +3569,8 @@ Web组件返回的请求/响应头对象。 提供点击区域的元素信息。示例代码参考getHitTestValue。 +**系统能力:** SystemCapability.Web.Webview.Core + | 名称 | 类型 | 说明 | | ----- | ------------- | :----------------------------------------------------------- | | type | [HitTestTypeV9](#hittesttypev9) | 当前被点击区域的元素类型。 | @@ -3649,8 +3580,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..35bfb2ce17c34a439c404a78200f9b8a19a0a441 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)> | 否 | 回调函数。返回当前的状态栏、导航栏信息集合。 | **示例:** @@ -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 **参数:** @@ -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)。 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md index b7c5fdc2ae5372dde1cea4125843e0a59c381242..142d6c90300829ff945e86886b178c7a0b2fc86d 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md @@ -1,6 +1,7 @@ # slider > **说明:** +> > 从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-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-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 228d46c53f5a7dbc6625e39978edd3f271a26c62..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 @@ -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 24abe7b2849674e92a3edc966ded1d3924062f01..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对象说明 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 4cd68d8e5c0c24323c3f43f8023cfb750debe580..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,7 +85,7 @@ 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) 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-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 d38abf5af8e7f03f22029645ddb02288657c0245..2f819a5c110bac78019962d02fae5e773d7e1a4f 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 @@ -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 46a907365e9e618205100a7ced53123dcdafd427..d93f1e3aff2614ef0662a3ac91cf528835f750e3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -423,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%') @@ -1172,7 +1172,7 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu | 参数 | 类型 | 必填 | 描述 | | ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | 图源对象,具体参考ImageBitmap对象。 | -| repetition | string | 是 | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'。
默认值:'' | +| repetition | string | 是 | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'。
默认值:'' | **返回值:**: @@ -1996,7 +1996,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: 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 img:ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2005,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%') @@ -2264,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() }) } 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-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 43487f3c6d291a02fdc8526423500110b6887bc8..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的颜色。 | ## 示例 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-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index 163eab51997874323a9d985831fe081cc0439bcd..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() { @@ -262,17 +262,17 @@ struct NestedScroll { .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..425b58cef2a90d2c7089d5ce332e1ed77e5d3153 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 @@ -25,7 +25,7 @@ WaterFlow(options?: {footer?: CustomBuilder, scroller?: Scroller}) | 参数名 | 参数类型 | 必填 | 参数描述 | | ---------- | ----------------------------------------------- | ------ | -------------------------------------------- | | footer | [CustomBuilder](ts-types.md#custombuilder8) | 否 | 设置WaterFlow尾部组件。 | - | scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器,与可滚动组件绑定。 | + | 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.itemWidthtArray[item1]) + .height(this.itemHeightArray[item1]) .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-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-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 11fb2e197ce9d067af664db6c0b96028acce3663..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 @@ -47,7 +47,7 @@ SetAndLink\(propName: string, defaultValue: T): SubscribedAbstractProperty\(propName: string, defaultValue: S): SubscribedAbstractProperty\(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) @@ -261,7 +261,7 @@ IsMutable(propName: string): boolean | boolean | 返回此属性是否存在并且是否可以改变。 | ```ts -let simple = AppStorage.IsMutable() +let simple = AppStorage.IsMutable('simpleProp') ``` ### Size @@ -520,7 +520,7 @@ delete(propName: string): boolean | 类型 | 描述 | | ------- | ------------------------------------------------------------ | -| boolean | 删除key指定的键值对,如果存在且删除成功返回true,不存在或删除失败返回false。 | +| boolean | 删除key指定的键值对。存在且删除成功,返回true。不存在、删除失败或有状态变量依旧引用propName,返回false。 | ```ts this.storage = new LocalStorage() @@ -643,7 +643,7 @@ PersistProps(properties: {key: string, defaultValue: any}[]): void; | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | ```ts -PersistentStorage.PersistProps([{'highScore', '0'},{'wightScore','1'}]) +PersistentStorage.PersistProps([{key: 'highScore', defaultValue: '0'},{key: 'wightScore',defaultValue: '1'}]) ``` ### Keys @@ -699,14 +699,14 @@ EnvProp\(key: string, value: S): boolean **内置环境变量说明:** -| key | 类型 | 说明 | -| ------------ | ------------- | ------------------- | -| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | -| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | -| fontScale | number | 字体大小比例。 | -| fontWeightScale | number | 字重比例。 | -| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | -| languageCode | string | 当前系统语言,小写字母,例如zh。 | +| key | 类型 | 说明 | +| ------------ | ------------- | ------------------- | +| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | +| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | +| fontScale | number | 字体大小比例。 | +| fontWeightScale | number | 字重比例。 | +| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | +| languageCode | string | 当前系统语言,小写字母,例如zh。 | ```ts Environment.EnvProp('accessibilityEnabled', 'default') @@ -725,7 +725,7 @@ EnvProps(props: {key: string, defaultValue: any}[]): void | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | 要关联的属性数组。 | ```ts -Environment.EnvProps([{'accessibilityEnabled', 'default'},{'accessibilityUnEnabled','undefault'}]) +Environment.EnvProps([{key: 'accessibilityEnabled', defaultValue: 'default'},{key: 'accessibilityUnEnabled', defaultValue: 'undefault'}]) ``` ### Keys diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-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 b5cab28a14a9870fbe9231beb341c28b1f419dfa..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 @@ -63,8 +63,8 @@ struct Index { }) .margin({ top: 30 }) .onChange((value: number, mode: SliderChangeMode) => { - this.outSetValue = value; - console.info('value:' + value + 'mode:' + mode.toString()); + this.outSetValue = value + console.info('value:' + value + 'mode:' + mode.toString()) }) } .width('100%') 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 09b45008a49582d537d1896e552b0cda0125e538..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 @@ -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-popup.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 16070d610f5dd2bbca8bfae08bfd95aa696c71e9..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,8 +20,6 @@ | -------------------------| ------------------------------------------------| -----| ----------------------------------------- | | 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为弹窗当前的显示状态。 | @@ -34,8 +32,6 @@ | -------------------------| ------------------------- | ---- | ---------------------------------------------------- | | 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 | 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/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-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-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-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-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/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/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/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..968540c91ddbf38ebc9ce853cb8a7dbe603a0568 100644 --- a/zh-cn/application-dev/windowmanager/application-window-fa.md +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -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, 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)); }); ``` diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 22276bfd2365379cddbb9c32a8e7ef83008f66a2..1cb4e281f1c78336a50df42cbe79e1e5b7f120f0 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -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; @@ -178,16 +179,30 @@ class MainAbility extends Ability { console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); }); }); - // 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, 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; + // 开发者可以在适当的时机,如主窗口上按钮点击事件等,创建子窗口。并不一定需要在onWindowStageCreate调用,这里仅作展示 + this.showSubWindow(); + } + + onWindowStageDestroy() { + // 开发者可以在适当的时机,如子窗口上点击关闭按钮等,销毁子窗口。并不一定需要在onWindowStageDestroy调用,这里仅作展示 + this.destroySubWindow(); + } }; ``` 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/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/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/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/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-component-building-rules.md b/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..c256505552d4f8a3e741853516e1049adcef97ca --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md @@ -0,0 +1,279 @@ +# 部件编译构建规范 + +## 前言 + +### 目的 + +编译构建是部件化设计落地的切入点,一个优秀的部件在编译态应该具备可维护、可移植、低耦合的特征。本规范用于引导部件开发人员编写符合部件化设计的编译脚本,使得部件在编译态依赖合理、可配置、可复用、可裁剪。 + +### 基本概念 + +**部件** + +部件是OpenHarmony系统能力的基本单元,以源码为划分依据,具有独立的仓和目录,在不同的设备上可实例化为不同的库或二进制文件。 + +**特性** + +部件特性为编译态可配置的编译选项,可供产品在编译时按需配置。不同的特性配置,编译出部件的不同形态,使得部件可以适应不同形态产品的差异化需求。部件特性的配置只影响部件内部功能的实现差异,不能影响部件的Public API(部件对应用提供的接口)以及inner api(部件间的接口)。 + +**依赖** + +在编译态,部件的依赖分为: + +- 有条件依赖:在特定场景下可裁剪的依赖,有条件的依赖裁剪后不影响部件的Public API 和inner api。比如音频对蓝牙的依赖。 +- 强依赖:部件间合理的必要的依赖,不可裁剪。比如syscap部件对安全库函数的依赖。 + +### 总体原则 + +部件编译构建应遵循以下几个原则: + +**独立自治** + +部件编译态应内聚,新增外部依赖时应慎重,尽量减少编译时的静态依赖。 + +**合理依赖** + +部件间的依赖都应基于部件间的接口,禁止依赖其他部件内部的模块和头文件。 + +**产品无关** + +部件在编译态应是多产品通用的,禁止在编译脚本中使用产品名称。 + +### 约定 + +**规则:** 必须遵守的约定。 + +**建议:** 必须加以考虑的约定。 + +### 看护手段 + +为了维护部件编译构建规范,门禁会对构建配置文件做一些检查。 + +预编译检查:指在预编译阶段进行检查,检测到错误将报错并停止编译。 + +静态检查:指检查工具对配置文件进行扫描检查,非编译手段。 + +### 例外 + +在不违背总体原则,经过充分考虑,有充足的理由的前提下,可以适当违背规范中约定。 + +例外破坏了代码的一致性,请尽量避免。“规则”的例外应该是极少的。 + +## 命名 + +编译脚本中的变量、编译目标(target)、模板,gni文件,以及部件描述文件中的对象和数据的命名都应采用内核风格(unix_like),单词全小写,用下划线分割。如:"startup_init"。 + +### 规则1.1 部件名格式须统一 +- 名词形式,需体现部件的功能。 +- 在系统内全局唯一。 +- 不超过63个有效英文字符。 +- 使用小写加下划线的内核风格命名,例如:unix_like。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 三方开源软件的使用对应社区的原生命名方式,比如:cJson。 + +### 规则1.2 特性名为部件名前缀+特性名称 + +特性是部件声明的可配置的编译选项,加上部件名前缀可避免系统内特性重名。示例: + +```py +declare_args() { + dsoftbus_conn_p2p = true # dsoftbus 为部件名, conn_p2p 为特性名称 + dsoftbus_conn_ble = false # dsoftbus 为部件名, conn_ble 为特性名称 +} +``` + +看护手段:预编译检查 + +### 建议1.1 编译目标名以部件名为前缀+模块名称 + +一个部件可能有多个编译目标(即模块),以“{部件名}_{模块名}”的方式命名可以根据编译产物(库、可执行文件)快速定位归属部件和避免重名。 + +反例: +```py +ohos_shared_library("data") # Bad: 不精确,过于通用,系统内易重名 +``` +正例: +```py +ohos_shared_library("cellular_data_napi") # Good +``` + +## 描述文件 + +bundle.json是定义部件的描述文件,包含了部件的根目录、名称、功能描述、版本号、接口定义和编译入口等信息,须保证其准确性。 + +### 规则2.1 部件描述文件中字段须准确 + +| 字段 | 类型 | 看护手段 | +|---|---|---| +|name|string。部件的HPM(鸿蒙包管理器)包名称,必填。命名规则:@{organization}/{component_name}。"component_name"为部件的名称,须满足规则1.1。|静态检查| +|version|string。部件版本号,必填,命名和升级跟随OpenHarmony版本号。|静态检查| +|destPath|string。部件源码的根目录,必填。部件的根目录须独立唯一,不允许存在多个根目录。|静态检查| +|component:name|string。部件名,必填。须满足规则1.1。|静态检查| +|component:subsystem|string。部件归属的子系统名称,必填,子系统名为小写英文字母组合、不使用下划线。|静态检查| +|component:syscap|string list。系统能力的描述,可选。命名规则:大驼峰,"SystemCapability.Subsystem.部件能力.子能力(可选)",如`SystemCapability.Media.Camera`,`SystemCapability.Media.Camera.Front`。|静态检查| +|component:features|string list,部件可配置的特性,可选,命名须满足规则1.2。|静态检查| +|component:adapted_system_type|string list。部件适用的系统类型,必填,值为`mini`、`small`和`standard`,可同时支持多种。|静态检查| +|component:rom|string。ROM基线值,必填,单位默认为KByte。|静态检查| +|component:ram|string。RAM基线值,必填,单位默认为KByte。|静态检查| +|component:deps|string list。deps对象描述了部件的外部依赖,必填,包括其他部件和三方开源软件,应该与部件编译脚本中依赖一致。|预编译检查| + + +### 建议2.1 部件的描述文件应存放在部件根目录下 + +部件目录是独立的,应将bundle.json文件存放到部件根目录下。 + +## 变量 + +编译目标(target)的内置变量赋值决定了编译内容、依赖和打包等信息,与实现部件化设计强相关。 + +### 规则3.1 部件编译脚本中只允许引用本部件的路径,禁止引用其他部件的绝对或相对路径 + +部件间的依赖都必须使用"externel_deps",部件编译目标的变量sources、include_dirs、configs、public_configs、deps、public_deps引用其他部件的相对和绝对路径属于非法引入依赖: + +- sources + + sources只允许包含本部件的源码,包含其他部件的源码破坏了部件源码目录独立的原则。 + +- include_dirs + + include_dirs只允许引用本部件的头文件搜索路径,编译单元对其他部件的接口的依赖都通过externel_deps自动导入。 + +- configs + + configs只允许引用本部件的配置路径,引用其他部件的configs可能会引入接口依赖。 + +- pulic_configs + + pulic_configs只允许引用本部件的配置路径,引用其他部件的configs可能会引入接口依赖。 + +- deps + + deps只允许用于部件内模块的依赖,直接引用其他部件的模块可能会导致依赖其他部件的内部模块和接口。 + + 例: + + base/foos/foo_a/BUILD.gn + + ```py + deps = [ "//base/foo/foo_b:b" ] # Bad, 绝对路径依赖其他部件 + deps = [ "../../foo_b:b" ] # Bad, 相对路径依赖其他部件 + deps = [ "a" ] # Good, 依赖当前部件内的其他模块 + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 对三方开源软件的引用除外。 + +- public_deps + + public_deps只允许用于部件内模块的依赖,直接引用其他部件的模块可能会导致依赖其他部件的内部模块和接口。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 对三方开源软件的引用除外。 + + +看护手段:静态检查 + +### 规则3.2 部件编译目标必须指定部件和子系统名 + +部件的编译单元ohos_shared_library、ohos_static_library、ohos_executable_library、ohos_source_set都必须指定"part_name"和"subsystem_name"。 + +以developtools/syscap_codec/BUILD.gn的ohos_shared_library编译单元为例: + +```py +ohos_shared_library("syscap_interface_shared") { + include_dirs = [ + "include", + "src", + ] + public_configs = [ ":syscap_interface_public_config" ] + sources = [ + "./interfaces/inner_api/syscap_interface.c", + "./src/endian_internal.c", + "./src/syscap_tool.c", + ] + deps = [ + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + ] + + subsystem_name = "developtools" # 必须指定subsystem_name + part_name = "syscap_codec" # 必须指定part_name +} +``` + +看护手段:静态检查 + +### 建议3.1 部件内部的引用使用相对路径 + +部件内的引用使用相对路径的优点: + +- 脚本更简洁 + +- 部件的编译脚本与部件的根目录解耦。 + +例: + +base/foos/foo_a/BUILD.gn + +```py +include_dirs = [ + "./include", # Good, 相对路径引用 + "//base/foo/foo_a/include" # Bad, 绝对路径引用 +] + +deps = [ + "sub_module:foo", # Good, 相对路径引用 + "base/foo/foo_a/sub_moudule:foo" # Bad, 绝对路径引用 +] +``` + +看护手段:静态检查 + +### 建议3.2 部件内部模块的可见度设置为部件内可见 + +部件内部的模块应使用`"visibility"`字段标识,防止被其他部件依赖。示例: + +base/foos/foo_a/BUILD.gn + +```py +ohos_shared_library("foo_a") { + visibility = [ "./*" ] # foo_a只在base/foo/foo_a及其子目录下可见 +} + +ohos_shared_library("foo_a") { + visibility = [ ":*" ] # foo_a只在本BUILD.gn可见 +} +``` + +## 其他 + +### 规则4.1 部件编译脚本中禁止使用产品名称变量 + +部件是通用的系统能力,与特定产品无关。编译脚本中使用产品名称,将导致部件功能与产品绑定,不具备通用性。部件不同产品形态上的差异应抽象为特性或者运行时的插件。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**例外:** vendor和device目录下三方厂商部件的编译脚本例外。 + +看护手段:静态检查 + +### 建议4.1 避免import其他部件目录下的gni文件 + +部件内的gni文件用于声明部件内部编译变量和模板,import其他部件的gni文件等同于使用其他部件内部的变量和模板,即引入对其他部件的依赖。影响多个部件的变量、args和模板应定义在编译框架的gni文件中。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**例外:** build目录下编译框架定义全局的编译选项的gni可以被所有部件import。 + +看护手段:静态检查 + +### 建议4.2 部件使用统一的编译单元模板 + +轻量、小型和标准的系统的编译单元都应使用ohos定义的模板,比如`ohos_shared_library`、`ohos_static_library`、`ohos_executable`、`ohos_source_set`等以"ohos_"为前缀的模板。 + +例如: + +```py + executable("foundation") { # Bad, 不推荐使用内置的模板 + ... + } + + ohos_executable("foundation") { # Good, 推荐使用ohos定制模板 + ... + } +``` + diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-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/readme/ARK-Runtime-Subsystem-zh.md b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md index 219299721d153e1bef8724a85e7ca96145e7dcec..e4c02ca1259bf516a0bef18952806ab9ece2c65e 100644 --- a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md +++ b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md @@ -72,15 +72,16 @@ JS Runtime主要由四个子系统组成: ## 目录 ``` -/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 +89,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/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)