diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 65d3f42d95a37f3bdb9728a8e0b2897dd1ff8519..5aef516bfc51bbe842ecd6be64f2be3b0b7a1653 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -32,7 +32,7 @@ Then, equip yourself for developing the key features, with the following guideli - [WebGL](webgl/webgl-overview.md) - [Media](media/media-application-overview.md) - [Security](security/userauth-overview.md) -- [AI](ai/mindspore-lite-js-guidelines.md) +- [AI](ai/ai-overview.md) - [Connectivity](connectivity/ipc-rpc-overview.md) - [Telephony Service](telephony/telephony-overview.md) - [Data Management](database/data-mgmt-overview.md) diff --git a/en/application-dev/application-models/arkts-ui-widget-configuration.md b/en/application-dev/application-models/arkts-ui-widget-configuration.md index f0f003e608c995461ad1e84c65ed2a09b87febb7..ea9832f92d32dfe0c2a4160f3ac6f8e904d323fa 100644 --- a/en/application-dev/application-models/arkts-ui-widget-configuration.md +++ b/en/application-dev/application-models/arkts-ui-widget-configuration.md @@ -16,7 +16,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and "extensionAbilities": [ { "name": "EntryFormAbility", - "srcEntry": "./ets/entryformability/EntryFormAbility.ts", + "srcEntry": "./ets/entryformability/EntryFormAbility.ets", "label": "$string:EntryFormAbility_label", "description": "$string:EntryFormAbility_desc", "type": "form", @@ -42,9 +42,9 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | src | Full path of the UI code corresponding to the widget. For an ArkTS widget, the full path must contain the widget file name extension, for example, **./ets/widget/pages/WidgetCard.ets**. For a JS widget, the full path does not need to contain the widget file name extension, for example, **./js/widget/pages/WidgetCard**.| String| No| | uiSyntax | Type of the widget.
- **arkts**: ArkTS widget
- **hml**: JS widget| String| Yes (initial value: **hml**)| - | window | Window-related configurations.| Object| Yes| + | window | Window-related configurations.| Object| YYes (initial value: see Table 2)| | isDefault | Whether the widget is a default one. Each UIAbility has only one default widget.
- **true**: The widget is the default one.
- **false**: The widget is not the default one.| Boolean| No| - | colorMode | Color mode of the widget.
- **auto**: auto-adaptive color mode
- **dark**: dark color mode
- **light**: light color mode| String| Yes (initial value: **auto**)| + | colorMode | Color mode of the widget.
- **auto**: following the system color mode
- **dark**: dark color mode
- **light**: light color mode| String| Yes (initial value: **auto**)| | supportDimensions | Grid styles supported by the widget.
- **1 * 2**: indicates a grid with one row and two columns.
- **2 * 2**: indicates a grid with two rows and two columns.
- **2 * 4**: indicates a grid with two rows and four columns.
- **4 * 4**: indicates a grid with four rows and four columns.| String array| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| | updateEnabled | Whether the widget can be updated periodically.
- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.
- **false**: The widget cannot be updated periodically.| Boolean| No| @@ -56,6 +56,13 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If this tag is set to **true**, the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not.| Boolean| Yes (initial value: **false**)| | isDynamic | Whether the widget is a dynamic widget. This tag only applies to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)| + **Table 2** Internal structure of the window object + + | Field| Description| Data Type| Default Value Allowed| + | -------- | -------- | -------- | -------- | + | designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number| Yes (initial value: **720px**)| + | autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute will be ignored, and the baseline width will be calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| + Example configuration: diff --git a/en/application-dev/application-models/arkts-ui-widget-page-animation.md b/en/application-dev/application-models/arkts-ui-widget-page-animation.md index 0cb8e356c61155d367e55c0f39bbf491d03e2e12..ff479a47e17cadc04c38ecdc3931b5aa1b3d687f 100644 --- a/en/application-dev/application-models/arkts-ui-widget-page-animation.md +++ b/en/application-dev/application-models/arkts-ui-widget-page-animation.md @@ -1,7 +1,7 @@ # Using Animations in the Widget -To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [attribute animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Just note the following restrictions when using the animations in ArkTS widgets. +To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [property animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Just note the following restrictions when using the animations in ArkTS widgets. **Table 1** Restrictions on animation parameters diff --git a/en/application-dev/application-models/arkts-ui-widget-working-principles.md b/en/application-dev/application-models/arkts-ui-widget-working-principles.md index 25cb66f1b05eaf845c11ab05350f2e705de6cec8..a8599ca8827c2d41c3ff1be032151c1f6debead9 100644 --- a/en/application-dev/application-models/arkts-ui-widget-working-principles.md +++ b/en/application-dev/application-models/arkts-ui-widget-working-principles.md @@ -35,7 +35,7 @@ As a quick entry to applications, ArkTS widgets outperform JS widgets in the fol ![WidgetProject](figures/WidgetProject.png) - More widget features - - Animation: ArkTS widgets support the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience. + - Animation: ArkTS widgets support the [property animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience. - Custom drawing: ArkTS widgets allow you to draw graphics with the [\](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly. - Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the use cases of widgets. diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index d7316d5a25c20f4cd076b8ebca4ed700d7c387c7..760af4a45a98b31c5f8bfed8745c3f100c6e1f60 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -2,7 +2,7 @@ - [Full SDK Compilation](full-sdk-compile-guide.md) - [Switching to Full SDK](full-sdk-switch-guide.md) -- [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](howto-migrate-cmake-with-ohosndk.md) +- [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](cmake-with-ndk.md) - [Application Model Development](faqs-ability.md) - ArkUI Development (ArkTS) - [ArkTS Syntax Usage](faqs-arkui-arkts.md) diff --git a/en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md b/en/application-dev/faqs/cmake-with-ndk.md similarity index 100% rename from en/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md rename to en/application-dev/faqs/cmake-with-ndk.md diff --git a/en/application-dev/napi/figures/onDestroy.png b/en/application-dev/napi/figures/onDestroy.png new file mode 100644 index 0000000000000000000000000000000000000000..41f10a3a0a1ecafb673f5013199977a42bc9b531 Binary files /dev/null and b/en/application-dev/napi/figures/onDestroy.png differ diff --git a/en/application-dev/napi/figures/onLoad.png b/en/application-dev/napi/figures/onLoad.png new file mode 100644 index 0000000000000000000000000000000000000000..361cd48e2ddd5e14b86644628c09874d411c37f9 Binary files /dev/null and b/en/application-dev/napi/figures/onLoad.png differ diff --git a/en/application-dev/napi/native-window-guidelines.md b/en/application-dev/napi/native-window-guidelines.md index 4f39be0a9b311d28b1a6551eac728484893a948f..f6f4e44b5edd8f40757105b4c050d4c9b2b0363d 100644 --- a/en/application-dev/napi/native-window-guidelines.md +++ b/en/application-dev/napi/native-window-guidelines.md @@ -23,81 +23,88 @@ For details about the APIs, see [native_window](../reference/native-apis/_native The following describes how to use the native APIs provided by **NativeWindow** to request a graphics buffer, write the produced graphics content to the buffer, and flush the buffer to the graphics queue. +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**: +```txt +libace_ndk.z.so +libnative_window.so +``` + **Header File** ```c++ +#include #include ``` -1. Obtain an **OHNativeWindow** instance, which can be obtained by running the APIs provided by [OH_NativeXComponent_Callback](../reference/native-apis/_o_h___native_x_component___callback.md). - 1. Define **XComponent** in an .ets file. +1. Obtain an **OHNativeWindow** instance. + + You can call the APIs provided by [OH_NativeXComponent_Callback](../reference/native-apis/_o_h___native_x_component___callback.md) to obtain an **OHNativeWindow** instance. An example code snippet is provided below. For details about how to use the **\**, see [XComponent Development](xcomponent-guidelines.md). + 1. Add an **\** to the .ets file. ```ts - XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'nativerender'}) - .onLoad((context) => { - this.context = context; - }) - .onDestroy(() => { - }) + XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'entry'}) + .width(360) + .height(360) + ``` + 2. Obtain **NativeXComponent** at the native C++ layer. + ```c++ + napi_value exportInstance = nullptr; + // Parse the attribute of the wrapped NativeXComponent pointer. + napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); + OH_NativeXComponent *nativeXComponent = nullptr; + // Use the napi_unwrap API to parse the NativeXComponent instance pointer. + napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + ``` + 3. Define **OH_NativeXComponent_Callback**. + ```c++ + // Define the callback. + void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) + { + // Obtain an OHNativeWindow instance. + OHNativeWindow* nativeWindow = static_cast(window); + // ... + } + void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window) + { + // Obtain an OHNativeWindow instance. + OHNativeWindow* nativeWindow = static_cast(window); + // ... + } + void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) + { + // Obtain an OHNativeWindow instance. + OHNativeWindow* nativeWindow = static_cast(window); + // ... + } + void DispatchTouchEventCB(OH_NativeXComponent* component, void* window) + { + // Obtain an OHNativeWindow instance. + OHNativeWindow* nativeWindow = static_cast(window); + // ... + } + ``` + ```c++ + // Initialize OH_NativeXComponent_Callback. + OH_NativeXComponent_Callback callback; + callback.OnSurfaceCreated = OnSurfaceCreatedCB; + callback.OnSurfaceChanged = OnSurfaceChangedCB; + callback.OnSurfaceDestroyed = OnSurfaceDestroyedCB; + callback.DispatchTouchEvent = DispatchTouchEventCB; ``` - 2. Obtain **NativeXComponent** at the native C++ layer. - ```c++ - napi_value exportInstance = nullptr; - napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); - - OH_NativeXComponent *nativeXComponent = nullptr; - napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); - - char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { }; - uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; - OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize); - ``` - 3. Define **OH_NativeXComponent_Callback**. - ```c++ - // Define the callback. - void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) - { - // Obtain an OHNativeWindow instance. - OHNativeWindow* nativeWindow = window; - // ... - } - void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window) - { - // Obtain an OHNativeWindow instance. - OHNativeWindow* nativeWindow = window; - // ... - } - void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) - { - // Obtain an OHNativeWindow instance. - OHNativeWindow* nativeWindow = window; - // ... - } - void DispatchTouchEventCB(OH_NativeXComponent* component, void* window) - { - // Obtain an OHNativeWindow instance. - OHNativeWindow* nativeWindow = window; - // ... - } - ``` - ```c++ - // Initialize OH_NativeXComponent_Callback. - OH_NativeXComponent_Callback callback_; - callback_->OnSurfaceCreated = OnSurfaceCreatedCB; - callback_->OnSurfaceChanged = OnSurfaceChangedCB; - callback_->OnSurfaceDestroyed = OnSurfaceDestroyedCB; - callback_->DispatchTouchEvent = DispatchTouchEventCB; - ``` 4. Register **OH_NativeXComponent_Callback** with **NativeXComponent**. - ```c++ - OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback_); - ``` + ```c++ + // Register the callback. + OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback); + ``` 2. Set the attributes of an **OHNativeWindowBuffer** by using **OH_NativeWindow_NativeWindowHandleOpt**. ```c++ // Set the width and height of the OHNativeWindowBuffer. - code = SET_BUFFER_GEOMETRY; + int32_t code = SET_BUFFER_GEOMETRY; int32_t width = 0x100; int32_t height = 0x100; - ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); + // The nativeWindow instance is obtained from the callback in the previous step. + int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); // Set the step of the OHNativeWindowBuffer. code = SET_STRIDE; int32_t stride = 0x8; @@ -109,18 +116,27 @@ The following describes how to use the native APIs provided by **NativeWindow** OHNativeWindowBuffer* buffer = nullptr; int fenceFd; // Obtain the OHNativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer. - OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd); - // Obtain the buffer handle by calling OH_NativeWindow_GetNativeBufferHandleFromNative. - BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer); + OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow, &buffer, &fenceFd); + // Obtain the buffer handle by calling OH_NativeWindow_GetBufferHandleFromNative. + BufferHandle* bufferHandle = OH_NativeWindow_GetBufferHandleFromNative(buffer); + ``` + +4. Map memory. + ```c++ + #include + + // Use mmap() to obtain the memory virtual address of buffer handle. + void* mappedAddr = mmap(bufferHandle->virAddr, bufferHandle->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufferHandle->fd, 0); + if (mappedAddr == MAP_FAILED) { + // mmap failed + } ``` -4. Write the produced content to the **OHNativeWindowBuffer**. +5. Write the produced content to the **OHNativeWindowBuffer**. ```c++ - auto image = static_cast(buffer->sfbuffer->GetVirAddr()); static uint32_t value = 0x00; value++; - - uint32_t *pixel = static_cast(image); + uint32_t *pixel = static_cast(mappedAddr); // Use the address obtained by mmap() to access the memory. for (uint32_t x = 0; x < width; x++) { for (uint32_t y = 0; y < height; y++) { *pixel++ = value; @@ -133,5 +149,15 @@ The following describes how to use the native APIs provided by **NativeWindow** // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the OHNativeWindowBuffer are changed. Region region{nullptr, 0}; // Flush the buffer to the consumer through OH_NativeWindow_NativeWindowFlushBuffer, for example, by displaying it on the screen. - OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region); + OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow, buffer, fenceFd, region); ``` +6. Unmap memory. + ```c++ + // Unmap the memory when the memory is no longer required. + int result = munmap(mappedAddr, bufferHandle->size); + if (result == -1) { + // munmap failed + } + ``` + + \ No newline at end of file diff --git a/en/application-dev/napi/neural-network-runtime-guidelines.md b/en/application-dev/napi/neural-network-runtime-guidelines.md index 0c86fd05801197bdd63a885c2071f258687a768e..344ae4f1d623f67fcd3b093e8dec6653b806c4f2 100644 --- a/en/application-dev/napi/neural-network-runtime-guidelines.md +++ b/en/application-dev/napi/neural-network-runtime-guidelines.md @@ -19,18 +19,21 @@ The environment requirements for the Neural Network Runtime are as follows: - Development environment: Ubuntu 18.04 or later. - Access device: a standard device running OpenHarmony. The built-in hardware accelerator driver has been connected to the Neural Network Runtime through an HDI API. -The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. You can download the **ohos-sdk** package of the corresponding version from [Daily Build](http://ci.openharmony.cn/dailys/dailybuilds) in the OpenHarmony community and then decompress the package to obtain the Native development suite of the corresponding platform. Take Linux as an example. The package of the Native development suite is named `native-linux-{version number}.zip`. +The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. + ### Environment Setup 1. Start the Ubuntu server. -2. Copy the downloaded package of the Native development suite to the root directory of the current user. +2. Copy the package of the Native development suite to the root directory of the current user. 3. Decompress the package of the Native development suite. + ```shell unzip native-linux-{version number}.zip ``` The directory structure after decompression is as follows. The content in the directory may vary depending on version iteration. Use the Native APIs of the latest version. + ```text native/ ─ ─ build // Cross-compilation toolchain @@ -470,22 +473,19 @@ The development process of the Neural Network Runtime consists of three phases: > The IR graphs of the model need to be passed to the hardware driver layer, so that the HDI service compiles the IR graphs into a computing graph dedicated to hardware. The compilation process is time-consuming. The Neural Network Runtime supports the computing graph cache feature. It can cache the computing graphs compiled by the HDI service to the device storage. If the same model is compiled on the same acceleration chip next time, you can specify the cache path so that the Neural Network Runtime can directly load the computing graphs in the cache file, reducing the compilation time. Check the cached files in the cache directory. + ```shell ls /data/local/tmp ``` The command output is as follows: + ```text # 0.nncache cache_info.nncache ``` If the cache is no longer used, manually delete the cache files. + ```shell rm /data/local/tmp/*nncache - ``` - -## Samples - -The following sample is provided to help you understand how to connect a third-party AI inference framework to the Neural Network Runtime: -- [Development Guide for Connecting TensorFlow Lite to NNRt Delegate](https://gitee.com/openharmony/neural_network_runtime/tree/master/example/deep_learning_framework) - + ``` \ No newline at end of file diff --git a/en/application-dev/napi/xcomponent-guidelines.md b/en/application-dev/napi/xcomponent-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..dd365dd461a3bf868451b047aecd1c8f68c5b390 --- /dev/null +++ b/en/application-dev/napi/xcomponent-guidelines.md @@ -0,0 +1,902 @@ +# XComponent Development + +## When to Use + +**NativeXComponent** provides an instance for the **\** at the native layer, which can be used as a bridge for binding with the **\** at the JS layer. The NDK APIs provided by the **\** depend on this instance. The provided APIs include those for obtaining a native window, obtaining the layout or event information of the **\**, registering the lifecycle callbacks of the **\**, and registering the callbacks for the touch, mouse, and key events of the **\**. You can use the provided APIs in the following scenarios: + +- Register the lifecycle and event callbacks of the **\**. +- In these callbacks, you can initialize the environment, obtain the current state, and respond to various events. +- Use the native window and EGL APIs to develop custom drawing content, and apply for and submit buffers to the graphics queue. + +## Available APIs + +| API| Description.| +| -------- | -------- | +|OH_NativeXComponent_GetXComponentId(OH_NativeXComponent* component, char* id, uint64_t* size)|Obtains the ID of the **\**.| +|OH_NativeXComponent_GetXComponentSize(OH_NativeXComponent* component, const void* window, uint64_t* width, uint64_t* height)|Obtains the size of the surface held by the **\**.| +|OH_NativeXComponent_GetXComponentOffset(OH_NativeXComponent* component, const void* window, double* x, double* y)|Obtains the offset of the surface held by the **\** relative to the upper left corner of the window.| +|OH_NativeXComponent_GetTouchEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_TouchEvent* touchEvent)|Obtains the touch event triggered by the **\**.| +|OH_NativeXComponent_GetTouchPointToolType(OH_NativeXComponent* component, uint32_t pointIndex, OH_NativeXComponent_TouchPointToolType* toolType)|Obtains the tool type of the **\** touch point.| +|OH_NativeXComponent_GetTouchPointTiltX(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltX)|Obtains the tilt angle of the **\** touch point relative to the x-axis.| +|OH_NativeXComponent_GetTouchPointTiltY(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltY)|Obtains the tilt angle of the **\** touch point relative to the y-axis.| +|OH_NativeXComponent_GetMouseEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_MouseEvent* mouseEvent)|Obtains the mouse event triggered by the **\**.| +|OH_NativeXComponent_RegisterCallback(OH_NativeXComponent* component, OH_NativeXComponent_Callback* callback)|Registers the lifecycle and touch event callback for this **OH_NativeXComponent** instance.| +|OH_NativeXComponent_RegisterMouseEventCallback(OH_NativeXComponent* component, OH_NativeXComponent_MouseEvent_Callback* callback)|Registers the mouse event callback for this **OH_NativeXComponent** instance.| +|OH_NativeXComponent_RegisterFocusEventCallback(OH_NativeXComponent* component, void (\*callback)(OH_NativeXComponent* component, void* window))|Registers the focus obtaining event callback function for this **OH_NativeXComponent** instance.| +|OH_NativeXComponent_RegisterKeyEventCallback(OH_NativeXComponent* component, void (\*callback)(OH_NativeXComponent* component, void* window))|Registers the key event callback for this **OH_NativeXComponent** instance.| +|OH_NativeXComponent_RegisterBlurEventCallback(OH_NativeXComponent* component, void (\*callback)(OH_NativeXComponent* component, void* window))|Registers the focus loss event callback for this **OH_NativeXComponent** instance.| +|OH_NativeXComponent_GetKeyEvent(OH_NativeXComponent* component, OH_NativeXComponent_KeyEvent\** keyEvent)|Obtains the key event triggered by the **\**.| +|OH_NativeXComponent_GetKeyEventAction(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyAction* action)|Obtains the action of a key event.| +|OH_NativeXComponent_GetKeyEventCode(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyCode* code)|Obtains the key code value of a key event.| +|OH_NativeXComponent_GetKeyEventSourceType(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_EventSourceType* sourceType)|Obtains the input source type of a key event.| +|OH_NativeXComponent_GetKeyEventDeviceId(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* deviceId)|Obtains the device ID of a key event.| +|OH_NativeXComponent_GetKeyEventTimestamp(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* timestamp)|Obtains the timestamp of a key event.| + +## Lifecycle Description + +You can use the **\** to develop EGL/OpenGL ES rendering by using the following code on the ArkTS side: + +```typescript +XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' }) + .onLoad((context) => {}) + .onDestroy(() => {}) +``` + +### **onLoad** Event + +Trigger time: when the surface of the **\** is ready. + +**context** parameter: where the native API exposed on the module is mounted. Its usage is similar to the usage of a **context** instance obtained after the module is directly loaded using **import context from "libnativerender.so"**. + +Time sequence: subject to the surface. The figure below shows the time sequence of the **onLoad** event and the **OnSurfaceCreated** event at the native layer. + +![onLoad](./figures/onLoad.png) + +### **onDestroy** Event + +Trigger time: when the **\** is destroyed, in the same manner as that when an ArkUI component is destroyed. The figure below shows the time sequence of the **onDestroy** event and the **OnSurfaceDestroyed** event at the native layer. + +![onDestroy](./figures/onDestroy.png) + +## How to Develop +The following describes how to use the **\** to call the native APIs to create the EGL/GLES environment, draw graphics on the main page, and change graphics colors. + +1. Define the **\** on the GUI. + + ```typescript + // ... + // Define XComponent in an .ets file. + XComponent({ + id: 'xcomponentId', + type: XComponentType.SURFACE, + libraryname: 'nativerender' + }) + .focusable(true) // Set the component to be able to respond to key events. + .onLoad((xComponentContext) => { + this.xComponentContext = xComponentContext; + }) + .onDestroy(() => { + console.log("onDestroy"); + }) + // ... + ``` + +2. Register the N-API module. For details, see [Using Native APIs in Application Projects](https://gitee.com/openharmony/docs/blob/master/en/application-dev/napi/napi-guidelines.md). + + ```c++ + // In the napi_init.cpp file, use the Init method to register the target function to transfer the encapsulated C++ methods for the JS side to call. + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + // ... + // Expose the getContext() API to the JS side. + napi_property_descriptor desc[] = { + { "getContext", nullptr, PluginManager::GetContext, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "napi_define_properties failed"); + return nullptr; + } + // Check whether the environment variables in the method contain the instance. If the instance exists, register the drawing-related API. + PluginManager::GetInstance()->Export(env, exports); + return exports; + } + EXTERN_C_END + + // Write the API description. You can modify the corresponding parameters as required. + static napi_module nativerenderModule = { + .nm_version = 1, + .nflag_s = 0, + .nm_filename = nullptr, + // Entry function + .nm_register_func = Init, + // Module name + .nm_modname = "nativerender", + .nm_priv = ((void *)0), + .reserved = { 0 } + }; + + // The method decorated by __attribute__((constructor)) is automatically called by the system. The N-API napi_module_register() is used to transfer the module description for module registration. + extern "C" __attribute__((constructor)) void RegisterModule(void) + { + napi_module_register(&nativerenderModule); + } + + // Use the napi_define_properties method in the N-APIs to expose the drawPattern() method to the JS side and call the drawPattern() method on the JS side to draw content. + void PluginRender::Export(napi_env env, napi_value exports) + { + // ... + // Register the function as the JS API drawPattern. + napi_property_descriptor desc[] = { + { "drawPattern", nullptr, PluginRender::NapiDrawPattern, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "Export: napi_define_properties failed"); + } + } + ``` + +3. Register the **\** event callback and use the N-API to implement it. + + (1) Define the callbacks for the touch event of the **\** and for when a surface is successfully created, changed, or destroyed. + + ```c++ + // Define the OnSurfaceCreatedCB() function to encapsulate the initialization environment and drawing background. + void OnSurfaceCreatedCB(OH_NativeXComponent *component, void *window) + { + // ... + // Obtain the ID of the , that is, the id parameter in the struct on the JS side. + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", + "OnSurfaceCreatedCB: Unable to get XComponent id"); + return; + } + + // Initialize the environment and draw the background. + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + uint64_t width; + uint64_t height; + // Obtain the size of the surface held by the . + int32_t xSize = OH_NativeXComponent_GetXComponentSize(component, window, &width, &height); + if ((xSize == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) && (render != nullptr)) { + if (render->eglCore_->EglContextInit(window, width, height)) { + render->eglCore_->Background(); + } + } + } + + // Define the OnSurfaceChangedCB() function. + void OnSurfaceChangedCB(OH_NativeXComponent *component, void *window) + { + // ... + // Obtain the ID of the . + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", + "OnSurfaceChangedCB: Unable to get XComponent id"); + return; + } + + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + if (render != nullptr) { + // Encapsulate the OnSurfaceChanged method. + render->OnSurfaceChanged(component, window); + } + } + + // Define the OnSurfaceDestroyedCB() function and encapsulate in it the Release() method in the PluginRender class for releasing resources. + void OnSurfaceDestroyedCB(OH_NativeXComponent *component, void *window) + { + // ... + // Obtain the ID of the . + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", + "OnSurfaceDestroyedCB: Unable to get XComponent id"); + return; + } + + std::string id(idStr); + // Release resources. + PluginRender::Release(id); + } + + // Define the DispatchTouchEventCB() function, which is triggered when a touch event is responded to. + void DispatchTouchEventCB(OH_NativeXComponent *component, void *window) + { + // ... + // Obtain the ID of the . + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", + "DispatchTouchEventCB: Unable to get XComponent id"); + return; + } + + std::string id(idStr); + PluginRender *render = PluginRender::GetInstance(id); + if (render != nullptr) { + // Encapsulate the OnTouchEvent method. + render->OnTouchEvent(component, window); + } + } + + // Define the DispatchMouseEventCB() function, which is triggered when a mouse event is responded to. + void DispatchMouseEventCB(OH_NativeXComponent *component, void *window) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchMouseEventCB"); + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + if (render) { + // Encapsulate the OnMouseEvent method. + render->OnMouseEvent(component, window); + } + } + + // Define the DispatchHoverEventCB() function, which is triggered when the mouse pointer hover event is responded to. + void DispatchHoverEventCB(OH_NativeXComponent *component, bool isHover) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchHoverEventCB"); + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + if (render) { + // Encapsulate the OnHoverEvent method. + render->OnHoverEvent(component, isHover); + } + } + + // Define the OnFocusEventCB() function, which is triggered when a focus obtaining event is responded to. + void OnFocusEventCB(OH_NativeXComponent *component, void *window) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnFocusEventCB"); + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + if (render) { + // Encapsulate the OnFocusEvent method. + render->OnFocusEvent(component, window); + } + } + + // Define the OnBlurEventCB() function, which is triggered when the focus loss event is responded to. + void OnBlurEventCB(OH_NativeXComponent *component, void *window) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnBlurEventCB"); + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + if (render) { + // Encapsulate the OnBlurEvent method. + render->OnBlurEvent(component, window); + } + } + + // Define the OnKeyEventCB() function, which is triggered when a key event is responded to. + void OnKeyEventCB(OH_NativeXComponent *component, void *window) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnKeyEventCB"); + int32_t ret; + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize); + if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + return; + } + std::string id(idStr); + auto render = PluginRender::GetInstance(id); + if (render) { + // Encapsulate the OnKeyEvent method. + render->OnKeyEvent(component, window); + } + } + + // Define an OnSurfaceChanged() method. + void PluginRender::OnSurfaceChanged(OH_NativeXComponent* component, void* window) + { + // ... + std::string id(idStr); + PluginRender* render = PluginRender::GetInstance(id); + double offsetX; + double offsetY; + // Obtain the offset of the surface held by the relative to the upper left corner of the window. + OH_NativeXComponent_GetXComponentOffset(component, window, &offsetX, &offsetY); + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OH_NativeXComponent_GetXComponentOffset", + "offsetX = %{public}lf, offsetY = %{public}lf", offsetX, offsetY); + uint64_t width; + uint64_t height; + OH_NativeXComponent_GetXComponentSize(component, window, &width, &height); + if (render != nullptr) { + render->eglCore_->UpdateSize(width, height); + } + } + + // Define an OnTouchEvent() method. + void PluginRender::OnTouchEvent(OH_NativeXComponent* component, void* window) + { + // ... + OH_NativeXComponent_TouchEvent touchEvent; + // Obtain the touch event triggered by the . + OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent); + std::string id(idStr); + PluginRender* render = PluginRender::GetInstance(id); + if (render != nullptr && touchEvent.type == OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UP) { + render->eglCore_->ChangeColor(); + hasChangeColor_ = 1; + } + float tiltX = 0.0f; + float tiltY = 0.0f; + OH_NativeXComponent_TouchPointToolType toolType = + OH_NativeXComponent_TouchPointToolType::OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN; + // Obtain the tool type of the touch point. + OH_NativeXComponent_GetTouchPointToolType(component, 0, &toolType); + // Obtain the tilt angle of the touch point relative to the x-axis. + OH_NativeXComponent_GetTouchPointTiltX(component, 0, &tiltX); + // Obtain the tilt angle of the touch point relative to the y-axis. + OH_NativeXComponent_GetTouchPointTiltY(component, 0, &tiltY); + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OnTouchEvent", + "touch info: toolType = %{public}d, tiltX = %{public}lf, tiltY = %{public}lf", toolType, tiltX, tiltY); + } + + // Define an OnMouseEvent() method. + void PluginRender::OnMouseEvent(OH_NativeXComponent *component, void *window) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnMouseEvent"); + OH_NativeXComponent_MouseEvent mouseEvent; + // Obtain the mouse event triggered by the . + int32_t ret = OH_NativeXComponent_GetMouseEvent(component, window, &mouseEvent); + if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "MouseEvent Info: x = %{public}f, y = %{public}f, action = %{public}d, button = %{public}d", mouseEvent.x, mouseEvent.y, mouseEvent.action, mouseEvent.button); + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetMouseEvent error"); + } + } + + // Define an OnMouseEvent() method. + void PluginRender::OnKeyEvent(OH_NativeXComponent *component, void *window) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnKeyEvent"); + + OH_NativeXComponent_KeyEvent *keyEvent = nullptr; + // Obtain the key event triggered by the . + if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) { + OH_NativeXComponent_KeyAction action; + // Obtain the action of a key event. + OH_NativeXComponent_GetKeyEventAction(keyEvent, &action); + OH_NativeXComponent_KeyCode code; + // Obtain the key code value of a key event. + OH_NativeXComponent_GetKeyEventCode(keyEvent, &code); + OH_NativeXComponent_EventSourceType sourceType; + // Obtain the input source type of a key event. + OH_NativeXComponent_GetKeyEventSourceType(keyEvent, &sourceType); + int64_t deviceId; + // Obtain the device ID of a key event. + OH_NativeXComponent_GetKeyEventDeviceId(keyEvent, &deviceId); + int64_t timeStamp; + // Obtain the timestamp of a key event. + OH_NativeXComponent_GetKeyEventTimestamp(keyEvent, &timeStamp); + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "KeyEvent Info: action=%{public}d, code=%{public}d, sourceType=%{public}d, deviceId=%{public}ld, timeStamp=%{public}ld", action, code, sourceType, deviceId, timeStamp); + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetKeyEvent error"); + } + } + ``` + + (2) Register the **\** event callback and call the method defined in step 3.1 when the **\** event is triggered. + + ```c++ + void PluginRender::RegisterCallback(OH_NativeXComponent *nativeXComponent) { + // Set the callback of the component creation event. When the component is created, related operations are triggered to initialize the environment and draw the background. + renderCallback_.OnSurfaceCreated = OnSurfaceCreatedCB; + // Set the callback of the component change event. When the component changes, related operations are triggered. + renderCallback_.OnSurfaceChanged = OnSurfaceChangedCB; + // Set the callback of the component destruction event. When the component is destroyed, related operations are triggered to release the requested resources. + renderCallback_.OnSurfaceDestroyed = OnSurfaceDestroyedCB; + // Set the callback of the touch event. When the touch event is triggered, the N-API is called to call the original C++ method. + renderCallback_.DispatchTouchEvent = DispatchTouchEventCB; + // Register OH_NativeXComponent_Callback with NativeXComponent. + OH_NativeXComponent_RegisterCallback(nativeXComponent, &renderCallback_); + + // Set the callback of the mouse event. When the event is triggered, the N-API is called to call the original C++ method. + mouseCallback_.DispatchMouseEvent = DispatchMouseEventCB; + // Set the callback of the mouse event. When the event is triggered, the N-API is called to call the original C++ method. + mouseCallback_.DispatchHoverEvent = DispatchHoverEventCB; + // Register OH_NativeXComponent_MouseEvent_Callback with NativeXComponent. + OH_NativeXComponent_RegisterMouseEventCallback(nativeXComponent, &mouseCallback_); + + // Register the OnFocusEventCB method with NativeXComponent. + OH_NativeXComponent_RegisterFocusEventCallback(nativeXComponent, OnFocusEventCB); + // Register the OnKeyEventCB method with NativeXComponent. + OH_NativeXComponent_RegisterKeyEventCallback(nativeXComponent, OnKeyEventCB); + // Register the OnBlurEventCB method with NativeXComponent. + OH_NativeXComponent_RegisterBlurEventCallback(nativeXComponent, OnBlurEventCB); + } + ``` + + (3) Define the **NapiDrawPattern** method, which will be called by the **drawPattern()** method exposed to the JS side. + + ```c++ + napi_value PluginRender::NapiDrawPattern(napi_env env, napi_callback_info info) + { + // ... + // Obtain environment variables. + napi_value thisArg; + if (napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, nullptr) != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_get_cb_info fail"); + return nullptr; + } + + // Obtain the XComponent instance from the environment variables. + napi_value exportInstance; + if (napi_get_named_property(env, thisArg, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance) != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", + "NapiDrawPattern: napi_get_named_property fail"); + return nullptr; + } + + // Use napi_unwrap to obtain the pointer to the XComponent instance. + OH_NativeXComponent *nativeXComponent = nullptr; + if (napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)) != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_unwrap fail"); + return nullptr; + } + + // Obtain the ID of the XComponent instance. + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", + "NapiDrawPattern: Unable to get XComponent id"); + return nullptr; + } + + std::string id(idStr); + PluginRender *render = PluginRender::GetInstance(id); + if (render) { + // Call the drawing method. + render->eglCore_->Draw(); + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "render->eglCore_->Draw() executed"); + } + return nullptr; + } + ``` + +4. Initialize the environment, including initializing the available EGLDisplay, determining the available surface configuration, creating the rendering area surface, and creating and associating the context. + + ```c++ + void EGLCore::UpdateSize(int width, int height) + { + width_ = width; + height_ = height; + if (width_ > 0) { + // Calculate the width percentage of the drawn rectangle. + width_Percent_ = FIFTY_PERCENT * height_ / width_; + } + } + + bool EGLCore::EglContextInit(void *window, int width, int height) + { + // ... + UpdateSize(width, height); + eglWindow_ = static_cast(window); + + // Initialize the display. + eglDisplay_ = eglGetDisplay(EGL_DEFAULT_DISPLAY); + if (eglDisplay_ == EGL_NO_DISPLAY) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglGetDisplay: unable to get EGL display"); + return false; + } + + // Initialize the EGL. + EGLint majorVersion; + EGLint minorVersion; + if (!eglInitialize(eglDisplay_, &majorVersion, &minorVersion)) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", + "eglInitialize: unable to get initialize EGL display"); + return false; + } + + // Select the configuration. + const EGLint maxConfigSize = 1; + EGLint numConfigs; + if (!eglChooseConfig(eglDisplay_, ATTRIB_LIST, &eglConfig_, maxConfigSize, &numConfigs)) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglChooseConfig: unable to choose configs"); + return false; + } + + // Create an environment. + return CreateEnvironment(); + } + ``` + + ```c++ + bool EGLCore::CreateEnvironment() + { + // ... + // Create a surface. + eglSurface_ = eglCreateWindowSurface(eglDisplay_, eglConfig_, eglWindow_, NULL); + + // ... + // Create a context. + eglContext_ = eglCreateContext(eglDisplay_, eglConfig_, EGL_NO_CONTEXT, CONTEXT_ATTRIBS); + if (!eglMakeCurrent(eglDisplay_, eglSurface_, eglSurface_, eglContext_)) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglMakeCurrent failed"); + return false; + } + + // Create a program. + program_ = CreateProgram(VERTEX_SHADER, FRAGMENT_SHADER); + if (program_ == PROGRAM_ERROR) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "CreateProgram: unable to create program"); + return false; + } + return true; + } + ``` + +5. Implement the rendering function. + + (1) Draw the background. + + ```c++ + // Draw the background color #f4f4f4. + const GLfloat BACKGROUND_COLOR[] = { 244.0f / 255, 244.0f / 255, 244.0f / 255, 1.0f }; + + // Draw the background vertex. + const GLfloat BACKGROUND_RECTANGLE_VERTICES[] = { + -1.0f, 1.0f, + 1.0f, 1.0f, + 1.0f, -1.0f, + -1.0f, -1.0f + }; + ``` + + ```c++ + // Draw the background color. + void EGLCore::Background() + { + GLint position = PrepareDraw(); + if (position == POSITION_ERROR) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Background get position failed"); + return; + } + + if (!ExecuteDraw(position, BACKGROUND_COLOR, BACKGROUND_RECTANGLE_VERTICES, + sizeof(BACKGROUND_RECTANGLE_VERTICES))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Background execute draw failed"); + return; + } + + if (!FinishDraw()) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Background FinishDraw failed"); + return; + } + } + + // Prepare for drawing and obtain the value of position. When the creation is successful, the value of position starts from 0. + GLint EGLCore::PrepareDraw() + { + if ((eglDisplay_ == nullptr) || (eglSurface_ == nullptr) || (eglContext_ == nullptr) || + (!eglMakeCurrent(eglDisplay_, eglSurface_, eglSurface_, eglContext_))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "PrepareDraw: param error"); + return POSITION_ERROR; + } + + glViewport(DEFAULT_X_POSITION, DEFAULT_Y_POSITION, width_, height_); + glClearColor(GL_RED_DEFAULT, GL_GREEN_DEFAULT, GL_BLUE_DEFAULT, GL_ALPHA_DEFAULT); + glClear(GL_COLOR_BUFFER_BIT); + glUseProgram(program_); + + return glGetAttribLocation(program_, POSITION_NAME); + } + + // Draw a specified color in the specified area based on the input parameters. + bool EGLCore::ExecuteDraw(GLint position, const GLfloat *color, const GLfloat shapeVertices[], + unsigned long vertSize) + { + if ((position > 0) || (color == nullptr) || (vertSize / sizeof(shapeVertices[0]) != SHAPE_VERTICES_SIZE)) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ExecuteDraw: param error"); + return false; + } + + glVertexAttribPointer(position, POINTER_SIZE, GL_FLOAT, GL_FALSE, 0, shapeVertices); + glEnableVertexAttribArray(position); + glVertexAttrib4fv(1, color); + glDrawArrays(GL_TRIANGLE_FAN, 0, TRIANGLE_FAN_SIZE); + glDisableVertexAttribArray(position); + + return true; + } + + // End the drawing operation. + bool EGLCore::FinishDraw() + { + // Forcibly refresh the buffer. + glFlush(); + glFinish(); + return eglSwapBuffers(eglDisplay_, eglSurface_); + } + ``` + + (2) Draw the shape. + + ```c++ + void EGLCore::Draw() + { + flag_ = false; + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "EGLCore", "Draw"); + GLint position = PrepareDraw(); + if (position == POSITION_ERROR) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw get position failed"); + return; + } + + // Draw the background. + if (!ExecuteDraw(position, BACKGROUND_COLOR, BACKGROUND_RECTANGLE_VERTICES, + sizeof(BACKGROUND_RECTANGLE_VERTICES))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw background failed"); + return; + } + + // Divide the pentagon into five quadrilaterals and calculate the four vertices of one of the quadrilaterals. + GLfloat rotateX = 0; + GLfloat rotateY = FIFTY_PERCENT * height_; + GLfloat centerX = 0; + GLfloat centerY = -rotateY * (M_PI / 180 * 54) * (M_PI / 180 * 18); + GLfloat leftX = -rotateY * (M_PI / 180 * 18); + GLfloat leftY = 0; + GLfloat rightX = rotateY * (M_PI / 180 * 18); + GLfloat rightY = 0; + + // Determine the vertices for drawing the quadrilateral, which are represented by the percentage of the drawing area. + const GLfloat shapeVertices[] = { + centerX / width_, centerY / height_, + leftX / width_, leftY / height_, + rotateX / width_, rotateY / height_, + rightX / width_, rightY / height_ + }; + + if (!ExecuteDrawStar(position, DRAW_COLOR, shapeVertices, sizeof(shapeVertices))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw star failed"); + return; + } + + GLfloat rad = M_PI / 180 * 72; + for (int i = 0; i < 4; ++i) + { + // Obtain the vertices of the other four quadrilaterals through rotation. + rotate2d(centerX, centerY, &rotateX, &rotateY,rad); + rotate2d(centerX, centerY, &leftX, &leftY,rad); + rotate2d(centerX, centerY, &rightX, &rightY,rad); + + // Determine the vertices for drawing the quadrilateral, which are represented by the percentage of the drawing area. + const GLfloat shapeVertices[] = { + centerX / width_, centerY / height_, + leftX / width_, leftY / height_, + rotateX / width_, rotateY / height_, + rightX / width_, rightY / height_ + }; + + // Draw the shape. + if (!ExecuteDrawStar(position, DRAW_COLOR, shapeVertices, sizeof(shapeVertices))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw star failed"); + return; + } + } + + // End drawing. + if (!FinishDraw()) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw FinishDraw failed"); + return; + } + + flag_ = true; + } + ``` + + (3) Change the colors, by drawing a new shape with the same size but different colors and replacing the original shape with the new shape. + + ```c++ + void EGLCore::ChangeColor() + { + if (!flag_) { + return; + } + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor"); + GLint position = PrepareDraw(); + if (position == POSITION_ERROR) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor get position failed"); + return; + } + + // Draw the background. + if (!ExecuteDraw(position, BACKGROUND_COLOR, BACKGROUND_RECTANGLE_VERTICES, + sizeof(BACKGROUND_RECTANGLE_VERTICES))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor execute draw background failed"); + return; + } + + // Determine the vertices for drawing the quadrilateral, which are represented by the percentage of the drawing area. + GLfloat rotateX = 0; + GLfloat rotateY = FIFTY_PERCENT * height_; + GLfloat centerX = 0; + GLfloat centerY = -rotateY * (M_PI / 180 * 54) * (M_PI / 180 * 18); + GLfloat leftX = -rotateY * (M_PI / 180 * 18); + GLfloat leftY = 0; + GLfloat rightX = rotateY * (M_PI / 180 * 18); + GLfloat rightY = 0; + + // Determine the vertices for drawing the quadrilateral, which are represented by the percentage of the drawing area. + const GLfloat shapeVertices[] = { + centerX / width_, centerY / height_, + leftX / width_, leftY / height_, + rotateX / width_, rotateY / height_, + rightX / width_, rightY / height_ + }; + + // Use the new colors for drawing. + if (!ExecuteDrawStar2(position, CHANGE_COLOR, shapeVertices, sizeof(shapeVertices))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw star failed"); + return; + } + + GLfloat rad = M_PI / 180 * 72; + for (int i = 0; i < 4; ++i) + { + // Obtain the vertices of the other four quadrilaterals through rotation. + rotate2d(centerX, centerY, &rotateX, &rotateY,rad); + rotate2d(centerX, centerY, &leftX, &leftY,rad); + rotate2d(centerX, centerY, &rightX, &rightY,rad); + + // Determine the vertices for drawing the quadrilateral, which are represented by the percentage of the drawing area. + const GLfloat shapeVertices[] = { + centerX / width_, centerY / height_, + leftX / width_, leftY / height_, + rotateX / width_, rotateY / height_, + rightX / width_, rightY / height_ + }; + + // Use the new colors for drawing. + if (!ExecuteDrawStar2(position, CHANGE_COLOR, shapeVertices, sizeof(shapeVertices))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw star failed"); + return; + } + } + + // End drawing. + if (!FinishDraw()) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor FinishDraw failed"); + } + } + ``` + +6. Release related resources. + + (1) Create the **Release()** method in the **EGLCore** class to release the resources requested during environment initialization, including the window display, rendering area surface, and environment context. + + ```c++ + void EGLCore::Release() + { + // Release the surface. + if ((eglDisplay_ == nullptr) || (eglSurface_ == nullptr) || (!eglDestroySurface(eglDisplay_, eglSurface_))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Release eglDestroySurface failed"); + } + // Release the context. + if ((eglDisplay_ == nullptr) || (eglContext_ == nullptr) || (!eglDestroyContext(eglDisplay_, eglContext_))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Release eglDestroyContext failed"); + } + // Release the display. + if ((eglDisplay_ == nullptr) || (!eglTerminate(eglDisplay_))) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Release eglTerminate failed"); + } + } + ``` + + (2) Add the **Release()** method to the **PluginRender** class to release the **EGLCore** and **PluginRender** instances. + + ```c++ + void PluginRender::Release(std::string &id) + { + PluginRender *render = PluginRender::GetInstance(id); + if (render != nullptr) { + render->eglCore_->Release(); + delete render->eglCore_; + render->eglCore_ = nullptr; + delete render; + render = nullptr; + instance_.erase(instance_.find(id)); + } + } + ``` + +7. Use the CMake toolchain to compile the C++ source code into a dynamic link library (DLL) file. + + ```CMake + # Set the minimum CMake version. + cmake_minimum_required(VERSION 3.4.1) + # Project name + project(XComponent) + + set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + add_definitions(-DOHOS_PLATFORM) + # Set the header file search directory. + include_directories( + ${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include + ) + # Add the **nativerender** dynamic library, with the **libnativerender.so** library file. Add the .cpp file. + add_library(nativerender SHARED + render/egl_core.cpp + render/plugin_render.cpp + manager/plugin_manager.cpp + napi_init.cpp + ) + + find_library( + EGL-lib + EGL + ) + + find_library( + GLES-lib + GLESv3 + ) + + find_library( + hilog-lib + hilog_ndk.z + ) + + find_library( + libace-lib + ace_ndk.z + ) + + find_library( + libnapi-lib + ace_napi.z + ) + + find_library( + libuv-lib + uv + ) + # Add the library to be linked. + target_link_libraries(nativerender PUBLIC + ${EGL-lib} ${GLES-lib} ${hilog-lib} ${libace-lib} ${libnapi-lib} ${libuv-lib}) + ``` + +## + + + +- diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 7e6d0acac8ef49b1d6cb38a294d490c6f9a6144c..1d079b36d7af3cf7682659edc9362e6e802e258b 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -2,7 +2,7 @@ - Getting Started - [Before You Start](start-overview.md) - - [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md) + - [Building the First ArkTS Application in Stage Model](start-with-ets-stage.md) - Development Fundamentals - Application Package Fundamentals - [Application Package Overview](application-package-overview.md) @@ -41,8 +41,8 @@ - [Resource Categories and Access](resource-categories-and-access.md) - Learning ArkTS - [Getting Started with ArkTS](arkts-get-started.md) - - [Introduction to ArkTS](arkts/introduction-to-arkts.md) - - [TypeScript to ArkTS Migration Guide](arkts/typescript-to-arkts-migration-guide.md) + - [Introduction to ArkTS](introduction-to-arkts.md) + - [TypeScript to ArkTS Migration Guide](typescript-to-arkts-migration-guide.md) - UI paradigms - Basic Syntax - [Basic Syntax Overview](arkts-basic-syntax-overview.md) @@ -55,6 +55,7 @@ - [\@Styles Decorator: Definition of Resusable Styles](arkts-style.md) - [\@Extend Decorator: Extension of Built-in Components](arkts-extend.md) - [stateStyles Decorator: Polymorphic Style](arkts-statestyles.md) + - [\@AnimatableExtend Decorator: Definition of Animatable Attributes](arkts-animatable-extend.md) - State Management - [State Management Overview](arkts-state-management-overview.md) - Component State Management diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 60a0baa6a6046da92101a1dcff891a6ed16d774d..5fe815d3e9df1e60501504dab5b38f3b860e9b93 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -93,7 +93,6 @@ As shown above, the **module.json5** file contains several tags. | [dependencies](#dependencies)| List of shared libraries on which the current module depends during running.| Object array| Yes (initial value: left empty) | | targetModuleName | Target module of the bundle. The value is a string with a maximum of 31 bytes. It must be unique in the entire application.|String|Yes (if the initial value is used, the target module is not a module with the overlay feature)| | targetPriority | Priority of the module. When **targetModuleName** is set, the module is a module with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)| -| [proxyDatas(deprecated)](#proxydatasdeprecated) | This API is deprecated since API version 10. You are advised to use **proxydata** instead. List of data proxies provided by the module.| Object array| Yes (initial value: left empty)| | [proxyData](#proxydata) | List of data proxies provided by the module.| Object array| Yes (initial value: left empty)| | isolationMode | Multi-process configuration of the module. The options are as follows:
- **nonisolationFirst**: The module preferentially runs in a non-independent process.
- **isolationFirst**: The module preferentially runs in an independent process.
- **isolationOnly**: The module runs only in an independent process.
- **nonisolationOnly**: The module runs only in non-independent processes.|String|Yes (initial value: **nonisolationFirst**)| | generateBuildHash |Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
This tag is enabled only when the **generateBuildHash** tag in the [app.json5](./app-configuration-file.md) file is **false**.**
**NOTE**
This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)| @@ -421,7 +420,7 @@ Example of the **extensionAbilities** structure: ## requestPermissions -The **requestPermissions** tag represents a set of permissions that the application needs to request from the system for running correctly. +The **requestPermissions** tag represents a set of permissions that the application needs to request from the system for running correctly. For details about how to request permissions, see [Applying for Permissions](../security/accesstoken-guidelines.md). > **NOTE** > @@ -738,40 +737,6 @@ Example of the **dependencies** structure: } ``` -## proxyDatas(deprecated) - ->This API is supported since API version 10 and deprecated since API version 10. You are advised to use [proxyData](#proxydata) instead. - -The **proxyDatas** tag provides the list of data proxies provided by the module. It can be configured only for entry and feature modules. - -**Table 21** proxyDatas -| Name | Description | Data Type| Initial Value Allowed| -| ----------- | ------------------------------ | -------- | ---------- | -| uri | URI of the data proxy. The URIs configured for different data proxies must be unique and must be in the *datashareproxy://Current application package name/xxx* format. | String | No| -| requiredReadPermission | Permission required for reading data from the data proxy. For non-system applications, this field is mandatory, and the permission level must be system_basic or system_core. For system applications, this field is optional, and the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| -| requiredWritePermission | Permission required for writing data to the data proxy. For non-system applications, this field is mandatory, and the permission level must be system_basic or system_core. For system applications, this field is optional, and the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| -| [metadata](#metadata)| Metadata of the data proxy. Only the **name** and **resource** fields can be configured.| Object| Yes (initial value: left empty)| - -Example of the **proxyDatas** structure: - -```json -{ - "module": { - "proxyDatas": [ - { - "uri":"datashareproxy://com.ohos.datashare/event/Meeting", - "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", - "requiredWritePermission": "ohos.permission.GET_BUNDLE_INFO", - "metadata": { - "name": "datashare_metadata", - "resource": "$profile:datashare" - } - } - ] - } -} -``` - ## proxyData The **proxyDatas** tag provides the list of data proxies provided by the module. It can be configured only for entry and feature modules. @@ -780,8 +745,8 @@ The **proxyDatas** tag provides the list of data proxies provided by the module. | Name | Description | Data Type| Initial Value Allowed| | ----------- | ------------------------------ | -------- | ---------- | | uri | URI of the data proxy. The URIs configured for different data proxies must be unique and must be in the *datashareproxy://Current application package name/xxx* format. | String | No| -| requiredReadPermission | Permission required for reading data from the data proxy. For non-system applications, this field is mandatory, and the permission level must be system_basic or system_core. For system applications, this field is optional, and the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| -| requiredWritePermission | Permission required for writing data to the data proxy. For non-system applications, this field is mandatory, and the permission level must be system_basic or system_core. For system applications, this field is optional, and the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| +| requiredReadPermission | Permission required for reading data from the data proxy. If it is not specified, other applications will not be able to use the data proxy. For non-system applications, the level of the set permission must be system_basic or system_core. For system applications, the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| +| requiredWritePermission | Permission required for writing data to the data proxy. If it is not specified, other applications will not be able to use the data proxy. For non-system applications, the level of the set permission must be system_basic or system_core. For system applications, the permission level is not limited. For details about the permission level, see [Application Permission List](../security/permission-list.md).| String | Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the data proxy. Only the **name** and **resource** fields can be configured.| Object| Yes (initial value: left empty)| Example of the **proxyData** structure: diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index 2bc53666dce570f5c9c5c9c5a0b8c48e353422d2..df1178706cc93fac75f9f443dcff2627b026b9c8 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -44,4 +44,4 @@ To help you better understand the preceding basic concepts and application devel 2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/environment_config-0000001052902427-V3). -When you are done, follow the instructions in [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md). +When you are done, you can set out to [build your first ArkTS application in the stage model](start-with-ets-stage.md). diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index ec3ab196bb1d0edb494d2a26be688b4b455a714a..789f4c05e28730d4f2851fc507af6bc4a8af1d9b 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -1,4 +1,4 @@ -# Getting Started with ArkTS in Stage Model +# Building the First ArkTS Application in Stage Model > **NOTE** diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index d8fd233696ea1ef468e7f9c98016ca87741a4871..cc95f18bea02638e473d14ac31d585b12a9ca45a 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -317,8 +317,18 @@ - [@ohos.request (Upload and Download)](js-apis-request.md) - Connectivity + - [@ohos.bluetooth.a2dp (Bluetooth a2dp Module)(Recommended)](js-apis-bluetooth-a2dp.md) + - [@ohos.bluetooth.access (Bluetooth access Module)(Recommended)](js-apis-bluetooth-access.md) + - [@ohos.bluetooth.baseProfile (Bluetooth baseProfile Module)(Recommended)](js-apis-bluetooth-baseProfile.md) + - [@ohos.bluetooth.ble (Bluetooth ble Module)(Recommended)](js-apis-bluetooth-ble.md) + - [@ohos.bluetooth.connection (Bluetooth connection Module)(Recommended)](js-apis-bluetooth-connection.md) + - [@ohos.bluetooth.constant (Bluetooth constant Module)(Recommended)](js-apis-bluetooth-constant.md) + - [@ohos.bluetooth.hfp (Bluetooth hfp Module)(Recommended)](js-apis-bluetooth-hfp.md) + - [@ohos.bluetooth.hid (Bluetooth hid Module)(Recommended)(js-apis-bluetooth-hid.md) + - [@ohos.bluetooth.pan (Bluetooth pan Module)(Recommended)](js-apis-bluetooth-pan.md) + - [@ohos.bluetooth.socket (Bluetooth socket Module)(Recommended)](js-apis-bluetooth-socket.md) - [@ohos.bluetooth (Bluetooth) (To Be Deprecated Soon)](js-apis-bluetooth.md) - - [@ohos.bluetoothManager (Bluetooth) (Recommended)](js-apis-bluetoothManager.md) + - [@ohos.bluetoothManager (Bluetooth) (To Be Deprecated Soon)](js-apis-bluetoothManager.md) - [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md) - [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](js-apis-cardEmulation.md) - [@ohos.nfc.controller (Standard NFC)](js-apis-nfcController.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index db930ccbe8cc14f368b9e16d29b556074e981482..63b12c68575f0d3c79b71b3cb7f241c35c7a13c8 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -646,7 +646,7 @@ This is a system API. ```ts let bundleName = "com.example.myapplication"; -bundleManager.setApplicationEnabled(bundleName, false).then(()=> { +bundle.setApplicationEnabled(bundleName, false).then(()=> { console.info('setApplicationEnabled successfully.'); }).catch(err=> { console.error('setApplicationEnabled failed.'); @@ -767,7 +767,7 @@ This is a system API. ```ts let permission = "ohos.permission.GET_BUNDLE_INFO"; -bundleManager.getPermissionDef(permission, (err, data) => { +bundle.getPermissionDef(permission, (err, data) => { if (err) { console.error('getPermissionDef failed:' + err.message); } else { diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-a2dp.md b/en/application-dev/reference/apis/js-apis-bluetooth-a2dp.md new file mode 100644 index 0000000000000000000000000000000000000000..ee1d29a240b2d718744ac1935196ae118116fab4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-a2dp.md @@ -0,0 +1,184 @@ +# @ohos.bluetooth.a2dp (Bluetooth A2DP Module) + +The **a2dp** module provides APIs for using the Bluetooth Advanced Audio Distribution Profile (A2DP), which defines how to stream high quality audio from one device to another over a Bluetooth connection. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +``` + + +## a2dp.createA2dpSrcProfile + +createA2dpSrcProfile(): A2dpSourceProfile + +Creates an **A2dpSrcProfile** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| A2dpSourceProfile | **A2dpSrcProfile** instance created.| + +**Example** + +```js +try { + let a2dpProfile = a2dp.createA2dpSrcProfile(); + console.info('a2dp success'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## A2dpSourceProfile + +Provides APIs for using the A2DP. Before using any API of **A2dpSourceProfile**, you need to create an instance of this class by using **createA2dpSrcProfile()**. + + +### connect + +connect(deviceId: string): void + +Connects to an A2DP device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the device to connect. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### disconnect + +disconnect(deviceId: string): void + +Disconnects from an A2DP device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the device to disconnect. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getPlayingState + +getPlayingState(deviceId: string): PlayingState + +Obtains the playing state of a device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| device | string | Yes | Address of the remote device.| + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| [PlayingState](#PlayingState) | Playing state of the remote device obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + +## PlayingState + +Enumerates the A2DP playing states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ----------------- | ------ | ------- | +| STATE_NOT_PLAYING | 0x0000 | Not playing. | +| STATE_PLAYING | 0x0001 | Playing.| diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-access.md b/en/application-dev/reference/apis/js-apis-bluetooth-access.md new file mode 100644 index 0000000000000000000000000000000000000000..fbbfd0a64400ab98a13d0d6cef0c50e7387562b5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-access.md @@ -0,0 +1,206 @@ +# @ohos.bluetooth.access (Bluetooth Access Module) + +The **access** module provides APIs for enabling and disabling Bluetooth and obtaining the Bluetooth status. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```js +import access from '@ohos.bluetooth.access'; +``` + + +## access.enableBluetooth + +enableBluetooth(): void + +Enables Bluetooth. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message | +| -------- | ------------------ | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + access.enableBluetooth(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## access.disableBluetooth + +disableBluetooth(): void + +Disables Bluetooth. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +|ID | Error Message | +| -------- | ------------------ | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + access.disableBluetooth(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## access.getState + +getState(): BluetoothState + +Obtains the Bluetooth state. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------- | +| [BluetoothState](#bluetoothstate) | Bluetooth state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +|ID | Error Message | +| -------- | ------------------ | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let state = access.getState(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## access.on('stateChange') + +on(type: "stateChange", callback: Callback<BluetoothState>): void + +Subscribes to Bluetooth state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------- | ----- | ---------------------------------------------------------- | +| type | string | Yes | Event type. The value is **stateChange**, which indicates a Bluetooth state change event. | +| callback | Callback<[BluetoothState](#bluetoothstate)> | Yes | Callback invoked to return the Bluetooth state. You need to implement this callback.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +|ID | Error Message | +| -------- | ------------------ | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth state = '+ JSON.stringify(data)); +} +try { + access.on('stateChange', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## access.off('stateChange') + +off(type: "stateChange", callback?: Callback<BluetoothState>): void + +Unsubscribes from Bluetooth state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **stateChange**, which indicates a Bluetooth state change event. | +| callback | Callback<[BluetoothState](#bluetoothstate)> | No | Callback for the Bluetooth state change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth state = '+ JSON.stringify(data)); +} +try { + access.on('stateChange', onReceiveEvent); + access.off('stateChange', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## BluetoothState + +Enumerates the Bluetooth states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| STATE_OFF | 0 | Bluetooth is turned off. | +| STATE_TURNING_ON | 1 | Bluetooth is being turned on. | +| STATE_ON | 2 | Bluetooth is turned on. | +| STATE_TURNING_OFF | 3 | Bluetooth is being turned off. | +| STATE_BLE_TURNING_ON | 4 | The LE-only mode is being turned on for Bluetooth.| +| STATE_BLE_ON | 5 | Bluetooth is in LE-only mode. | +| STATE_BLE_TURNING_OFF | 6 | The LE-only mode is being turned off for Bluetooth.| diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md b/en/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md new file mode 100644 index 0000000000000000000000000000000000000000..74789b23af6367fa6f549d20ac49abe1e7a1c938 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md @@ -0,0 +1,388 @@ +# @ohos.bluetooth.baseProfile (Bluetooth baseProfile Module) + +The **baseProfile** module provides APIs for using basic Bluetooth profiles. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import baseProfile from '@ohos.bluetooth.baseProfile'; +``` + + +## ConnectionStrategy + +Enumerates the profile connection strategies. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| -------------------------------- | ------ | --------------- | +| CONNECTION_STRATEGY_UNSUPPORTED | 0 | Default connection strategy to use when the device is not paired.
This is a system API.| +| CONNECTION_STRATEGY_ALLOWED | 1 | Connection strategy to use when the device is allowed to accept or initiate pairing.
This is a system API.| +| CONNECTION_STRATEGY_FORBIDDEN | 2 | Connection strategy to use when the device is not allowed to accept or initiate pairing.
This is a system API. | + + +## StateChangeParam + +Represents the profile state change parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable| Writable| Description | +| -------- | ----------------------------- | ---- | ---- | ------------------------------- | +| deviceId | string | Yes | No | Address of the Bluetooth device. | +| state | ProfileConnectionState | Yes | No | Profile connection state of the device.| + + +## baseProfile.setConnectionStrategy + +setConnectionStrategy(deviceId: string, strategy: ConnectionStrategy, callback: AsyncCallback<void>): void + +Sets the profile connection strategy for this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX. | +| strategy | [ConnectionStrategy](#connectionstrategy) | Yes |Profile connection strategy to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let setRet = a2dpSrc.setConnectionStrategy('XX:XX:XX:XX:XX:XX', 0, (err, data) => { + console.info('setConnectionStrategy, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + +## baseProfile.setConnectionStrategy + +setConnectionStrategy(deviceId: string, strategy: ConnectionStrategy): Promise<void> + +Sets the profile connection strategy for this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX. | +| strategy | [ConnectionStrategy](#connectionstrategy) | Yes |Profile connection strategy to set.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let setRet = a2dpSrc.setConnectionStrategy('XX:XX:XX:XX:XX:XX', 1).then((data) => { + console.info('setConnectionStrategy'); + }, (err) => { + console.error('setConnectionStrategy errCode: ' + err.code + ', errMessage: ' + err.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + +## baseProfile.getConnectionStrategy + +getConnectionStrategy(deviceId: string, callback: AsyncCallback<ConnectionStrategy>): void + +Obtains the profile connection strategy. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX. | +| callback | AsyncCallback<[ConnectionStrategy](#connectionstrategy)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let setRet = a2dpSrc.getConnectionStrategy('XX:XX:XX:XX:XX:XX', 0, (err, data) => { + console.info('getConnectionStrategy, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + +## baseProfile.getConnectionStrategy + +getConnectionStrategy(deviceId: string): Promise<ConnectionStrategy> + +Obtains the profile connection strategy. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX. | + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<[ConnectionStrategy](#connectionstrategy)> | Promise used to return the profile connection strategy obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let setRet = a2dpSrc.getConnectionStrategy('XX:XX:XX:XX:XX:XX', 1).then((data) => { + console.info('getConnectionStrategy'); + }, (error) => { + console.error('getConnectionStrategy errCode: ' + err.code + ', errMessage: ' + err.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## baseProfile.getConnectedDevices + +getConnectedDevices(): Array<string> + +Obtains the connected devices. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------- | +| Array<string> | Addresses of the connected devices.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let retArray = a2dpSrc.getConnectedDevices(); +} catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); +} +``` + + +## baseProfile.getConnectionState + +getConnectionState(deviceId: string): ProfileConnectionState + +Obtains the profile connection state of a device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the remote device.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | ----------------------- | +| [ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | Profile connection state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + let a2dpSrc = a2dp.createA2dpSrcProfile(); + let ret = a2dpSrc.getConnectionState('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## baseProfile.on('connectionStateChange') + +on(type: 'connectionStateChange', callback: Callback<StateChangeParam>): void + +Subscribes to profile connection state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **connectionStateChange**, which indicates a profile connection state change event.| +| callback | Callback<[StateChangeParam](#statechangeparam)> | Yes | Callback invoked to return the profile connection state change. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + function onReceiveEvent(data) { + console.info('a2dp state = '+ JSON.stringify(data)); + } + let a2dpSrc = a2dp.createA2dpSrcProfile(); + a2dpSrc.on('connectionStateChange', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## baseProfile.off('connectionStateChange') + +off(type: 'connectionStateChange', callback?: Callback<[StateChangeParam](#StateChangeParam)>): void + +Unsubscribes from profile connection state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **connectionStateChange**, which indicates a profile connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the profile connection state change. | + +**Example** + +```js +import a2dp from '@ohos.bluetooth.a2dp'; +try { + function onReceiveEvent(data) { + console.info('a2dp state = '+ JSON.stringify(data)); + } + let a2dpSrc = a2dp.createA2dpSrcProfile(); + a2dpSrc.on('connectionStateChange', onReceiveEvent); + a2dpSrc.off('connectionStateChange', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-ble.md b/en/application-dev/reference/apis/js-apis-bluetooth-ble.md new file mode 100644 index 0000000000000000000000000000000000000000..4036451fc4941e9b047de860c4172bfa48076138 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-ble.md @@ -0,0 +1,2539 @@ +# @ohos.bluetooth.ble (Bluetooth BLE Module) + +The **ble** module provides APIs for accessing the Bluetooth personal area network. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import ble from '@ohos.bluetooth.ble'; +``` + + +## ble.createGattServer + +createGattServer(): GattServer + +Creates a **GattServer** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| GattServer | **GattServer** instance created.| + +**Example** + +```js +let gattServer = ble.createGattServer(); +console.info('gatt success'); +``` + + +## ble.createGattClientDevice + +createGattClientDevice(deviceId: string): GattClientDevice + +Creates a **GattClientDevice** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------ | +| deviceId | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------------------------------------- | ------------------------------------ | +| [GattClientDevice](#gattclientdevice) | **GattClientDevice** instance created. Before using an API of the client, you must create a **GattClientDevice** instance.| + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.getConnectedBLEDevices + +getConnectedBLEDevices(): Array<string> + +Obtains the Bluetooth Low Energy (BLE) devices connected to this device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------- | +| Array<string> | Addresses of the BLE devices connected to this device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let result = ble.getConnectedBLEDevices(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.startBLEScan + +startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void + +Starts a BLE scan. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | -------------------------------------- | ---- | ----------------------------------- | +| filters | Array<[ScanFilter](#scanfilter)> | Yes | Criteria for filtering the scan result. Set this parameter to **null** if you do not want to filter the scan result.| +| options | [ScanOptions](#scanoptions) | No | Scan options. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('BLE scan device find result = '+ JSON.stringify(data)); +} +try { + ble.on("BLEDeviceFind", onReceiveEvent); + ble.startBLEScan( + [{ + deviceId:"XX:XX:XX:XX:XX:XX", + name:"test", + serviceUuid:"00001888-0000-1000-8000-00805f9b34fb" + }], + { + interval: 500, + dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, + matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE, + } + ); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.stopBLEScan + +stopBLEScan(): void + +Stops the BLE scan. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + ble.stopBLEScan(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.startAdvertising + +startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void + +Starts BLE advertising. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------------- | ---- | -------------- | +| setting | [AdvertiseSetting](#advertisesetting) | Yes | Settings related to BLE advertising. | +| advData | [AdvertiseData](#advertisedata) | Yes | Content of the BLE advertisement packet. | +| advResponse | [AdvertiseData](#advertisedata) | No | Response to the BLE scan request.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let manufactureValueBuffer = new Uint8Array(4); +manufactureValueBuffer[0] = 1; +manufactureValueBuffer[1] = 2; +manufactureValueBuffer[2] = 3; +manufactureValueBuffer[3] = 4; + +let serviceValueBuffer = new Uint8Array(4); +serviceValueBuffer[0] = 4; +serviceValueBuffer[1] = 6; +serviceValueBuffer[2] = 7; +serviceValueBuffer[3] = 8; +console.info('manufactureValueBuffer = '+ JSON.stringify(manufactureValueBuffer)); +console.info('serviceValueBuffer = '+ JSON.stringify(serviceValueBuffer)); +try { + ble.startAdvertising({ + interval:150, + txPower:0, + connectable:true, + },{ + serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], + manufactureData:[{ + manufactureId:4567, + manufactureValue:manufactureValueBuffer.buffer + }], + serviceData:[{ + serviceUuid:"00001888-0000-1000-8000-00805f9b34fb", + serviceValue:serviceValueBuffer.buffer + }], + },{ + serviceUuids:["00001889-0000-1000-8000-00805f9b34fb"], + manufactureData:[{ + manufactureId:1789, + manufactureValue:manufactureValueBuffer.buffer + }], + serviceData:[{ + serviceUuid:"00001889-0000-1000-8000-00805f9b34fb", + serviceValue:serviceValueBuffer.buffer + }], + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.stopAdvertising + +stopAdvertising(): void + +Stops BLE advertising. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + ble.stopAdvertising(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.on('BLEDeviceFind') + +on(type: 'BLEDeviceFind', callback: Callback<Array<ScanResult>>): void + +Subscribes to BLE device discovery events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| type | string | Yes | Event type. The value is **BLEDeviceFind**, which indicates an event of discovering a BLE device. | +| callback | Callback<Array<[ScanResult](#scanresult)>> | Yes | Callback invoked to return the discovered devices. You need to implement this callback.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + ble.on('BLEDeviceFind', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## ble.off('BLEDeviceFind') + +off(type: 'BLEDeviceFind', callback?: Callback<Array<ScanResult>>): void + +Unsubscribes from BLE device discovery events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **BLEDeviceFind**, which indicates an event of discovering a BLE device. | +| callback | Callback<Array<[ScanResult](#scanresult)>> | No | Callback for the **BLEDeviceFind** event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + ble.on('BLEDeviceFind', onReceiveEvent); + ble.off('BLEDeviceFind', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## GattServer + +Implements the Generic Attribute Profile (GATT) server. Before using an API of this class, you need to create a **GattServer** instance using **createGattServer()**. + + +### addService + +addService(service: GattService): void + +Adds a service to this GATT server. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------- | ---- | ------------------------ | +| service | [GattService](#gattservice) | Yes | Service to add. Settings related to BLE advertising.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; + +// Create characteristics. +let characteristics = []; +let arrayBufferC = new ArrayBuffer(8); +let cccV = new Uint8Array(arrayBufferC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +characteristics[0] = characteristic; + +// Create a gattService instance. +let gattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]}; + +try { + gattServer.addService(gattService); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### removeService + +removeService(serviceUuid: string): void + +Removes a service from this GATT server. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Universally unique identifier (UUID) of the service to remove, for example, **00001810-0000-1000-8000-00805F9B34FB**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +let server = ble.createGattServer(); +try { + server.removeService('00001810-0000-1000-8000-00805F9B34FB'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### close + +close(): void + +Closes this GATT server to unregister it from the protocol stack. The closed [GattServer](#gattserver) instance will no longer be used. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let server = ble.createGattServer(); +try { + server.close(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### notifyCharacteristicChanged + +notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic, callback: AsyncCallback<void>): void + +Notifies a connected client device when a characteristic value changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | +| deviceId | string | Yes | Address of the client that receives the notifications, for example, XX:XX:XX:XX:XX:XX.| +| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | Yes | New characteristic value. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let arrayBufferC = new ArrayBuffer(8); +let notifyCharacter = { + "serviceUuid": '00001810-0000-1000-8000-00805F9B34FB', + "characteristicUuid": '00001820-0000-1000-8000-00805F9B34FB', + "characteristicValue": arrayBufferC, + "confirm": true, +}; +try { + gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter, (err) => { + if (err) { + console.info('notifyCharacteristicChanged callback failed'); + } else { + console.info('notifyCharacteristicChanged callback successful'); + } + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### notifyCharacteristicChanged + +notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): Promise<void> + +Notifies a connected client device when a characteristic value changes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | --------------------------------------- | +| deviceId | string | Yes | Address of the client that receives the notifications, for example, XX:XX:XX:XX:XX:XX.| +| notifyCharacteristic | [NotifyCharacteristic](#notifycharacteristic) | Yes | New characteristic value. | + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let arrayBufferC = new ArrayBuffer(8); +let notifyCharacter = { + "serviceUuid": '00001810-0000-1000-8000-00805F9B34FB', + "characteristicUuid": '00001820-0000-1000-8000-00805F9B34FB', + "characteristicValue": arrayBufferC, + "confirm": true, +}; +try { + gattServer.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacter).then(() => { + console.info('notifyCharacteristicChanged promise successfull'); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### sendResponse + +sendResponse(serverResponse: ServerResponse): void + +Sends a response to a read or write request from the GATT client. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------- | ---- | --------------- | +| serverResponse | [ServerResponse](#serverresponse) | Yes | Response returned by the GATT server.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +/* send response */ +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +cccValue[0] = 1123; +let serverResponse = { + 'deviceId': 'XX:XX:XX:XX:XX:XX', + 'transId': 0, + 'status': 0, + 'offset': 0, + 'value': arrayBufferCCC, +}; +try { + gattServer.sendResponse(serverResponse); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### on('characteristicRead') + +on(type: 'characteristicRead', callback: Callback<CharacteristicReadRequest>): void + +Subscribes to characteristic read request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------- | +| type | string | Yes | Event type. The value is **characteristicRead**, which indicates a characteristic read request event.| +| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | Yes | Callback invoked to return a characteristic read request event from the GATT client. | + +**Example** + +```js +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +cccValue[0] = 1123; +function ReadCharacteristicReq(CharacteristicReadRequest) { + let deviceId = CharacteristicReadRequest.deviceId; + let transId = CharacteristicReadRequest.transId; + let offset = CharacteristicReadRequest.offset; + let characteristicUuid = CharacteristicReadRequest.characteristicUuid; + + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); + } +} +gattServer.on('characteristicRead', ReadCharacteristicReq); +``` + + +### off('characteristicRead') + +off(type: 'characteristicRead', callback?: Callback<CharacteristicReadRequest>): void + +Unsubscribes from characteristic read request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **characteristicRead**, which indicates a characteristic read request event. | +| callback | Callback<[CharacteristicReadRequest](#characteristicreadrequest)> | No | Callback for the characteristic read request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +gattServer.off('characteristicRead'); +``` + + +### on('characteristicWrite') + +on(type: 'characteristicWrite', callback: Callback<CharacteristicWriteRequest>): void + +Subscribes to characteristic write request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.| +| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | + +**Example** + +```js +let arrayBufferCCC = new ArrayBuffer(8); +let cccValue = new Uint8Array(arrayBufferCCC); +function WriteCharacteristicReq(CharacteristicWriteRequest) { + let deviceId = CharacteristicWriteRequest.deviceId; + let transId = CharacteristicWriteRequest.transId; + let offset = CharacteristicWriteRequest.offset; + let isPrepared = CharacteristicWriteRequest.isPrepared; + let needRsp = CharacteristicWriteRequest.needRsp; + let value = new Uint8Array(CharacteristicWriteRequest.value); + let characteristicUuid = CharacteristicWriteRequest.characteristicUuid; + + cccValue[0] = value[0]; + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); + } +} +gattServer.on('characteristicWrite', WriteCharacteristicReq); +``` + + +### off('characteristicWrite') + +off(type: 'characteristicWrite', callback?: Callback<CharacteristicWriteRequest>): void + +Unsubscribes from characteristic write request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **characteristicWrite**, which indicates a characteristic write request event. | +| callback | Callback<[CharacteristicWriteRequest](#characteristicwriterequest)> | No | Callback for the characteristic write request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +gattServer.off('characteristicWrite'); +``` + + +### on('descriptorRead') + +on(type: 'descriptorRead', callback: Callback<DescriptorReadRequest>): void + +Subscribes to descriptor read request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **descriptorRead**, which indicates a descriptor read request event.| +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | + +**Example** + +```js +let arrayBufferDesc = new ArrayBuffer(8); +let descValue = new Uint8Array(arrayBufferDesc); +descValue[0] = 1101; +function ReadDescriptorReq(DescriptorReadRequest) { + let deviceId = DescriptorReadRequest.deviceId; + let transId = DescriptorReadRequest.transId; + let offset = DescriptorReadRequest.offset; + let descriptorUuid = DescriptorReadRequest.descriptorUuid; + + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); + } +} +gattServer.on('descriptorRead', ReadDescriptorReq); +``` + + +### off('descriptorRead') + +off(type: 'descriptorRead', callback?: Callback<DescriptorReadRequest>): void + +Unsubscribes from descriptor read request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **descriptorRead**, which indicates a descriptor read request event. | +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | No | Callback for the descriptor read request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +gattServer.off('descriptorRead'); +``` + + +### on('descriptorWrite') + +on(type: 'descriptorWrite', callback: Callback<DescriptorWriteRequest>): void + +Subscribes to descriptor write request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------- | +| type | string | Yes | Event type. The value is **descriptorWrite**, which indicates a descriptor write request event.| +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | + +**Example** + +```js +let arrayBufferDesc = new ArrayBuffer(8); +let descValue = new Uint8Array(arrayBufferDesc); +function WriteDescriptorReq(DescriptorWriteRequest) { + let deviceId = DescriptorWriteRequest.deviceId; + let transId = DescriptorWriteRequest.transId; + let offset = DescriptorWriteRequest.offset; + let isPrepared = DescriptorWriteRequest.isPrepared; + let needRsp = DescriptorWriteRequest.needRsp; + let value = new Uint8Array(DescriptorWriteRequest.value); + let descriptorUuid = DescriptorWriteRequest.descriptorUuid; + + descValue[0] = value[0]; + let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; + + try { + gattServer.sendResponse(serverResponse); + } catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); + } +} +gattServer.on('descriptorRead', WriteDescriptorReq); +``` + + +### off('descriptorWrite') + +off(type: 'descriptorWrite', callback?: Callback<DescriptorWriteRequest>): void + +Unsubscribes from descriptor write request events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **descriptorWrite**, which indicates a descriptor write request event. | +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | No | Callback for the descriptor write request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +gattServer.off('descriptorWrite'); +``` + + +### on('connectionStateChange') + +on(type: 'connectionStateChange', callback: Callback<BLEConnectionChangeState>): void + +Subscribes to BLE connection state change events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **connectionStateChange**, which indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | Yes | Callback invoked to return the BLE connection state. | + +**Example** + +```js +function Connected(BLEConnectionChangeState) { + let deviceId = BLEConnectionChangeState.deviceId; + let status = BLEConnectionChangeState.state; +} +gattServer.on('connectionStateChange', Connected); +``` + + +### off('connectionStateChange') + +off(type: 'connectionStateChange', callback?: Callback<BLEConnectionChangeState>): void + +Unsubscribes from BLE connection state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **connectionStateChange**, which indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | No | Callback for the BLE connection state change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +gattServer.off('connectionStateChange'); +``` + + +## GattClientDevice + +Implements the GATT client. Before using an API of this class, you must create a **GattClientDevice** instance using **createGattClientDevice(deviceId: string)**. + + +### connect + +connect(): void + +Connects to the remote BLE device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### disconnect + +disconnect(): void + +Disconnects from the remote BLE device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.disconnect(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### close + +close(): void + +Closes this GATT client to unregister it from the protocol stack. The closed [GattClientDevice](#gattclientdevice) instance will no longer be used. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.close(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getDeviceName + +getDeviceName(callback: AsyncCallback<string>): void + +Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the remote BLE device name obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// callback +try { + let gattClient = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let deviceName = gattClient.getDeviceName((err, data)=> { + console.info('device name err ' + JSON.stringify(err)); + console.info('device name' + JSON.stringify(data)); + }) +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getDeviceName + +getDeviceName(): Promise<string> + +Obtains the name of the remote BLE device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------- | +| Promise<string> | Promise used to return the remote BLE device name.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// promise +try { + let gattClient = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let deviceName = gattClient.getDeviceName().then((data) => { + console.info('device name' + JSON.stringify(data)); + }) +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getServices + +getServices(callback: AsyncCallback<Array<GattService>>): void + +Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<Array<[GattService](#gattservice)>> | Yes | Callback invoked to return the services obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Callback +function getServices(code, gattServices) { + if (code.code == 0) { + let services = gattServices; + console.log('bluetooth code is ' + code.code); + console.log('bluetooth services size is ', services.length); + + for (let i = 0; i < services.length; i++) { + console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); + } + } +} + +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); + device.getServices(getServices); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getServices + +getServices(): Promise<Array<GattService>> + +Obtains all services of the remote BLE device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------------- | +| Promise<Array<[GattService](#gattservice)>> | Promise used to return the services obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Promise +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.connect(); + device.getServices().then(result => { + console.info('getServices successfully:' + JSON.stringify(result)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### readCharacteristicValue + +readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void + +Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ----------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic value to read. | +| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the characteristic value read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +function readCcc(code, BLECharacteristic) { + if (code.code != 0) { + return; + } + console.log('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid); + let value = new Uint8Array(BLECharacteristic.characteristicValue); + console.log('bluetooth characteristic value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); +} + +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +characteristicValue: bufferCCC, descriptors:descriptors}; + +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readCharacteristicValue(characteristic, readCcc); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### readCharacteristicValue + +readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> + +Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | -------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Characteristic value to read.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<[BLECharacteristic](#blecharacteristic)> | Promise used to return the characteristic value read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', +characteristicValue: bufferCCC, descriptors:descriptors}; + +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readCharacteristicValue(characteristic); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### readDescriptorValue + +readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void + +Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ----------------------- | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback invoked to return the descriptor read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +function readDesc(code, BLEDescriptor) { + if (code.code != 0) { + return; + } + console.log('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid); + let value = new Uint8Array(BLEDescriptor.descriptorValue); + console.log('bluetooth descriptor value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]); +} + +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readDescriptorValue(descriptor, readDesc); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### readDescriptorValue + +readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> + +Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------- | ---- | -------- | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<[BLEDescriptor](#bledescriptor)> | Promise used to return the descriptor read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901000 | Read forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.readDescriptorValue(descriptor); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### writeCharacteristicValue + +writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType, callback: AsyncCallback<void>): void + +Writes a characteristic value to the remote BLE device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Binary value and other parameters of the BLE device characteristic.| +| writeType | GattWriteType | Yes | Write type of the Bluetooth device characteristic value.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the write operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + characteristicValue: bufferCCC, descriptors:descriptors}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeCharacteristicValue(characteristic); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### writeCharacteristicValue + +writeCharacteristicValue(characteristic: BLECharacteristic, writeType: GattWriteType): Promise<void> + +Writes a characteristic value to the remote BLE device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | Binary value and other parameters of the BLE device characteristic.| +| writeType | GattWriteType | Yes | Write type of the Bluetooth device characteristic value.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<void> | Promise used to return the descriptor read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let descriptors = []; +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc}; +descriptors[0] = descriptor; + +let bufferCCC = new ArrayBuffer(8); +let cccV = new Uint8Array(bufferCCC); +cccV[0] = 1; +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + characteristicValue: bufferCCC, descriptors:descriptors}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeCharacteristicValue(characteristic); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### writeDescriptorValue + +writeDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<void>): void + +Writes binary data to the specific descriptor of the remote BLE device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------- | ---- | ------------------ | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Binary value and other parameters of the BLE device descriptor.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the write operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 22; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeDescriptorValue(descriptor); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### writeDescriptorValue + +writeDescriptorValue(descriptor: BLEDescriptor): Promise<void> + +Writes binary data to the specific descriptor of the remote BLE device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------- | ---- | ------------------ | +| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Binary value and other parameters of the BLE device descriptor.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<void> | Promise used to return the descriptor read.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2901001 | Write forbidden. | +|2900099 | Operation failed. | + +**Example** + +```js +let bufferDesc = new ArrayBuffer(8); +let descV = new Uint8Array(bufferDesc); +descV[0] = 22; +let descriptor = { + serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', + descriptorValue: bufferDesc +}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.writeDescriptorValue(descriptor); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getRssiValue + +getRssiValue(callback: AsyncCallback<number>): void + +Obtains the RSSI of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the RSSI, in dBm.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +// callback +try { + let gattClient = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + gattClient.connect(); + let rssi = gattClient.getRssiValue((err, data)=> { + console.info('rssi err ' + JSON.stringify(err)); + console.info('rssi value' + JSON.stringify(data)); + }) +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### getRssiValue + +getRssiValue(): Promise<number> + +Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect). + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| Promise<number> | Promise used to return the RSSI, in dBm.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +// promise +try { + let gattClient = ble.createGattClientDevice("XX:XX:XX:XX:XX:XX"); + let rssi = gattClient.getRssiValue().then((data) => { + console.info('rssi' + JSON.stringify(data)); + }) +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### setBLEMtuSize + +setBLEMtuSize(mtu: number): void + +Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling [connect](#connect). + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------------- | +| mtu | number | Yes | MTU to set, which ranges from 22 to 512 bytes.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setBLEMtuSize(128); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### setCharacteristicChangeNotification + +setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void + +Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ----------------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | BLE characteristic to listen for. | +| enable | boolean | Yes | Whether to enable the notify function. The value **true** means to enable the notify function, and the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setCharacteristicChangeNotification(characteristic, false); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} + +``` + + +### setCharacteristicChangeNotification + +setCharacteristicChangeNotification(characteristic: BLECharacteristic, enable: boolean): Promise<void> + +Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ----------------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | BLE characteristic to listen for. | +| enable | boolean | Yes | Whether to enable the notify function. The value **true** means to enable the notify function, and the value **false** means the opposite.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setCharacteristicChangeNotification(characteristic, false); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} + +``` + + +### setCharacteristicChangeIndication + +setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean, callback: AsyncCallback<void>): void + +Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ----------------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | BLE characteristic to listen for. | +| enable | boolean | Yes | Whether to enable the notify function. The value **true** means to enable the notify function, and the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setCharacteristicChangeIndication(characteristic, false); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} + +``` + + +### setCharacteristicChangeIndication + +setCharacteristicChangeIndication(characteristic: BLECharacteristic, enable: boolean): Promise<void> + +Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------------------- | ---- | ----------------------------- | +| characteristic | [BLECharacteristic](#blecharacteristic) | Yes | BLE characteristic to listen for. | +| enable | boolean | Yes | Whether to enable the notify function. The value **true** means to enable the notify function, and the value **false** means the opposite.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.setCharacteristicChangeIndication(characteristic, false); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} + +``` + + +### on('BLECharacteristicChange') + +on(type: 'BLECharacteristicChange', callback: Callback<BLECharacteristic>): void + +Subscribes to BLE characteristic changes. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic value change event.| +| callback | Callback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the characteristic value changes. | + +**Example** + +```js +function CharacteristicChange(CharacteristicChangeReq) { + let serviceUuid = CharacteristicChangeReq.serviceUuid; + let characteristicUuid = CharacteristicChangeReq.characteristicUuid; + let value = new Uint8Array(CharacteristicChangeReq.characteristicValue); +} +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.on('BLECharacteristicChange', CharacteristicChange); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### off('BLECharacteristicChange') + +off(type: 'BLECharacteristicChange', callback?: Callback<BLECharacteristic>): void + +Unsubscribes from BLE characteristic change events. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLECharacteristicChange** indicates a characteristic value change event.| +| callback | Callback<[BLECharacteristic](#blecharacteristic)> | No | Callback for the characteristic value change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLECharacteristicChange'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### on('BLEConnectionStateChange') + +on(type: 'BLEConnectionStateChange', callback: Callback<BLEConnectionChangeState>): void + +Subscribes to BLE connection state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | Yes | Callback invoked to return the BLE connection state. | + +**Example** + +```js +function ConnectStateChanged(state) { + console.log('bluetooth connect state changed'); + let connectState = state.state; +} +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.on('BLEConnectionStateChange', ConnectStateChanged); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### off('BLEConnectionStateChange') + +off(type: 'BLEConnectionStateChange', callback?: Callback<BLEConnectionChangeState>): void + +Unsubscribes from BLE connection state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **BLEConnectionStateChange** indicates a BLE connection state change event.| +| callback | Callback<[BLEConnectionChangeState](#bleconnectionchangestate)> | No | Callback for the BLE connection state change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLEConnectionStateChange'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### on('BLEMtuChange') + +on(type: 'BLEMtuChange', callback: Callback<number>): void + +Subscribes to MTU status changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **BLEMtuChange**, which indicates a MTU status change event.| +| callback | Callback<number> | Yes | Callback invoked to return the MTU status, which can be connected or disconnected.| + +**Example** + +```js +try { + let gattClient = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + gattClient.on('BLEMtuChange', (mtu) => { + console.info('BLEMtuChange, mtu: ' + mtu); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### off('BLEMtuChange') + +off(type: 'BLEMtuChange', callback?: Callback<number>): void + +Unsubscribes from MTU status changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **BLEMtuChange**, which indicates a MTU status change event.| +| callback | Callback<number> | No | Callback for MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Example** + +```js +try { + let device = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX'); + device.off('BLEMtuChange'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## GattService + +Defines the GATT service API parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| isPrimary | boolean | Yes | Yes | Whether the service is a primary service. The value **true** means a primary service. | +| characteristics | Array<[BLECharacteristic](#blecharacteristic)> | Yes | Yes | List of characteristics of the service. | +| includeServices | Array<[GattService](#gattservice)> | Yes | Yes | Services on which the service depends. | + + +## BLECharacteristic + +Defines the characteristic API parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | +| descriptors | Array<[BLEDescriptor](#bledescriptor)> | Yes | Yes | List of descriptors of the characteristic. | +| properties | [GattProperties](#gattproperties) | Yes | Yes | Properties of the characteristic. | + + +## BLEDescriptor + +Defines the BLE descriptor. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| descriptorUuid | string | Yes | Yes | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| descriptorValue | ArrayBuffer | Yes | Yes | Binary value of the descriptor. | + + +## NotifyCharacteristic + +Defines the parameters in the notifications sent when the server characteristic value changes. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------- | ----------- | ---- | ---- | ---------------------------------------- | +| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | +| confirm | boolean | Yes | Yes | Whether the notification needs to be confirmed by the remote end. For a notification, set it to **true**. In this case, the remote end must confirm the receipt of the notification. For an indication, set it to **false**. In this case, the remote end does not need to confirm the receipt of the notification.| + + +## CharacteristicReadRequest + +Defines the parameters of the **CharacteristicReadReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends the **CharacteristicReadReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the read request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Position from which the characteristic value is read. For example, **k** means to read from the kth byte. The response returned by the server must use the same offset.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## CharacteristicWriteRequest + +Defines the parameters of the **CharacteristicWriteReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends the **CharacteristicWriteReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the write request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Start position for writing the characteristic value. For example, **k** means to write from the kth byte. The response returned by the server must use the same offset.| +| isPrepared | boolean | Yes | No | Whether the write request is executed immediately.| +| needRsp | boolean | Yes | No | Whether to send a response to the GATT client.| +| value | ArrayBuffer | Yes | No | Binary value of the descriptor to write.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## DescriptorReadRequest + +Defines the parameters of the **DescriptorReadReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends a **DescriptorReadReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the read request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Position from which the descriptor is read. For example, **k** means to read from the kth byte. The response returned by the server must use the same offset.| +| descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## DescriptorWriteRequest + +Defines the parameters of the **DescriptorWriteReq** event received by the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------------ | ----------- | ---- | ---- | ---------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device that sends a **DescriptorWriteReq** event, for example, XX:XX:XX:XX:XX:XX.| +| transId | number | Yes | No | Transmission ID of the write request. The response returned by the server must use the same transmission ID. | +| offset | number | Yes | No | Start position for writing the descriptor. For example, **k** means to write from the kth byte. The response returned by the server must use the same offset.| +| isPrepared | boolean | Yes | No | Whether the write request is executed immediately. | +| needRsp | boolean | Yes | No | Whether to send a response to the GATT client. | +| value | ArrayBuffer | Yes | No | Binary value of the descriptor to write. | +| descriptorUuid | string | Yes | No | UUID of the descriptor, for example, **00002902-0000-1000-8000-00805f9b34fb**.| +| characteristicUuid | string | Yes | No | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| + + +## ServerResponse + +Defines the parameters of the server's response to the GATT client's read/write request. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ----------- | ---- | ---- | -------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX. | +| transId | number | Yes | No | Transmission ID of the request. The value must be the same as the ID carried in the read/write request received. | +| status | number | Yes | No | Response state. Set this parameter to **0**, which indicates a normal response. | +| offset | number | Yes | No | Start read/write position. The value must be the same as the offset carried in the read/write request.| +| value | ArrayBuffer | Yes | No | Binary data in the response. | + + +## BLEConnectionChangeState + +Defines the parameters of **BLEConnectChangedState**. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| state | [ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | Yes | Yes | BLE connection state. | + + +## ScanResult + +Defines the scan result. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ----------- | ---- | ---- | ---------------------------------- | +| deviceId | string | Yes | No | Address of the scanned device, for example, XX:XX:XX:XX:XX:XX.| +| rssi | number | Yes | No | RSSI of the device. | +| data | ArrayBuffer | Yes | No | Advertisement packets sent by the device. | +| deviceName | string | Yes | No | Name of the device detected. | +| connectable | boolean | Yes | No | Whether the discovered device is connectable. | + + +## AdvertiseSetting + +Defines the BLE advertising parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ----------- | ------- | ---- | ---- | ---------------------------------------- | +| interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16384** slots. The default value is **1600** slots (1s).| +| txPower | number | Yes | Yes | Transmit power, in dBm. The value range is -127 to 1. The default value is **-7**. | +| connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | + + +## AdvertiseData + +Defines the content of a BLE advertisement packet. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------------- | ---------------------------------------- | ---- | ---- | --------------------------- | +| serviceUuids | Array<string> | Yes | Yes | List of service UUIDs to broadcast.| +| manufactureData | Array<[ManufactureData](#manufacturedata)> | Yes | Yes | List of manufacturers to broadcast. | +| serviceData | Array<[ServiceData](#servicedata)> | Yes | Yes | List of service data to broadcast. | +| includeDeviceName | boolean | Yes | Yes | Whether the device name is contained. This parameter is optional. | + + +## ManufactureData + +Defines the content of a BLE advertisement packet. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ---------------- | ------------------- | ---- | ---- | ------------------ | +| manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| +| manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | + + +## ServiceData + +Defines the service data contained in an advertisement packet. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------------ | ----------- | ---- | ---- | ---------- | +| serviceUuid | string | Yes | Yes | Service UUID.| +| serviceValue | ArrayBuffer | Yes | Yes | Service data. | + + +## ScanFilter + +Defines the scan filter parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable| Writable| Description | +| ---------------------------------------- | ----------- | ---- | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. | +| name | string | Yes | Yes | Name of the BLE device to filter. | +| serviceUuid | string | Yes | Yes | Service UUID of the device to filter, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| serviceUuidMask | string | Yes | Yes | Service UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| +| serviceSolicitationUuid | string | Yes | Yes | Service solicitation UUID of the device to filter, for example, **00001888-0000-1000-8000-00805F9B34FB**.| +| serviceSolicitationUuidMask | string | Yes | Yes | Service solicitation UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| +| serviceData | ArrayBuffer | Yes | Yes | Service data of the device to filter, for example, **[0x90, 0x00, 0xF1, 0xF2]**.| +| serviceDataMask | ArrayBuffer | Yes | Yes | Service data mask of the device to filter, for example, **[0xFF,0xFF,0xFF,0xFF]**.| +| manufactureId | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. | +| manufactureData | ArrayBuffer | Yes | Yes | Manufacturer data of the device to filter, for example, **[0x1F,0x2F,0x3F]**.| +| manufactureDataMask | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.| + + +## ScanOptions + +Defines the scan configuration parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------- | ----------------------- | ---- | ---- | -------------------------------------- | +| interval | number | Yes | Yes | Delay in reporting the scan result. The default value is **0**. | +| dutyMode | [ScanDuty](#scanduty) | Yes | Yes | Scan duty. The default value is SCAN_MODE_LOW_POWER. | +| matchMode | [MatchMode](#matchmode) | Yes | Yes | Hardware filtering match mode. The default value is **MATCH_MODE_AGGRESSIVE**.| + + +## GattProperties + +Defines the properties of a GATT characteristic. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Mandatory | Description | +| -------- | ------ |---- | ----------- | +| write | boolean | Yes | Permits writes of the characteristic value (with a response).| +| writeNoResponse | boolean | Yes | Permits writes of the characteristic value (without a response).| +| read | boolean | Yes | Permits reads of the characteristic value.| +| notify | boolean | Yes | Permits notifications of the characteristic value.| +| indicate | boolean | Yes | Permits notifications of the characteristic value without acknowledgement.| + + +## GattWriteType + +Enumerates the GATT write types. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------------------------| ------ | --------------- | +| WRITE | 1 | Write a characteristic value with a response from the peer device. | +| WRITE_NO_RESPONSE | 2 | Write characteristic value without a response from the peer device. | + + +## ScanDuty + +Enumerates the scan duties. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| +| SCAN_MODE_BALANCED | 1 | Balanced mode. | +| SCAN_MODE_LOW_LATENCY | 2 | Low-latency mode. | + + +## MatchMode + +Enumerates the hardware match modes of BLE scan filters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| --------------------- | ---- | ---------------------------------------- | +| MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| +| MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-connection.md b/en/application-dev/reference/apis/js-apis-bluetooth-connection.md new file mode 100644 index 0000000000000000000000000000000000000000..72f54a63f95bbd51029b191ff697f3aeea55577c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-connection.md @@ -0,0 +1,1397 @@ +# @ohos.bluetooth.connection (Bluetooth connection Module) + +The **connection** module provides APIs for operating and managing Bluetooth. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import connection from '@ohos.bluetooth.connection'; +``` + + +## connection.pairDevice + +pairDevice(deviceId: string, callback: AsyncCallback<void>): void + +Pairs a Bluetooth device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the pairing is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + // The address can be scanned. + connection.pairDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.pairDevice + +pairDevice(deviceId: string): Promise<void> + +Pairs a Bluetooth device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + // The address can be scanned. + connection.pairDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.pairCredibleDevice + +pairCredibleDevice(deviceId: string, transport: BluetoothTransport, callback: AsyncCallback<void>): void + +Pairs a trusted device whose address is obtained in a non-Bluetooth scan mode (such as using NFC). This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.| +| transport | [BluetoothTransport](#bluetoothtransport) | Yes | Device type, for example, a classic Bluetooth device or a Bluetooth low energy (BLE) device.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.pairCredibleDevice('68:13:24:79:4C:8C', 1, err => { + if (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); + return; + } + console.info('pairCredibleDevice, err: ' + JSON.stringify(err)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.pairCredibleDevice + +pairCredibleDevice(deviceId: string, transport: BluetoothTransport): Promise<void> + +Pairs a trusted device whose address is obtained in a non-Bluetooth scan mode (such as using NFC). This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.| +| transport | [BluetoothTransport](#bluetoothtransport) | Yes | Device type, for example, a classic Bluetooth device or a BLE device.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | ------------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.pairCredibleDevice('68:13:24:79:4C:8C', 0).then(() => { + console.info('PairCredibleDevice'); + }, err => { + console.error('PairCredibleDevice:errCode' + err.code + ', errMessage: ' + err.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.cancelPairedDevice + +cancelPairedDevice(deviceId: string, callback: AsyncCallback<void>): void + +Cancels a paired device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------- | +| deviceId | string | Yes | Address of the device to cancel, for example, XX:XX:XX:XX:XX:XX.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.cancelPairedDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.cancelPairedDevice + +cancelPairedDevice(deviceId: string): Promise<void> + +Cancels a paired device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------- | +| deviceId | string | Yes | Address of the device to cancel, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.cancelPairedDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.cancelPairingDevice + +cancelPairingDevice(deviceId: string, callback: AsyncCallback<void>): void + +Cancels the pairing of a device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------- | +| deviceId | string | Yes | Address of the device to cancel, for example, XX:XX:XX:XX:XX:XX.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.cancelPairingDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.cancelPairingDevice + +cancelPairingDevice(deviceId: string): Promise<void> + +Cancels the pairing of a device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------------- | +| deviceId | string | Yes | Address of the device to cancel, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.cancelPairingDevice('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getRemoteDeviceName + +getRemoteDeviceName(deviceId: string): string + +Obtains the name of a remote Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | --------------------------------- | +| deviceId | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------ | ------------- | +| string | Device name (a string) obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let remoteDeviceName = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getRemoteDeviceClass + +getRemoteDeviceClass(deviceId: string): DeviceClass + +Obtains the class of a remote Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | --------------------------------- | +| deviceId | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| --------------------------- | -------- | +| [DeviceClass](#deviceclass) | Class of the remote device obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let remoteDeviceClass = connection.getRemoteDeviceClass('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getLocalName + +getLocalName(): string + +Obtains the name of the local Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------ | --------- | +| string | Name of the local Bluetooth device obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let localName = connection.getLocalName(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getPairedDevices + +getPairedDevices(): Array<string> + +Obtains the paired devices. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Array<string> | Addresses of the paired Bluetooth devices obtained. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let devices = connection.getPairedDevices(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getProfileConnectionState + +getProfileConnectionState(profileId?: ProfileId): ProfileConnectionState + +Obtains the connection state of the specified profile. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------- | ---- | ------------------------------------- | +| ProfileId | [profileId](js-apis-bluetooth-constant.md#profileid) | No | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| + +**Return value** + +| Type | Description | +| ------------------------------------------------- | ------------------- | +| [ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | Profile connection state obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +import constant from '@ohos.bluetooth.constant'; +try { + let result = connection.getProfileConnectionState(constant.ProfileId.PROFILE_A2DP_SOURCE); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.setDevicePairingConfirmation + +setDevicePairingConfirmation(deviceId: string, accept: boolean): void + +Sets the device pairing confirmation. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------------------- | +| deviceId | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js + +try { + // Subscribe to the pinRequired event and configure the pairing confirmation after receiving a pairing request from the remote device. + function onReceivePinRequiredEvent(data) { // data is the input parameter for the pairing request. + console.info('pin required = '+ JSON.stringify(data)); + connection.setDevicePairingConfirmation(data.deviceId, true); + } + connection.on('pinRequired', onReceivePinRequiredEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.setDevicePinCode + +setDevicePinCode(deviceId: string, code: string, callback: AsyncCallback<void>): void + +Sets the PIN for the device when [PinType](#pintype) is **PIN_TYPE_ENTER_PIN_CODE** or **PIN_TYPE_PIN_16_DIGITS**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------------------- | +| deviceId | string | Yes | MAC address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| code | string | Yes | PIN to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +//callback +try { + connection.setDevicePinCode('11:22:33:44:55:66', '12345', (err, data) => { + console.info('setDevicePinCode,device name err:' + JSON.stringify(err) + ',device name:' + JSON.stringify(data)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.setDevicePinCode + +setDevicePinCode(deviceId: string, code: string): Promise<void> + +Sets the PIN for the device when [PinType](#pintype) is **PIN_TYPE_ENTER_PIN_CODE** or **PIN_TYPE_PIN_16_DIGITS**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------------------- | +| deviceId | string | Yes | MAC address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| code | string | Yes | PIN to set. | + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +//promise +try { + connection.setDevicePinCode('11:22:33:44:55:66', '12345').then(() => { + console.info('setDevicePinCode'); + }, error => { + console.info('setDevicePinCode: errCode:' + error.code + ',errMessage' + error.message); + }) + +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.setLocalName + +setLocalName(name: string): void + +Sets the name of the local Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------------- | +| name | string | Yes | Bluetooth device name to set. It cannot exceed 248 bytes.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.setLocalName('device_name'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.setBluetoothScanMode + +setBluetoothScanMode(mode: ScanMode, duration: number): void + +Sets the Bluetooth scan mode so that the device can be discovered by a remote device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ---------------------------- | +| mode | [ScanMode](#scanmode) | Yes | Bluetooth scan mode to set. | +| duration | number | Yes | Duration (in ms) in which the device can be discovered. The value **0** indicates unlimited time.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + // The device can be discovered and connected only when the discoverable and connectable mode is used. + connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getBluetoothScanMode + +getBluetoothScanMode(): ScanMode + +Obtains the Bluetooth scan mode. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | ------- | +| [ScanMode](#scanmode) | Bluetooth scan mode obtained. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let scanMode = connection.getBluetoothScanMode(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.startBluetoothDiscovery + +startBluetoothDiscovery(): void + +Starts discovery of Bluetooth devices. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +let deviceId; +function onReceiveEvent(data) { + deviceId = data; +} +try { + connection.on('bluetoothDeviceFind', onReceiveEvent); + connection.startBluetoothDiscovery(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.stopBluetoothDiscovery + +stopBluetoothDiscovery(): void + +Stops discovery of Bluetooth devices. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.stopBluetoothDiscovery(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getLocalProfileUuids + +getLocalProfileUuids(callback: AsyncCallback<Array<ProfileUuids>>): void + +Obtains the profile UUIDs of the local device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| callback | AsyncCallback<Array<[ProfileUuids](js-apis-bluetooth-constant.md#profileuuids)>> | Yes | Callback invoked to return the profile UUIDs obtained. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.getLocalProfileUuids('XX:XX:XX:XX:XX:XX', (err, data) => { + console.info('getLocalProfileUuids, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getLocalProfileUuids + +getLocalProfileUuids(): Promise<Array<ProfileUuids>> + +Obtains the profile UUIDs of the local device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<Array<[ProfileUuids](js-apis-bluetooth-constant.md#profileuuids)>> | Promise used to return the profile UUIDs obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.getLocalProfileUuids('XX:XX:XX:XX:XX:XX').then(() => { + console.info('getLocalProfileUuids'); + }, err => { + console.error('getLocalProfileUuids: errCode' + err.code + ', errMessage: ' + err.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.getRemoteProfileUuids + +getRemoteProfileUuids(deviceId: string, callback: AsyncCallback<Array<ProfileUuids>>): void + +Obtains the profile UUIDs of a remote Bluetooth device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.| +| callback | AsyncCallback<Array<[ProfileUuids](js-apis-bluetooth-constant.md#profileuuids)>> | Yes | Callback invoked to return the profile UUIDs obtained. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX', (err, data) => { + console.info('getRemoteProfileUuids, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} + +``` + + +## connection.getRemoteProfileUuids + +getRemoteProfileUuids(deviceId: string): Promise<Array<ProfileUuids>> + +Obtains the profile UUIDs of a remote Bluetooth device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------------------- | +| deviceId | string | Yes | Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<Array<[ProfileUuids](js-apis-bluetooth-constant.md#profileuuids)>> | Promise used to return the profile UUIDs obtained.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX').then(() => { + console.info('getRemoteProfileUuids'); + }, err => { + console.error('getRemoteProfileUuids: errCode' + err.code + ', errMessage: ' + err.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.on('bluetoothDeviceFind') + +on(type: 'bluetoothDeviceFind', callback: Callback<Array<string>>): void + +Subscribes to the discovery of a Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **bluetoothDeviceFind**, which indicates an event of discovering a Bluetooth device.| +| callback | Callback<Array<string>> | Yes | Callback invoked to return the discovered devices. You need to implement this callback. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { // data is a set of Bluetooth device addresses. + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + connection.on('bluetoothDeviceFind', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.off('bluetoothDeviceFind') + +off(type: 'bluetoothDeviceFind', callback?: Callback<Array<string>>): void + +Unsubscribes from the discovery of a Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **bluetoothDeviceFind**, which indicates an event of discovering a Bluetooth device. | +| callback | Callback<Array<string>> | No | Callback for the **bluetoothDeviceFind** event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bluetooth device find = '+ JSON.stringify(data)); +} +try { + connection.on('bluetoothDeviceFind', onReceiveEvent); + connection.off('bluetoothDeviceFind', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.on('bondStateChange') + +on(type: 'bondStateChange', callback: Callback<BondStateParam>): void + +Subscribes to Bluetooth pairing state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| type | string | Yes | Event type. The value is **bondStateChange**, which indicates a Bluetooth pairing state change event.| +| callback | Callback<[BondStateParam](#BondStateParam)> | Yes | Callback invoked to return the pairing state. You need to implement this callback. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the pairing state. + console.info('pair state = '+ JSON.stringify(data)); +} +try { + connection.on('bondStateChange', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.off('bondStateChange') + +off(type: 'bondStateChange', callback?: Callback<BondStateParam>): void + +Unsubscribes from Bluetooth pairing state changes. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **bondStateChange**, which indicates a Bluetooth pairing state change event. | +| callback | Callback<[BondStateParam](#BondStateParam)> | No | Callback for the change of the Bluetooth pairing state. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('bond state = '+ JSON.stringify(data)); +} +try { + connection.on('bondStateChange', onReceiveEvent); + connection.off('bondStateChange', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.on('pinRequired') + +on(type: 'pinRequired', callback: Callback<PinRequiredParam>): void + +Subscribes to the pairing request events of the remote Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| type | string | Yes | Event type. The value **pinRequired** indicates a pairing request event. | +| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | Yes | Callback invoked to return the pairing request. You need to implement this callback.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { // data is the pairing request parameter. + console.info('pin required = '+ JSON.stringify(data)); +} +try { + connection.on('pinRequired', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## connection.off('pinRequired') + +off(type: 'pinRequired', callback?: Callback<PinRequiredParam>): void + +Unsubscribes from the pairing request events of the remote Bluetooth device. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value **pinRequired** indicates a pairing request event. | +| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | No | Callback for the Bluetooth pairing request event. The input parameter is the pairing request parameter. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900099 | Operation failed. | + +**Example** + +```js +function onReceiveEvent(data) { + console.info('pin required = '+ JSON.stringify(data)); +} +try { + connection.on('pinRequired', onReceiveEvent); + connection.off('pinRequired', onReceiveEvent); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## BondStateParam + +Represents the pairing state parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | Yes | No | ID of the device to pair.| +| state | BondState | Yes | No | State of the device.| + + +## PinRequiredParam + +Represents the pairing request parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | Yes | No | ID of the device to pair.| +| pinCode | string | Yes | No | Key for the device pairing. | +| pinType | [PinType](#pintype) | Yes | No | Type of the device to pair.
This is a system API. | + + +## DeviceClass + +Represents the class of a Bluetooth device. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| --------------- | ----------------------------------- | ---- | ---- | ---------------- | +| majorClass | [MajorClass](js-apis-bluetooth-constant.md#majorclass) | Yes | No | Major class of the Bluetooth device. | +| majorMinorClass | [MajorMinorClass](js-apis-bluetooth-constant.md#majorminorclass) | Yes | No | Major and minor classes of the Bluetooth device.| +| classOfDevice | number | Yes | No | Class of the device. | + + +## BluetoothTransport + +Enumerates the device types. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| -------------------------------- | ------ | --------------- | +| TRANSPORT_BR_EDR | 0 | Classic Bluetooth (BR/EDR) device, which is the default value. | +| TRANSPORT_LE | 1 | BLE device. | + + +## ScanMode + +Enumerates the scan modes. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ---------------------------------------- | ---- | --------------- | +| SCAN_MODE_NONE | 0 | No scan mode. | +| SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | +| SCAN_MODE_GENERAL_DISCOVERABLE | 2 | General discoverable mode. | +| SCAN_MODE_LIMITED_DISCOVERABLE | 3 | Limited discoverable mode. | +| SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | General connectable and discoverable mode.| +| SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | Limited connectable and discoverable mode.| + + +## BondState + +Enumerates the pairing states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------ | ---- | ------ | +| BOND_STATE_INVALID | 0 | Invalid pairing.| +| BOND_STATE_BONDING | 1 | Pairing. | +| BOND_STATE_BONDED | 2 | Paired. | + + +## PinType + +Enumerates the Bluetooth pairing types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| -------------------------------- | ------ | --------------- | +| PIN_TYPE_ENTER_PIN_CODE | 0 | The user needs to enter the PIN displayed on the peer device.
This is a system API.| +| PIN_TYPE_ENTER_PASSKEY | 1 | The user needs to enter the PASSKEY displayed on the peer device.
This is a system API. | +| PIN_TYPE_CONFIRM_PASSKEY | 2 | The user needs to confirm the PASSKEY displayed on the local device.
This is a system API. | +| PIN_TYPE_NO_PASSKEY_CONSENT | 3 | There is no PASSKEY, and the user needs to accept or reject the pairing request.
This is a system API. | +| PIN_TYPE_NOTIFY_PASSKEY | 4 | The user needs to enter the PASSKEY displayed on the local device on the peer device.
This is a system API. | +| PIN_TYPE_DISPLAY_PIN_CODE | 5 | The user needs to enter the PIN displayed on the peer device for Bluetooth 2.0 devices.
This is a system API. | +| PIN_TYPE_OOB_CONSENT | 6 | The user needs to accept or reject the out of band (OOB) pairing request.
This is a system API. | +| PIN_TYPE_PIN_16_DIGITS | 7 | The user needs to enter the 16-digit PIN displayed on the peer device.
This is a system API. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-constant.md b/en/application-dev/reference/apis/js-apis-bluetooth-constant.md new file mode 100644 index 0000000000000000000000000000000000000000..a8456d7218b5266619cc58871f1b5d438a54c7c7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-constant.md @@ -0,0 +1,181 @@ +# @ohos.bluetooth.constant (Bluetooth constant Module) + +The **constant** module provides definitions of the constants used in Bluetooth. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import constant from '@ohos.bluetooth.constant'; +``` + +## ProfileId + +Enumerates profiles. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| -------------------------------- | ------ | --------------- | +| PROFILE_A2DP_SOURCE | 1 | Advanced Audio Distribution Profile (A2DP).| +| PROFILE_HANDSFREE_AUDIO_GATEWAY | 4 | Hands-Free Profile (HFP). | +| PROFILE_HID_HOST | 6 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK | 7 | Bluetooth personal area network (PAN) profile. | + + +## ProfileUuids + +Enumerates profile UUIDs. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------------------------| ------ | --------------- | +| PROFILE_UUID_HFP_AG | '0000111F-0000-1000-8000-00805F9B34FB' | UUID of the HFPAG Profile.
This is a system API.| +| PROFILE_UUID_HFP_HF | '0000111E-0000-1000-8000-00805F9B34FB' | UUID of the HFPHF Profile.
This is a system API. | +| PROFILE_UUID_HSP_AG | '00001112-0000-1000-8000-00805F9B34FB' | UUID of the HSPAG Profile.
This is a system API. | +| PROFILE_UUID_HSP_HS | '00001108-0000-1000-8000-00805F9B34FB' | UUID of the HSPHS Profile.
This is a system API. | +| PROFILE_UUID_A2DP_SRC | '0000110A-0000-1000-8000-00805F9B34FB' | Indicates the UID of the A2DPSRC Profile.
This is a system API. | +| PROFILE_UUID_A2DP_SINK | '0000110B-0000-1000-8000-00805F9B34FB' | UUID of the A2DPSINK Profile.
This is a system API. | +| PROFILE_UUID_AVRCP_CT | '0000110E-0000-1000-8000-00805F9B34FB' | UUID of the AVRCPCT Profile.
This is a system API. | +| PROFILE_UUID_AVRCP_TG | '0000110C-0000-1000-8000-00805F9B34FB' | UUID of the AVRCPTG Profile.
This is a system API. | +| PROFILE_UUID_HID | '00001124-0000-1000-8000-00805F9B34FB' | UUID of the HID Profile.
This is a system API. | +| PROFILE_UUID_HOGP | '00001812-0000-1000-8000-00805F9B34FB' | UUID of the HOGP Profile.
This is a system API. | + + +## ProfileConnectionState + +Enumerates the profile connection states. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------- | ---- | -------------- | +| STATE_DISCONNECTED | 0 | Disconnected. | +| STATE_CONNECTING | 1 | Connecting.| +| STATE_CONNECTED | 2 | Connected. | +| STATE_DISCONNECTING | 3 | Disconnecting.| + + +## MajorClass + +Enumerates the major classes of Bluetooth devices. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ------------------- | ------ | ---------- | +| MAJOR_MISC | 0x0000 | Miscellaneous device. | +| MAJOR_COMPUTER | 0x0100 | Computer. | +| MAJOR_PHONE | 0x0200 | Mobile phone. | +| MAJOR_NETWORKING | 0x0300 | Network device. | +| MAJOR_AUDIO_VIDEO | 0x0400 | Audio or video device.| +| MAJOR_PERIPHERAL | 0x0500 | Peripheral device. | +| MAJOR_IMAGING | 0x0600 | Imaging device. | +| MAJOR_WEARABLE | 0x0700 | Wearable device. | +| MAJOR_TOY | 0x0800 | Toy. | +| MAJOR_HEALTH | 0x0900 | Health device. | +| MAJOR_UNCATEGORIZED | 0x1F00 | Unclassified device. | + + +## MajorMinorClass + +Enumerates the major and minor classes of Bluetooth devices. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ---------------------------------------- | ------ | --------------- | +| COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | +| COMPUTER_DESKTOP | 0x0104 | Desktop computer. | +| COMPUTER_SERVER | 0x0108 | Server. | +| COMPUTER_LAPTOP | 0x010C | Laptop. | +| COMPUTER_HANDHELD_PC_PDA | 0x0110 | Hand-held computer. | +| COMPUTER_PALM_SIZE_PC_PDA | 0x0114 | Palmtop computer. | +| COMPUTER_WEARABLE | 0x0118 | Wearable computer. | +| COMPUTER_TABLET | 0x011C | Tablet. | +| PHONE_UNCATEGORIZED | 0x0200 | Unclassified mobile phone. | +| PHONE_CELLULAR | 0x0204 | Portable phone. | +| PHONE_CORDLESS | 0x0208 | Cordless phone. | +| PHONE_SMART | 0x020C | Smartphone. | +| PHONE_MODEM_OR_GATEWAY | 0x0210 | Modem or gateway phone.| +| PHONE_ISDN | 0x0214 | ISDN phone. | +| NETWORK_FULLY_AVAILABLE | 0x0300 | Device with network fully available. | +| NETWORK_1_TO_17_UTILIZED | 0x0320 | Device used on network 1 to 17. | +| NETWORK_17_TO_33_UTILIZED | 0x0340 | Device used on network 17 to 33. | +| NETWORK_33_TO_50_UTILIZED | 0x0360 | Device used on network 33 to 50. | +| NETWORK_60_TO_67_UTILIZED | 0x0380 | Device used on network 60 to 67. | +| NETWORK_67_TO_83_UTILIZED | 0x03A0 | Device used on network 67 to 83. | +| NETWORK_83_TO_99_UTILIZED | 0x03C0 | Device used on network 83 to 99. | +| NETWORK_NO_SERVICE | 0x03E0 | Device without network service | +| AUDIO_VIDEO_UNCATEGORIZED | 0x0400 | Unclassified audio or video device. | +| AUDIO_VIDEO_WEARABLE_HEADSET | 0x0404 | Wearable audio or video headset. | +| AUDIO_VIDEO_HANDSFREE | 0x0408 | Hands-free audio or video device. | +| AUDIO_VIDEO_MICROPHONE | 0x0410 | Audio or video microphone. | +| AUDIO_VIDEO_LOUDSPEAKER | 0x0414 | Audio or video loudspeaker. | +| AUDIO_VIDEO_HEADPHONES | 0x0418 | Audio or video headphones. | +| AUDIO_VIDEO_PORTABLE_AUDIO | 0x041C | Portable audio or video device. | +| AUDIO_VIDEO_CAR_AUDIO | 0x0420 | In-vehicle audio or video device. | +| AUDIO_VIDEO_SET_TOP_BOX | 0x0424 | Audio or video STB device. | +| AUDIO_VIDEO_HIFI_AUDIO | 0x0428 | High-fidelity speaker device. | +| AUDIO_VIDEO_VCR | 0x042C | Video cassette recording (VCR) device. | +| AUDIO_VIDEO_VIDEO_CAMERA | 0x0430 | Camera. | +| AUDIO_VIDEO_CAMCORDER | 0x0434 | Camcorder | +| AUDIO_VIDEO_VIDEO_MONITOR | 0x0438 | Audio or video monitor. | +| AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER | 0x043C | Video display or loudspeaker. | +| AUDIO_VIDEO_VIDEO_CONFERENCING | 0x0440 | Video conferencing device. | +| AUDIO_VIDEO_VIDEO_GAMING_TOY | 0x0448 | Audio or video gaming toy. | +| PERIPHERAL_NON_KEYBOARD_NON_POINTING | 0x0500 | Non-keyboard or non-pointing peripheral device. | +| PERIPHERAL_KEYBOARD | 0x0540 | Keyboard device. | +| PERIPHERAL_POINTING_DEVICE | 0x0580 | Pointing peripheral device. | +| PERIPHERAL_KEYBOARD_POINTING | 0x05C0 | Keyboard pointing device. | +| PERIPHERAL_UNCATEGORIZED | 0x0500 | Unclassified peripheral device. | +| PERIPHERAL_JOYSTICK | 0x0504 | Peripheral joystick. | +| PERIPHERAL_GAMEPAD | 0x0508 | Peripheral game pad | +| PERIPHERAL_REMOTE_CONTROL | 0x05C0 | Peripheral remote control device | +| PERIPHERAL_SENSING_DEVICE | 0x0510 | Peripheral sensing device. | +| PERIPHERAL_DIGITIZER_TABLET | 0x0514 | Peripheral digitizer tablet.| +| PERIPHERAL_CARD_READER | 0x0518 | Peripheral card reader. | +| PERIPHERAL_DIGITAL_PEN | 0x051C | Peripheral digital pen. | +| PERIPHERAL_SCANNER_RFID | 0x0520 | Peripheral RFID scanner. | +| PERIPHERAL_GESTURAL_INPUT | 0x0522 | Gesture input device. | +| IMAGING_UNCATEGORIZED | 0x0600 | Unclassified imaging device. | +| IMAGING_DISPLAY | 0x0610 | Imaging display device. | +| IMAGING_CAMERA | 0x0620 | Imaging camera device. | +| IMAGING_SCANNER | 0x0640 | Imaging scanner. | +| IMAGING_PRINTER | 0x0680 | Imaging printer. | +| WEARABLE_UNCATEGORIZED | 0x0700 | Unclassified wearable device. | +| WEARABLE_WRIST_WATCH | 0x0704 | Smart watch. | +| WEARABLE_PAGER | 0x0708 | Wearable pager. | +| WEARABLE_JACKET | 0x070C | Smart jacket. | +| WEARABLE_HELMET | 0x0710 | Wearable helmet. | +| WEARABLE_GLASSES | 0x0714 | Wearable glasses. | +| TOY_UNCATEGORIZED | 0x0800 | Unclassified toy. | +| TOY_ROBOT | 0x0804 | Toy robot. | +| TOY_VEHICLE | 0x0808 | Toy vehicle. | +| TOY_DOLL_ACTION_FIGURE | 0x080C | Humanoid toy doll. | +| TOY_CONTROLLER | 0x0810 | Toy controller. | +| TOY_GAME | 0x0814 | Toy gaming device. | +| HEALTH_UNCATEGORIZED | 0x0900 | Unclassified health devices. | +| HEALTH_BLOOD_PRESSURE | 0x0904 | Blood pressure device. | +| HEALTH_THERMOMETER | 0x0908 | Thermometer | +| HEALTH_WEIGHING | 0x090C | Body scale. | +| HEALTH_GLUCOSE | 0x0910 | Blood glucose monitor. | +| HEALTH_PULSE_OXIMETER | 0x0914 | Pulse oximeter. | +| HEALTH_PULSE_RATE | 0x0918 | Heart rate monitor. | +| HEALTH_DATA_DISPLAY | 0x091C | Health data display. | +| HEALTH_STEP_COUNTER | 0x0920 | Step counter. | +| HEALTH_BODY_COMPOSITION_ANALYZER | 0x0924 | Body composition analyzer. | +| HEALTH_PEAK_FLOW_MONITOR | 0x0928 | Hygrometer. | +| HEALTH_MEDICATION_MONITOR | 0x092C | Medication monitor. | +| HEALTH_KNEE_PROSTHESIS | 0x0930 | Prosthetic knee. | +| HEALTH_ANKLE_PROSTHESIS | 0x0934 | Prosthetic ankle. | +| HEALTH_GENERIC_HEALTH_MANAGER | 0x0938 | Generic health management device. | +| HEALTH_PERSONAL_MOBILITY_DEVICE | 0x093C | Personal mobility device. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-hfp.md b/en/application-dev/reference/apis/js-apis-bluetooth-hfp.md new file mode 100644 index 0000000000000000000000000000000000000000..c9163681742e3dd19cf114518c742b0ff3d26c00 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-hfp.md @@ -0,0 +1,128 @@ +# @ohos.bluetooth.hfp (Bluetooth hfp Module) + +The **hfp** module provides APIs for using the Bluetooth Hands-Free Profile (HFP). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import hfp from '@ohos.bluetooth.hfp'; +``` + + +## hfp.createHfpAgProfile + +createHfpAgProfile(): HandsFreeAudioGatewayProfile + +Creates an **HfpAgProfile** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| HandsFreeAudioGatewayProfile | **HfpAgProfile** instance created.| + +**Example** + +```js +try { + let hfpAgProfile = hfp.createHfpAgProfile(); + console.info('hfpAg success'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## HandsFreeAudioGatewayProfile + +Before using any API of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using **createHfpAgProfile()**. + + +### connect + +connect(deviceId: string): void + +Connects to a hands-free device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the remote device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hfpAg = hfp.createHfpAgProfile(); + hfpAg.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### disconnect + +disconnect(deviceId: string): void + +Disconnects from a hands-free device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the remote device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hfpAg = hfp.createHfpAgProfile(); + hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-hid.md b/en/application-dev/reference/apis/js-apis-bluetooth-hid.md new file mode 100644 index 0000000000000000000000000000000000000000..a4449a7d63088b3398bb42596e5499c72a1dad3e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-hid.md @@ -0,0 +1,128 @@ +# @ohos.bluetooth.hid (Bluetooth hid Module) + +The **hid** module provides APIs for using the Bluetooth Human Interface Device Profile (HID). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import hid from '@ohos.bluetooth.hid'; +``` + + +## hid.createHidHostProfile + +createHidHostProfile(): HidHostProfile + +Creates a **HidHostProfile** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| HidHostProfile | **HidHostProfile** instance created.| + +**Example** + +```js +try { + let hidHostProfile = hid.createHidHostProfile(); + console.info('hidHost success'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## HidHostProfile + +Before using any API of **HidHostProfile**, you need to create an instance of this class by using **createHidHostProfile()**. + + +### connect + +connect(deviceId: string): void + +Connects to the HidHost service of a device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the remote device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hidHostProfile = hid.createHidHostProfile(); + hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### disconnect + +disconnect(deviceId: string): void + +Disconnects from the HidHost service of a device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the remote device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let hidHostProfile = hid.createHidHostProfile(); + hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-pan.md b/en/application-dev/reference/apis/js-apis-bluetooth-pan.md new file mode 100644 index 0000000000000000000000000000000000000000..b74dbdcbd5e656fc29d2042625b8d1113790488c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-pan.md @@ -0,0 +1,158 @@ +# @ohos.bluetooth.pan (Bluetooth pan Module) + +The **pan** module provides APIs for accessing the Bluetooth personal area network (PAN). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import pan from '@ohos.bluetooth.pan'; +``` + + +## pan.createPanProfile + +createPanProfile(): PanProfile + +Creates a **PanProfile** instance. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ---------- | +| PanProfile | **PanProfile** instance created.| + +**Example** + +```js +try { + let panProfile = pan.createPanProfile(); + console.info('pan success'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## PanProfile + +Before using any API of **PanProfile**, you need to create an instance of this class by using **createPanProfile()**. + + +### disconnect + +disconnect(deviceId: string): void + +Disconnects from the PAN service of a device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| deviceId | string | Yes | Address of the remote device.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let panProfile = pan.createPanProfile(); + panProfile.disconnect('XX:XX:XX:XX:XX:XX'); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### setTethering + +setTethering(enable: boolean): void + +Sets Bluetooth tethering, which shares a mobile connection. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| value | boolean | Yes | Whether to set tethering over a Bluetooth PAN.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +try { + let panProfile = pan.createPanProfile(); + panProfile.setTethering(false); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +### isTetheringOn + +isTetheringOn(): boolean + +Checks whether Bluetooth tethering is activated. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------- | +| boolean | Returns **true** if tethering is available over a Bluetooth PAN; returns **false** otherwise.| + +**Example** + +```js +try { + let panProfile = pan.createPanProfile(); + let ret = panProfile.isTetheringOn(); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-socket.md b/en/application-dev/reference/apis/js-apis-bluetooth-socket.md new file mode 100644 index 0000000000000000000000000000000000000000..8ec8977df385665edc64231cd7aea4b62dafd35e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bluetooth-socket.md @@ -0,0 +1,410 @@ +# @ohos.bluetooth.socket (Bluetooth socket Module) + +The **socket** module provides APIs for operating and managing Bluetooth sockets. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + + +## Modules to Import + +```js +import socket from '@ohos.bluetooth.socket'; +``` + +## socket.sppListen + +sppListen(name: string, options: SppOptions, callback: AsyncCallback<number>): void + +Creates a Serial Port Profile (SPP) listening socket for the server. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------- | +| name | string | Yes | Name of the service. | +| option | [SppOptions](#sppoptions) | Yes | SPP listening configuration. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the server socket ID.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} + +let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; +try { + socket.sppListen('server1', sppOption, serverSocket); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.sppAccept + +sppAccept(serverSocket: number, callback: AsyncCallback<number>): void + +Accepts a connection request from the client over a socket of the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | --------------------------- | ---- | ----------------------- | +| serverSocket | number | Yes | Server socket ID. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the client socket ID.| + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} +let clientNumber = -1; +function acceptClientSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth clientSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the server. + clientNumber = number; + } +} +try { + socket.sppAccept(serverNumber, acceptClientSocket); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.sppConnect + +sppConnect(deviceId: string, options: SppOptions, callback: AsyncCallback<number>): void + +Initiates an SPP connection to a remote device from the client. + +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------ | +| deviceId | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| option | [SppOptions](#sppoptions) | Yes | SSP listensing configuration for the connection. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the client socket ID. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900003 | Bluetooth switch is off. | +|2900004 | Profile is not supported. | +|2900099 | Operation failed. | + +**Example** + +```js + +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +let sppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0}; +try { + socket.sppConnect('XX:XX:XX:XX:XX:XX', sppOption, clientSocket); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.sppCloseServerSocket + +sppCloseServerSocket(socket: number): void + +Closes an SPP listening socket of the server. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| socket | number | Yes | Server socket ID, which is obtained by **sppListen()**. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} +try { + socket.sppCloseServerSocket(serverNumber); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.sppCloseClientSocket + +sppCloseClientSocket(socket: number): void + +Closes an SPP listening socket of the client. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------------- | +| socket | number | Yes | Client socket ID, which is obtained by **sppAccept()** or **sppConnect**(). | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2900001 | Service stopped. | +|2900099 | Operation failed. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +try { + socket.sppCloseClientSocket(clientNumber); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.sppWrite + +sppWrite(clientSocket: number, data: ArrayBuffer): void + +Writes data to the remote device through a socket. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ---- | ------------- | +| clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept()** or **sppConnect**(). | +| data | ArrayBuffer | Yes | Data to write. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2901054 | IO error. | +|2900099 | Operation failed. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +let arrayBuffer = new ArrayBuffer(8); +let data = new Uint8Array(arrayBuffer); +data[0] = 123; +try { + socket.sppWrite(clientNumber, arrayBuffer); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.on('sppRead') + +on(type: 'sppRead', clientSocket: number, callback: Callback<ArrayBuffer>): void + +Subscribes to SPP read request events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | --------------------------- | ---- | -------------------------- | +| type | string | Yes | Event type. The value is **sppRead**, which indicates an SPP read request event. | +| clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept()** or **sppConnect()**. | +| callback | Callback<ArrayBuffer> | Yes | Callback invoked to return the data read. | + +**Error codes** + +For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). + +| ID| Error Message| +| -------- | ---------------------------- | +|2901054 | IO error. | +|2900099 | Operation failed. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +function dataRead(dataBuffer) { + let data = new Uint8Array(dataBuffer); + console.log('bluetooth data is: ' + data[0]); +} +try { + socket.on('sppRead', clientNumber, dataRead); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## socket.off('sppRead') + +off(type: 'sppRead', clientSocket: number, callback?: Callback<ArrayBuffer>): void + +Unsubscribes from SPP read request events. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | --------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **sppRead**, which indicates an SPP read request event. | +| clientSocket | number | Yes | Client socket ID, which is obtained by **sppAccept()** or **sppConnect()**. | +| callback | Callback<ArrayBuffer> | No | Callback for the SPP read request event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**. | + +**Example** + +```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} +try { + socket.off('sppRead', clientNumber); +} catch (err) { + console.error('errCode: ' + err.code + ', errMessage: ' + err.message); +} +``` + + +## SppOptions + +Defines the SPP configuration. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| ------ | ------------------- | ---- | ---- | ----------- | +| uuid | string | Yes | Yes | UUID of the SPP.| +| secure | boolean | Yes | Yes | Whether it is a secure channel. | +| type | [SppType](#SppType) | Yes | Yes | Type of the SPP link. | + + +## SppType + +Enumerates the SPP link types. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Value | Description | +| ---------- | ---- | ------------- | +| SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index f22961f16809055e3ab560afb78750e42030aec3..7bd21aac353ac966f7d8f3b96c1b5ef8783dcfe8 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -3,9 +3,8 @@ The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. > **NOTE** -> -> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [bluetoothManager](js-apis-bluetoothManager.md). +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [bluetoothManager](js-apis-bluetoothManager.md). @@ -215,7 +214,7 @@ let result = bluetooth.pairDevice("XX:XX:XX:XX:XX:XX"); getProfileConnState(profileId: ProfileId): ProfileConnectionState -Obtains the connection status of a specified profile. +Obtains the connection status of the specified profile. > **NOTE** > This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.getProfileConnectionState](js-apis-bluetoothManager.md#bluetoothmanagergetprofileconnectionstate). @@ -664,7 +663,7 @@ bluetooth.off('pinRequired', onReceiveEvent); on(type: "bondStateChange", callback: Callback<BondStateParam>): void -Subscribes to the Bluetooth pairing state change events. +Subscribes to the Bluetooth pairing state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('bondStateChange')](js-apis-bluetoothManager.md#bluetoothmanageronbondstatechange). @@ -698,7 +697,7 @@ bluetooth.on('bondStateChange', onReceiveEvent); off(type: "bondStateChange", callback?: Callback<BondStateParam>): void -Unsubscribes from the Bluetooth pairing state change events. +Unsubscribes from the Bluetooth pairing state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('bondStateChange')](js-apis-bluetoothManager.md#bluetoothmanageroffbondstatechange). @@ -733,7 +732,7 @@ bluetooth.off('bondStateChange', onReceiveEvent); on(type: "stateChange", callback: Callback<BluetoothState>): void -Subscribes to the Bluetooth connection state change events. +Subscribes to the Bluetooth connection state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.on('stateChange')](js-apis-bluetoothManager.md#bluetoothmanageronstatechange). @@ -767,7 +766,7 @@ bluetooth.on('stateChange', onReceiveEvent); off(type: "stateChange", callback?: Callback<BluetoothState>): void -Unsubscribes from the Bluetooth connection state change events. +Unsubscribes from the Bluetooth connection state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.off('stateChange')](js-apis-bluetoothManager.md#bluetoothmanageroffstatechange). @@ -1145,7 +1144,7 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ## bluetooth.BLE -### bluetooth.BLE.createGattServer(deprecated) +### createGattServer(deprecated) createGattServer(): GattServer @@ -1169,7 +1168,7 @@ let gattServer = bluetooth.BLE.createGattServer(); ``` -### bluetooth.BLE.createGattClientDevice(deprecated) +### createGattClientDevice(deprecated) createGattClientDevice(deviceId: string): GattClientDevice @@ -1199,7 +1198,7 @@ let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); ``` -### bluetooth.BLE.getConnectedBLEDevices(deprecated) +### getConnectedBLEDevices(deprecated) getConnectedBLEDevices(): Array<string> @@ -1225,7 +1224,7 @@ let result = bluetooth.BLE.getConnectedBLEDevices(); ``` -### bluetooth.BLE.startBLEScan(deprecated) +### startBLEScan(deprecated) startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void @@ -1271,7 +1270,7 @@ bluetooth.BLE.startBLEScan( ``` -### bluetooth.BLE.stopBLEScan(deprecated) +### stopBLEScan(deprecated) stopBLEScan(): void @@ -1295,7 +1294,7 @@ bluetooth.BLE.stopBLEScan(); ``` -### bluetooth.BLE.on('BLEDeviceFind')(deprecated) +### on('BLEDeviceFind')(deprecated) on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void @@ -1329,7 +1328,7 @@ bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent); ``` -### bluetooth.BLE.off('BLEDeviceFind')(deprecated) +### off('BLEDeviceFind')(deprecated) off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void @@ -1502,7 +1501,7 @@ let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the A2DP connection state change events. +Subscribes to the A2DP connection state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.on('connectionStateChange')](js-apis-bluetoothManager.md#onconnectionstatechange). @@ -1535,7 +1534,7 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent); off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the A2DP connection state change events. +Unsubscribes from the A2DP connection state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.A2dpSourceProfile.off('connectionStateChange')](js-apis-bluetoothManager.md#offconnectionstatechange). @@ -1673,7 +1672,7 @@ let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the HFP connection state change events. +Subscribes to the HFP connection state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.HandsFreeAudioGatewayProfile.on('connectionStateChange')](js-apis-bluetoothManager.md#onconnectionstatechange-1). @@ -1707,7 +1706,7 @@ hfpAg.on('connectionStateChange', onReceiveEvent); off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the HFP connection state change events. +Unsubscribes from the HFP connection state changes. > **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [bluetoothManager.HandsFreeAudioGatewayProfile.off('connectionStateChange')](js-apis-bluetoothManager.md#offconnectionstatechange-1). @@ -2394,7 +2393,7 @@ gattServer.off("descriptorWrite"); on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void -Subscribes to the BLE connection state change events. +Subscribes to the BLE connection state changes. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.on('connectStateChange')](js-apis-bluetoothManager.md#onconnectstatechange). @@ -2431,7 +2430,7 @@ gattServer.on("connectStateChange", Connected); off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void -Unsubscribes from the BLE connection state change events. +Unsubscribes from the BLE connection state changes. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattServer.off('connectStateChange')](js-apis-bluetoothManager.md#offconnectstatechange). @@ -2995,7 +2994,7 @@ device.setNotifyCharacteristicChanged(characteristic, false); on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void -Subscribes to the BLE characteristic change events. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. +Subscribes to the BLE characteristic changes. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.on('BLECharacteristicChange')](js-apis-bluetoothManager.md#onblecharacteristicchange). @@ -3032,7 +3031,7 @@ device.on('BLECharacteristicChange', CharacteristicChange); off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void -Unsubscribes from the BLE characteristic change events. +Unsubscribes from the BLE characteristic changes. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.off('BLECharacteristicChange')](js-apis-bluetoothManager.md#offblecharacteristicchange). @@ -3064,7 +3063,7 @@ device.off('BLECharacteristicChange'); on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void -Subscribes to the BLE connection state change events. +Subscribes to the BLE connection state changes. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.on('BLEConnectionStateChange')](js-apis-bluetoothManager.md#onbleconnectionstatechange). @@ -3100,7 +3099,7 @@ device.on('BLEConnectionStateChange', ConnectStateChanged); off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void -Unsubscribes from the BLE connection state change events. +Unsubscribes from the BLE connection state changes. > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [bluetoothManager.GattClientDevice.off('BLEConnectionStateChange')](js-apis-bluetoothManager.md#offbleconnectionstatechange). diff --git a/en/application-dev/reference/apis/js-apis-bluetoothManager.md b/en/application-dev/reference/apis/js-apis-bluetoothManager.md index cbbbfe87b558ec6a9c43d7e70ebd513c1454c1f9..b6b353fee524e2abef7c3f74bcb6d4993571a920 100644 --- a/en/application-dev/reference/apis/js-apis-bluetoothManager.md +++ b/en/application-dev/reference/apis/js-apis-bluetoothManager.md @@ -15,12 +15,15 @@ import bluetoothManager from '@ohos.bluetoothManager'; ``` -## bluetoothManager.enableBluetooth +## bluetoothManager.enableBluetooth(deprecated) enableBluetooth(): void Enables Bluetooth. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [access.enableBluetooth](js-apis-bluetooth-access.md#accessenablebluetooth). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -45,12 +48,15 @@ try { ``` -## bluetoothManager.disableBluetooth +## bluetoothManager.disableBluetooth(deprecated) disableBluetooth(): void Disables Bluetooth. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [access.disableBluetooth](js-apis-bluetooth-access.md#accessdisablebluetooth). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -75,12 +81,15 @@ try { ``` -## bluetoothManager.getLocalName +## bluetoothManager.getLocalName(deprecated) getLocalName(): string Obtains the name of the local Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getLocalName](js-apis-bluetooth-connection.md#connectiongetlocalname). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -111,12 +120,15 @@ try { ``` -## bluetoothManager.getState +## bluetoothManager.getState(deprecated) getState(): BluetoothState Obtains the Bluetooth state. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [access.getState](js-apis-bluetooth-access.md#accessgetstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -147,12 +159,15 @@ try { ``` -## bluetoothManager.getBtConnectionState +## bluetoothManager.getBtConnectionState(deprecated) getBtConnectionState(): ProfileConnectionState Obtains the local profile connection status. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getProfileConnectionState](js-apis-bluetooth-connection.md#connectiongetprofileconnectionstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -184,12 +199,15 @@ try { ``` -## bluetoothManager.setLocalName +## bluetoothManager.setLocalName(deprecated) setLocalName(name: string): void Sets the name of the local Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.setLocalName](js-apis-bluetooth-connection.md#connectionsetlocalname). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -221,12 +239,15 @@ try { ``` -## bluetoothManager.pairDevice +## bluetoothManager.pairDevice(deprecated) pairDevice(deviceId: string): void Initiates Bluetooth pairing. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.pairDevice](js-apis-bluetooth-connection.md#connectionpairdevice). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -259,109 +280,15 @@ try { ``` -## bluetoothManager.pairCredibleDevice10+ - -pairCredibleDevice(deviceId: string, transport: BluetoothTransport, callback: AsyncCallback<void>): void - -Pairs a trusted remote device whose address is obtained in a non-Bluetooth scan mode (such as using NFC). - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | ----------------------------------- | -| deviceId | string | Yes | Address of the remote device to pair, for example, XX:XX:XX:XX:XX:XX.| -| transport | [BluetoothTransport](#bluetoothtransport10) | Yes | Device type, for example, a classic Bluetooth device or a Bluetooth low energy (BLE) device.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | - -**Error codes** - -For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). - -| ID| Error Message| -| -------- | ---------------------------- | -|2900001 | Service stopped. | -|2900003 | Bluetooth switch is off. | -|2900099 | Operation failed. | - -**Example** - -```js -try { - bluetoothManager.pairCredibleDevice("68:13:24:79:4C:8C", 1, err => { - if (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - return; - } - console.info("pairCredibleDevice,err:" + JSON.stringify(err)); - }); -} catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); -} -``` - - -## bluetoothManager.pairCredibleDevice10+ - -pairCredibleDevice(deviceId: string, transport: BluetoothTransport): Promise<void> - -Pairs a trusted remote device whose address is obtained in a non-Bluetooth scan mode (such as using NFC). - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | ----------------------------------- | -| deviceId | string | Yes | Address of the remote device to pair, for example, XX:XX:XX:XX:XX:XX.| -| transport | [BluetoothTransport](#bluetoothtransport10) | Yes | Device type, for example, a classic Bluetooth device or a BLE device.| - -**Return value** - -| Type | Description | -| ------------------------------------------------- | ------------------- | -| Promise<void> | Promise used to return the result.| - -**Error codes** - -For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). - -| ID| Error Message| -| -------- | ---------------------------- | -|2900001 | Service stopped. | -|2900003 | Bluetooth switch is off. | -|2900099 | Operation failed. | - -**Example** - -```js -try { - bluetoothManager.pairCredibleDevice("68:13:24:79:4C:8C", 0).then(() => { - console.info("PairCredibleDevice"); - }, err => { - console.error("PairCredibleDevice:errCode" + err.code + ",errMessage:" + err.message); - }); -} catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); -} -``` - - -## bluetoothManager.getProfileConnectionState +## bluetoothManager.getProfileConnectionState(deprecated) getProfileConnectionState(profileId: ProfileId): ProfileConnectionState Obtains the connection status of the specified profile. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getProfileConnectionState](js-apis-bluetooth-connection.md#connectiongetprofileconnectionstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -400,12 +327,15 @@ try { ``` -## bluetoothManager.cancelPairedDevice +## bluetoothManager.cancelPairedDevice(deprecated) cancelPairedDevice(deviceId: string): void Cancels a paired remote device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.cancelPairedDevice](js-apis-bluetooth-connection.md#connectioncancelpaireddevice). + **System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -439,12 +369,15 @@ try { ``` -## bluetoothManager.getRemoteDeviceName +## bluetoothManager.getRemoteDeviceName(deprecated) getRemoteDeviceName(deviceId: string): string Obtains the name of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getRemoteDeviceName](js-apis-bluetooth-connection.md#connectiongetremotedevicename). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -482,12 +415,15 @@ try { ``` -## bluetoothManager.getRemoteDeviceClass +## bluetoothManager.getRemoteDeviceClass(deprecated) getRemoteDeviceClass(deviceId: string): DeviceClass Obtains the class of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getRemoteDeviceClass](js-apis-bluetooth-connection.md#connectiongetremotedeviceclass). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -525,12 +461,15 @@ try { ``` -## bluetoothManager.getPairedDevices +## bluetoothManager.getPairedDevices(deprecated) getPairedDevices(): Array<string> Obtains the paired devices. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getPairedDevices](js-apis-bluetooth-connection.md#connectiongetpaireddevices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -562,12 +501,15 @@ try { ``` -## bluetoothManager.setBluetoothScanMode +## bluetoothManager.setBluetoothScanMode(deprecated) setBluetoothScanMode(mode: ScanMode, duration: number): void Sets the Bluetooth scan mode so that the device can be discovered by a remote device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.setBluetoothScanMode](js-apis-bluetooth-connection.md#connectionsetbluetoothscanmode). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -601,12 +543,15 @@ try { ``` -## bluetoothManager.getBluetoothScanMode +## bluetoothManager.getBluetoothScanMode(deprecated) getBluetoothScanMode(): ScanMode Obtains the Bluetooth scan mode. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.getBluetoothScanMode](js-apis-bluetooth-connection.md#connectiongetbluetoothscanmode). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -638,12 +583,15 @@ try { ``` -## bluetoothManager.startBluetoothDiscovery +## bluetoothManager.startBluetoothDiscovery(deprecated) startBluetoothDiscovery(): void Starts Bluetooth scan to discover remote devices. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.startBluetoothDiscovery](js-apis-bluetooth-connection.md#connectionstartbluetoothdiscovery). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -674,12 +622,15 @@ try { ``` -## bluetoothManager.stopBluetoothDiscovery +## bluetoothManager.stopBluetoothDiscovery(deprecated) stopBluetoothDiscovery(): void Stops Bluetooth scan. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.stopBluetoothDiscovery](js-apis-bluetooth-connection.md#connectionstopbluetoothdiscovery). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -705,12 +656,15 @@ try { ``` -## bluetoothManager.setDevicePairingConfirmation +## bluetoothManager.setDevicePairingConfirmation(deprecated) setDevicePairingConfirmation(device: string, accept: boolean): void Sets the device pairing confirmation. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.setDevicePairingConfirmation](js-apis-bluetooth-connection.md#connectionsetdevicepairingconfirmation). + **Required permissions**: ohos.permission.MANAGE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -749,104 +703,15 @@ try { ``` -## bluetoothManager.setDevicePinCode10+ - -setDevicePinCode(device: string, code: string, callback: AsyncCallback<void>): void - -Sets the PIN for the device when [PinType](#pintype10) is **PIN_TYPE_ENTER_PIN_CODE** or **PIN_TYPE_PIN_16_DIGITS**. - -**Required permissions**: ohos.permission.MANAGE_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------- | ---- | -------------------------------- | -| device | string | Yes | MAC address of the remote device, for example, XX:XX:XX:XX:XX:XX.| -| code | string | Yes | PIN to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | - -**Error codes** - -For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). - -| ID| Error Message| -| -------- | ---------------------------- | -|2900001 | Service stopped. | -|2900003 | Bluetooth switch is off. | -|2900099 | Operation failed. | - -**Example** - -```js -//callback -try { - bluetoothManager.setDevicePinCode('11:22:33:44:55:66', '12345', (err, data) => { - console.info('setDevicePinCode,device name err:' + JSON.stringify(err) + ',device name:' + JSON.stringify(data)); - }); -} catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); -} -``` - - -## bluetoothManager.setDevicePinCode10+ - -setDevicePinCode(device: string, code: string): Promise<void> - -Sets the PIN for the device when [PinType](#pintype10) is **PIN_TYPE_ENTER_PIN_CODE** or **PIN_TYPE_PIN_16_DIGITS**. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.MANAGE_BLUETOOTH - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------- | ---- | -------------------------------- | -| device | string | Yes | MAC address of the remote device, for example, XX:XX:XX:XX:XX:XX.| -| code | string | Yes | PIN to set. | - -**Return value** - -| Type | Description | -| ------------------- | ------------- | -| Promise<void> | Promise used to return the result.| - -**Error codes** - -For details about the error codes, see [Bluetooth Error Codes](../errorcodes/errorcode-bluetoothManager.md). - -| ID| Error Message| -| -------- | ---------------------------- | -|2900001 | Service stopped. | -|2900003 | Bluetooth switch is off. | -|2900099 | Operation failed. | - -**Example** - -```js -//promise -try { - bluetoothManager.setDevicePinCode('11:22:33:44:55:66', '12345').then(() => { - console.info('setDevicePinCode'); - }, error => { - console.info('setDevicePinCode: errCode:' + error.code + ',errMessage' + error.message); - }) - -} catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); -} -``` - - -## bluetoothManager.on('bluetoothDeviceFind') +## bluetoothManager.on('bluetoothDeviceFind')(deprecated) on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void Subscribes to the Bluetooth device discovery events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.on('bluetoothDeviceFind')](js-apis-bluetooth-connection.md#connectiononbluetoothdevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -880,12 +745,15 @@ try { ``` -## bluetoothManager.off('bluetoothDeviceFind') +## bluetoothManager.off('bluetoothDeviceFind')(deprecated) off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void Unsubscribes from the Bluetooth device discovery events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.off('bluetoothDeviceFind')](js-apis-bluetooth-connection.md#connectionoffbluetoothdevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -920,12 +788,15 @@ try { ``` -## bluetoothManager.on('pinRequired') +## bluetoothManager.on('pinRequired')(deprecated) on(type: "pinRequired", callback: Callback<PinRequiredParam>): void Subscribes to the pairing request events of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.on('pinRequired')](js-apis-bluetooth-connection.md#connectiononpinrequired). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -959,12 +830,15 @@ try { ``` -## bluetoothManager.off('pinRequired') +## bluetoothManager.off('pinRequired')(deprecated) off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void Unsubscribes from the pairing request events of the remote Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.off('pinRequired')](js-apis-bluetooth-connection.md#connectionoffpinrequired). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -999,11 +873,14 @@ try { ``` -## bluetoothManager.on('bondStateChange') +## bluetoothManager.on('bondStateChange')(deprecated) on(type: "bondStateChange", callback: Callback<BondStateParam>): void -Subscribes to the Bluetooth pairing state change events. +Subscribes to the Bluetooth pairing state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.on('bondStateChange')](js-apis-bluetooth-connection.md#connectiononbondstatechange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -1038,11 +915,14 @@ try { ``` -## bluetoothManager.off('bondStateChange') +## bluetoothManager.off('bondStateChange')(deprecated) off(type: "bondStateChange", callback?: Callback<BondStateParam>): void -Unsubscribes from the Bluetooth pairing state change events. +Unsubscribes from the Bluetooth pairing state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.off('bondStateChange')](js-apis-bluetooth-connection.md#connectionoffbondstatechange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -1078,12 +958,15 @@ try { ``` -## bluetoothManager.on('stateChange') +## bluetoothManager.on('stateChange')(deprecated) on(type: "stateChange", callback: Callback<BluetoothState>): void Subscribes to Bluetooth state events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [access.on('stateChange')](js-apis-bluetooth-access.md#accessonstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1117,12 +1000,15 @@ try { ``` -## bluetoothManager.off('stateChange') +## bluetoothManager.off('stateChange')(deprecated) off(type: "stateChange", callback?: Callback<BluetoothState>): void Unsubscribes from Bluetooth state events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [access.off('stateChange')](js-apis-bluetooth-access.md#accessoffstatechange). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1157,12 +1043,15 @@ try { ``` -## bluetoothManager.sppListen +## bluetoothManager.sppListen(deprecated) sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void Creates a server listening socket. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.sppListen](js-apis-bluetooth-socket.md#socketspplisten). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1207,12 +1096,15 @@ try { ``` -## bluetoothManager.sppAccept +## bluetoothManager.sppAccept(deprecated) sppAccept(serverSocket: number, callback: AsyncCallback<number>): void Listens for a connection to be made to this socket from the client and accepts it. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.sppAccept](js-apis-bluetooth-socket.md#socketsppaccept). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1261,12 +1153,15 @@ try { ``` -## bluetoothManager.sppConnect +## bluetoothManager.sppConnect(deprecated) sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void Initiates an SPP connection to a remote device from the client. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.sppConnect](js-apis-bluetooth-socket.md#socketsppconnect). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1312,12 +1207,15 @@ try { ``` -## bluetoothManager.sppCloseServerSocket +## bluetoothManager.sppCloseServerSocket(deprecated) sppCloseServerSocket(socket: number): void Closes the listening socket of the server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.sppCloseServerSocket](js-apis-bluetooth-socket.md#socketsppcloseserversocket). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1354,12 +1252,15 @@ try { ``` -## bluetoothManager.sppCloseClientSocket +## bluetoothManager.sppCloseClientSocket(deprecated) sppCloseClientSocket(socket: number): void Closes the client socket. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.sppCloseClientSocket](js-apis-bluetooth-socket.md#socketsppcloseclientsocket). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1398,12 +1299,15 @@ try { ``` -## bluetoothManager.sppWrite +## bluetoothManager.sppWrite(deprecated) sppWrite(clientSocket: number, data: ArrayBuffer): void Writes data to the remote device through the socket. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.sppWrite](js-apis-bluetooth-socket.md#socketsppwrite). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1445,12 +1349,15 @@ try { ``` -## bluetoothManager.on('sppRead') +## bluetoothManager.on('sppRead')(deprecated) on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void Subscribes to the SPP read request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.on('sppRead')](js-apis-bluetooth-socket.md#socketonsppread). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1494,12 +1401,15 @@ try { ``` -## bluetoothManager.off('sppRead') +## bluetoothManager.off('sppRead')(deprecated) off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void Unsubscribes from the SPP read request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.off('sppRead')](js-apis-bluetooth-socket.md#socketoffsppread). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1529,7 +1439,7 @@ try { } ``` -## bluetoothManager.getProfileInstance +## bluetoothManager.getProfileInstance(deprecated) getProfileInstance(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile @@ -1562,12 +1472,15 @@ try { ## bluetoothManager.BLE -### bluetoothManager.BLE.createGattServer +### createGattServer(deprecated) createGattServer(): GattServer Creates a **GattServer** instance. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.createGattServer](js-apis-bluetooth-ble.md#blecreategattserver). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Return value** @@ -1583,12 +1496,15 @@ let gattServer = bluetoothManager.BLE.createGattServer(); ``` -### bluetoothManager.BLE.createGattClientDevice +### createGattClientDevice(deprecated) createGattClientDevice(deviceId: string): GattClientDevice Creates a **GattClientDevice** instance. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.createGattClientDevice](js-apis-bluetooth-ble.md#blecreategattclientdevice). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1614,12 +1530,15 @@ try { ``` -### bluetoothManager.BLE.getConnectedBLEDevices +### getConnectedBLEDevices(deprecated) getConnectedBLEDevices(): Array<string> Obtains the BLE devices connected to this device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.getConnectedBLEDevices](js-apis-bluetooth-ble.md#blegetconnectedbledevices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1651,12 +1570,15 @@ try { ``` -### bluetoothManager.BLE.startBLEScan +### startBLEScan(deprecated) startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void Starts a BLE scan. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.startBLEScan](js-apis-bluetooth-ble.md#blestartblescan). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH, ohos.permission.MANAGE_BLUETOOTH, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1704,12 +1626,15 @@ try { ``` -### bluetoothManager.BLE.stopBLEScan +### stopBLEScan(deprecated) stopBLEScan(): void Stops the BLE scan. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.startBLEScan](js-apis-bluetooth-ble.md#blestopblescan). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1735,12 +1660,15 @@ try { ``` -### bluetoothManager.BLE.on('BLEDeviceFind') +### on('BLEDeviceFind')(deprecated) on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void Subscribe to the BLE device discovery events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.on('BLEDeviceFind')](js-apis-bluetooth-ble.md#bleonbledevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1774,12 +1702,15 @@ try { ``` -### bluetoothManager.BLE.off('BLEDeviceFind') +### off('BLEDeviceFind')(deprecated) off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void Unsubscribes from the BLE device discovery events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.off('BLEDeviceFind')](js-apis-bluetooth-ble.md#bleoffbledevicefind). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1819,12 +1750,15 @@ try { Provides the profile base class. -### getConnectionDevices +### getConnectionDevices(deprecated) getConnectionDevices(): Array<string> Obtains the connected devices. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.getConnectedDevices](js-apis-bluetooth-baseProfile.md#baseprofilegetconnecteddevices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1857,12 +1791,15 @@ try { } ``` -### getDeviceState +### getDeviceState(deprecated) getDeviceState(device: string): ProfileConnectionState Obtains the connection state of the profile. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.getConnectionState](js-apis-bluetooth-baseProfile.md#baseprofilegetconnectionstate). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1901,17 +1838,24 @@ try { } ``` + ## A2dpSourceProfile Before using an API of **A2dpSourceProfile**, you need to create an instance of this class by using **getProfile()**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [a2dp.A2dpSourceProfile](js-apis-bluetooth-a2dp.md#a2dpsourceprofile). -### connect + +### connect(deprecated) connect(device: string): void Sets up an Advanced Audio Distribution Profile (A2DP) connection. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [a2dp.A2dpSourceProfile#connect](js-apis-bluetooth-a2dp.md#connect). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1945,12 +1889,15 @@ try { ``` -### disconnect +### disconnect(deprecated) disconnect(device: string): void Disconnects an A2DP connection. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [a2dp.A2dpSourceProfile#disconnect](js-apis-bluetooth-a2dp.md#disconnect). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1984,11 +1931,14 @@ try { ``` -### on('connectionStateChange') +### on('connectionStateChange')(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the A2DP connection state change events. +Subscribes to the A2DP connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.on('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileonconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1996,7 +1946,7 @@ Subscribes to the A2DP connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates an A2DP connection state change event.| +| type | string | Yes | Event type. The value **connectionStateChange** indicates a A2DP connection state change event.| | callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the A2DP connection state change event. | **Return value** @@ -2014,11 +1964,14 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange') +### off('connectionStateChange')(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the A2DP connection state change events. +Unsubscribes from the A2DP connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.off('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileoffconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2026,7 +1979,7 @@ Unsubscribes from the A2DP connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates an A2DP connection state change event.| +| type | string | Yes | Event type. The value **connectionStateChange** indicates a A2DP connection state change event.| | callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the A2DP connection state change event. | **Return value** @@ -2045,12 +1998,15 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` -### getPlayingState +### getPlayingState(deprecated) getPlayingState(device: string): PlayingState Obtains the playing state of a device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [a2dp.A2dpSourceProfile#getPlayingState](js-apis-bluetooth-a2dp.md#getPlayingState). + **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -2088,10 +2044,13 @@ try { ``` -## HandsFreeAudioGatewayProfile +## HandsFreeAudioGatewayProfile(deprecated) Before using an API of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using **getProfile()**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [hfp.HandsFreeAudioGatewayProfile](js-apis-bluetooth-hfp.md#HandsFreeAudioGatewayProfile). + ### connect @@ -2099,6 +2058,9 @@ connect(device: string): void Sets up a Hands-free Profile (HFP) connection of a device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [hfp.HandsFreeAudioGatewayProfile#connect](js-apis-bluetooth-hfp.md#connect). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2132,12 +2094,15 @@ try { ``` -### disconnect +### disconnect(deprecated) disconnect(device: string): void Disconnects the HFP connection of a device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [hfp.HandsFreeAudioGatewayProfile#disconnect](js-apis-bluetooth-hfp.md#disconnect). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2171,11 +2136,14 @@ try { ``` -### on('connectionStateChange') +### on('connectionStateChange')(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the HFP connection state change events. +Subscribes to the HFP connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.on('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileonconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2183,7 +2151,7 @@ Subscribes to the HFP connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event. | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event.| | callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the HFP connection state change event. | **Example** @@ -2198,11 +2166,14 @@ hfpAg.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange') +### off('connectionStateChange')(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the HFP connection state change events. +Unsubscribes from the HFP connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.off('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileoffconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2210,7 +2181,7 @@ Unsubscribes from the HFP connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event. | +| type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event.| | callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the HFP connection state change event. | **Example** @@ -2226,7 +2197,7 @@ hfpAg.off('connectionStateChange', onReceiveEvent); ``` -## HidHostProfile +## HidHostProfile(deprecated) Before using an API of **HidHostProfile**, you need to create an instance of this class by using **getProfile()**. @@ -2237,6 +2208,9 @@ connect(device: string): void Connects to the HidHost service of a device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [hid.HidHostProfile#connect](js-apis-bluetooth-hid.md#connect). + **System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -2272,12 +2246,15 @@ try { ``` -### disconnect +### disconnect(deprecated) disconnect(device: string): void Disconnects from the HidHost service of a device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [hid.HidHostProfile#disconnect](js-apis-bluetooth-hid.md#disconnect). + **System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -2313,11 +2290,14 @@ try { ``` -### on('connectionStateChange') +### on('connectionStateChange')(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the HidHost connection state change events. +Subscribes to the HidHost connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.on('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileonconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2339,11 +2319,14 @@ hidHost.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange') +### off('connectionStateChange')(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the HidHost connection state change events. +Unsubscribes from the HidHost connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.off('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileoffconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2370,13 +2353,19 @@ hidHost.off('connectionStateChange', onReceiveEvent); Before using an API of **PanProfile**, you need to create an instance of this class by using **getProfile()**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [pan.PanProfile](js-apis-bluetooth-pan.md#panprofile). -### disconnect + +### disconnect(deprecated) disconnect(device: string): void Disconnects from the Personal Area Network (PAN) service of a device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [pan.PanProfile#disconnect](js-apis-bluetooth-pan.md#disconnect). + **System API**: This is a system API. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2412,11 +2401,14 @@ try { ``` -### on('connectionStateChange') +### on('connectionStateChange')(deprecated) on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the PAN connection state change events. +Subscribes to the PAN connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.on('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileonconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2424,8 +2416,8 @@ Subscribes to the PAN connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event. | -| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the PAN connection state change event. | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the PAN connection state change event. | **Example** @@ -2438,11 +2430,14 @@ panProfile.on('connectionStateChange', onReceiveEvent); ``` -### off('connectionStateChange') +### off('connectionStateChange')(deprecated) off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the PAN connection state change events. +Unsubscribes from the PAN connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.off('connectionStateChange')](js-apis-bluetooth-baseProfile.md#baseprofileoffconnectionstatechange). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2450,8 +2445,8 @@ Unsubscribes from the PAN connection state change events. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- | -| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event. | -| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the PAN connection state change event. | +| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.| +| callback | Callback<[StateChangeParam](#StateChangeParam)> | No | Callback for the PAN connection state change event. | **Example** @@ -2465,12 +2460,15 @@ panProfile.off('connectionStateChange', onReceiveEvent); ``` -### setTethering +### setTethering(deprecated) setTethering(enable: boolean): void Sets tethering. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [pan.PanProfile#setTethering](js-apis-bluetooth-pan.md#setTethering). + **System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -2506,12 +2504,15 @@ try { ``` -### isTetheringOn +### isTetheringOn(deprecated) isTetheringOn(): boolean Obtains the network sharing status. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [pan.PanProfile#isTetheringOn](js-apis-bluetooth-pan.md#isTetheringOn). + **System API**: This is a system API. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2538,13 +2539,19 @@ try { Implements the Generic Attribute Profile (GATT) server. Before using an API of this class, you need to create a **GattServer** instance using **createGattServer()**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer](js-apis-bluetooth-ble.md#GattServer). + -### startAdvertising +### startAdvertising(deprecated) startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void Starts BLE advertising. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.startAdvertising](js-apis-bluetooth-ble.md#blestartadvertising). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2587,7 +2594,7 @@ let gattServer = bluetoothManager.BLE.createGattServer(); try { gattServer.startAdvertising({ interval:150, - txPower:60, + txPower:0, connectable:true, },{ serviceUuids:["00001888-0000-1000-8000-00805f9b34fb"], @@ -2616,12 +2623,15 @@ try { ``` -### stopAdvertising +### stopAdvertising(deprecated) stopAdvertising(): void Stops BLE advertising. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.stopAdvertising](js-apis-bluetooth-ble.md#blestopadvertising). + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2648,12 +2658,15 @@ try { ``` -### addService +### addService(deprecated) addService(service: GattService): void Adds a service to this GATT server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#addService](js-apis-bluetooth-ble.md#addservice). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2710,12 +2723,15 @@ try { ``` -### removeService +### removeService(deprecated) removeService(serviceUuid: string): void Removes a service from this GATT server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#removeService](js-apis-bluetooth-ble.md#removeservice). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2749,12 +2765,15 @@ try { ``` -### close +### close(deprecated) close(): void Closes this GATT server to unregister it from the protocol stack. After this method is called, this [GattServer](#gattserver) cannot be used. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#close](js-apis-bluetooth-ble.md#close). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2781,12 +2800,15 @@ try { ``` -### notifyCharacteristicChanged +### notifyCharacteristicChanged(deprecated) notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): void Notifies the connected client device when a characteristic value changes. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#notifyCharacteristicChanged](js-apis-bluetooth-ble.md#notifycharacteristicchanged). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2834,12 +2856,15 @@ try { ``` -### sendResponse +### sendResponse(deprecated) sendResponse(serverResponse: ServerResponse): void Sends a response to a read or write request from the GATT client. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#sendResponse](js-apis-bluetooth-ble.md#sendresponse). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2884,12 +2909,15 @@ try { ``` -### on('characteristicRead') +### on('characteristicRead')(deprecated) on(type: "characteristicRead", callback: Callback<CharacteristicReadRequest>): void Subscribes to the characteristic read request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#on('characteristicRead')](js-apis-bluetooth-ble.md#oncharacteristicread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2927,12 +2955,15 @@ gattServer.on("characteristicRead", ReadCharacteristicReq); ``` -### off('characteristicRead') +### off('characteristicRead')(deprecated) off(type: "characteristicRead", callback?: Callback<CharacteristicReadRequest>): void Unsubscribes from the characteristic read request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#off('characteristicRead')](js-apis-bluetooth-ble.md#offcharacteristicread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2952,12 +2983,15 @@ gattServer.off("characteristicRead"); ``` -### on('characteristicWrite') +### on('characteristicWrite')(deprecated) on(type: "characteristicWrite", callback: Callback<CharacteristicWriteRequest>): void Subscribes to the characteristic write request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#on('characteristicWrite')](js-apis-bluetooth-ble.md#oncharacteristicwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -2998,12 +3032,15 @@ gattServer.on("characteristicWrite", WriteCharacteristicReq); ``` -### off('characteristicWrite') +### off('characteristicWrite')(deprecated) off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteRequest>): void Unsubscribes from the characteristic write request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#off('characteristicWrite')](js-apis-bluetooth-ble.md#offcharacteristicwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3023,12 +3060,15 @@ gattServer.off("characteristicWrite"); ``` -### on('descriptorRead') +### on('descriptorRead')(deprecated) on(type: "descriptorRead", callback: Callback<DescriptorReadRequest>): void Subscribes to the descriptor read request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#on('descriptorRead')](js-apis-bluetooth-ble.md#ondescriptorread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3038,7 +3078,7 @@ Subscribes to the descriptor read request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| -| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | +| callback | Callback<[DescriptorReadRequest](#descriptorreadrequest)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | **Example** @@ -3066,12 +3106,15 @@ gattServer.on("descriptorRead", ReadDescriptorReq); ``` -### off('descriptorRead') +### off('descriptorRead')(deprecated) off(type: "descriptorRead", callback?: Callback<DescriptorReadRequest>): void Unsubscribes from the descriptor read request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#off('descriptorRead')](js-apis-bluetooth-ble.md#offdescriptorread). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3091,12 +3134,15 @@ gattServer.off("descriptorRead"); ``` -### on('descriptorWrite') +### on('descriptorWrite')(deprecated) on(type: "descriptorWrite", callback: Callback<DescriptorWriteRequest>): void Subscribes to the descriptor write request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#on('descriptorWrite')](js-apis-bluetooth-ble.md#ondescriptorwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3106,7 +3152,7 @@ Subscribes to the descriptor write request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------- | | type | string | Yes | Event type. The value **descriptorWrite** indicates a descriptor write request event.| -| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | +| callback | Callback<[DescriptorWriteRequest](#descriptorwriterequest)> | Yes | Callback invoked to return a descriptor write request from the GATT client. | **Example** @@ -3137,12 +3183,15 @@ gattServer.on("descriptorRead", WriteDescriptorReq); ``` -### off('descriptorWrite') +### off('descriptorWrite')(deprecated) off(type: "descriptorWrite", callback?: Callback<DescriptorWriteRequest>): void Unsubscribes from the descriptor write request events. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#off('descriptorWrite')](js-apis-bluetooth-ble.md#offdescriptorwrite). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3162,11 +3211,14 @@ gattServer.off("descriptorWrite"); ``` -### on('connectStateChange') +### on('connectStateChange')(deprecated) on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void -Subscribes to the BLE connection state change events. +Subscribes to the BLE connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#on('connectionStateChange')](js-apis-bluetooth-ble.md#onconnectionstatechange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3192,11 +3244,14 @@ gattServer.on("connectStateChange", Connected); ``` -### off('connectStateChange') +### off('connectStateChange')(deprecated) off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void -Unsubscribes from the BLE connection state change events. +Unsubscribes from the BLE connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattServer#off('connectionStateChange')](js-apis-bluetooth-ble.md#offconnectionstatechange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3221,13 +3276,19 @@ gattServer.off("connectStateChange"); Implements the GATT client. Before using an API of this class, you must create a **GattClientDevice** instance using **createGattClientDevice(deviceId: string)**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice](js-apis-bluetooth-ble.md#gattclientdevice). -### connect + +### connect(deprecated) connect(): void Initiates a connection to the remote BLE device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#connect](js-apis-bluetooth-ble.md#connect). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3254,12 +3315,15 @@ try { ``` -### disconnect +### disconnect(deprecated) disconnect(): void Disconnects from the remote BLE device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#disconnect](js-apis-bluetooth-ble.md#disconnect). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3286,12 +3350,15 @@ try { ``` -### close +### close(deprecated) close(): void Closes this GATT client to unregister it from the protocol stack. After this method is called, this [GattClientDevice](#gattclientdevice) instance cannot be used. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#close](js-apis-bluetooth-ble.md#close). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3320,12 +3387,15 @@ try { -### getServices +### getServices(deprecated) getServices(callback: AsyncCallback<Array<GattService>>): void Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#getServices](js-apis-bluetooth-ble.md#getservices). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3371,12 +3441,15 @@ try { ``` -### getServices +### getServices(deprecated) getServices(): Promise<Array<GattService>> Obtains all services of the remote BLE device. This API uses a promise to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#getServices](js-apis-bluetooth-ble.md#getservices-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3412,12 +3485,15 @@ try { ``` -### readCharacteristicValue +### readCharacteristicValue(deprecated) readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#readCharacteristicValue](js-apis-bluetooth-ble.md#readcharacteristicvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3476,12 +3552,15 @@ try { ``` -### readCharacteristicValue +### readCharacteristicValue(deprecated) readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#readCharacteristicValue](js-apis-bluetooth-ble.md#readcharacteristicvalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3536,12 +3615,15 @@ try { ``` -### readDescriptorValue +### readDescriptorValue(deprecated) readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#readDescriptorValue](js-apis-bluetooth-ble.md#readdescriptorvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3593,12 +3675,15 @@ try { ``` -### readDescriptorValue +### readDescriptorValue(deprecated) readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#readDescriptorValue](js-apis-bluetooth-ble.md#readdescriptorvalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3646,12 +3731,15 @@ try { ``` -### writeCharacteristicValue +### writeCharacteristicValue(deprecated) writeCharacteristicValue(characteristic: BLECharacteristic): void Writes a characteristic value to the remote BLE device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#writeCharacteristicValue](js-apis-bluetooth-ble.md#writecharacteristicvalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3699,12 +3787,15 @@ try { ``` -### writeDescriptorValue +### writeDescriptorValue(deprecated) writeDescriptorValue(descriptor: BLEDescriptor): void Writes binary data to the specific descriptor of the remote BLE device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#writeCharacteristicValue](js-apis-bluetooth-ble.md#writecharacteristicvalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3747,12 +3838,15 @@ try { ``` -### setBLEMtuSize +### setBLEMtuSize(deprecated) setBLEMtuSize(mtu: number): void Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling [connect](#connect). +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#setBLEMtuSize](js-apis-bluetooth-ble.md#setBLEMtuSize). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3784,12 +3878,15 @@ try { ``` -### setNotifyCharacteristicChanged +### setNotifyCharacteristicChanged(deprecated) setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): void Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#setCharacteristicChangeNotification](js-apis-bluetooth-ble.md#setcharacteristicchangenotification). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3835,11 +3932,14 @@ try { ``` -### on('BLECharacteristicChange') +### on('BLECharacteristicChange')(deprecated) on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void -Subscribes to the BLE characteristic change events. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. +Subscribes to the BLE characteristic changes. The client can receive a notification from the server only after the **setNotifyCharacteristicChanged** method is called. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#on('BLECharacteristicChange')](js-apis-bluetooth-ble.md#onblecharacteristicchange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3869,11 +3969,14 @@ try { ``` -### off('BLECharacteristicChange') +### off('BLECharacteristicChange')(deprecated) off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void -Unsubscribes from the BLE characteristic change events. +Unsubscribes from the BLE characteristic changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#off('BLECharacteristicChange')](js-apis-bluetooth-ble.md#offblecharacteristicchange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3898,11 +4001,14 @@ try { ``` -### on('BLEConnectionStateChange') +### on('BLEConnectionStateChange')(deprecated) on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void -Subscribes to the BLE connection state change events. +Subscribes to the BLE connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#on('BLEConnectionStateChange')](js-apis-bluetooth-ble.md#onbleconnectionstatechange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3931,11 +4037,14 @@ try { ``` -### off('BLEConnectionStateChange') +### off('BLEConnectionStateChange')(deprecated) off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void -Unsubscribes from the BLE connection state change events. +Unsubscribes from the BLE connection state changes. + +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#off('BLEConnectionStateChange')](js-apis-bluetooth-ble.md#offbleconnectionstatechange). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3960,12 +4069,15 @@ try { ``` -### getDeviceName +### getDeviceName(deprecated) getDeviceName(callback: AsyncCallback<string>): void Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#getDeviceName](js-apis-bluetooth-ble.md#getdevicename). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -4002,12 +4114,15 @@ try { ``` -### getDeviceName +### getDeviceName(deprecated) getDeviceName(): Promise<string> Obtains the name of the remote BLE device. This API uses a promise to return the result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#getDeviceName](js-apis-bluetooth-ble.md#getdevicename-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -4043,12 +4158,15 @@ try { ``` -### getRssiValue +### getRssiValue(deprecated) getRssiValue(callback: AsyncCallback<number>): void Obtains the received signal strength indication (RSSI) of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#getRssiValue](js-apis-bluetooth-ble.md#getrssivalue). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -4084,12 +4202,15 @@ try { ``` -### getRssiValue +### getRssiValue(deprecated) getRssiValue(): Promise<number> Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect). +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattClientDevice#getRssiValue](js-apis-bluetooth-ble.md#getrssivalue-1). + **Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -4122,10 +4243,13 @@ try { } ``` -## ScanMode +## ScanMode(deprecated) Enumerates the scan modes. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.ScanMode](js-apis-bluetooth-connection.md#scanmode). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4137,10 +4261,13 @@ Enumerates the scan modes. | SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | General connectable and discoverable mode.| | SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | Limited connectable and discoverable mode.| -## BondState +## BondState(deprecated) Enumerates the pairing states. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.BondState](js-apis-bluetooth-connection.md#bondstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4150,10 +4277,13 @@ Enumerates the pairing states. | BOND_STATE_BONDED | 2 | Paired. | -## SppOption +## SppOption(deprecated) Defines the SPP configuration parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.SppOption](js-apis-bluetooth-socket.md#sppoptions). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4163,10 +4293,13 @@ Defines the SPP configuration parameters. | type | [SppType](#spptype) | Yes | Yes | Type of the SPP link. | -## SppType +## SppType(deprecated) Enumerates the SPP link types. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [socket.SppType](js-apis-bluetooth-socket.md#spptype). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4174,10 +4307,13 @@ Enumerates the SPP link types. | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| -## GattService +## GattService(deprecated) Defines the GATT service API parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.GattService](js-apis-bluetooth-ble.md#gattservice). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4188,10 +4324,13 @@ Defines the GATT service API parameters. | includeServices | Array<[GattService](#gattservice)> | Yes | Yes | Services on which the service depends. | -## BLECharacteristic +## BLECharacteristic(deprecated) Defines the characteristic API parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.BLECharacteristic](js-apis-bluetooth-ble.md#blecharacteristic). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4200,12 +4339,14 @@ Defines the characteristic API parameters. | characteristicUuid | string | Yes | Yes | UUID of the characteristic, for example, **00002a11-0000-1000-8000-00805f9b34fb**.| | characteristicValue | ArrayBuffer | Yes | Yes | Binary value of the characteristic. | | descriptors | Array<[BLEDescriptor](#bledescriptor)> | Yes | Yes | List of descriptors of the characteristic. | -| properties10+ | [GattProperties](#gattproperties10) | Yes | Yes | Properties of the characteristic. | -## BLEDescriptor +## BLEDescriptor(deprecated) + +Defines the descriptor API parameters. -Defines the BLE descriptor. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.BLEDescriptor](js-apis-bluetooth-ble.md#bledescriptor). **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -4217,10 +4358,13 @@ Defines the BLE descriptor. | descriptorValue | ArrayBuffer | Yes | Yes | Binary value of the descriptor. | -## NotifyCharacteristic +## NotifyCharacteristic(deprecated) Defines the parameters in the notifications sent when the server characteristic value changes. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.NotifyCharacteristic](js-apis-bluetooth-ble.md#notifycharacteristic). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4231,10 +4375,13 @@ Defines the parameters in the notifications sent when the server characteristic | confirm | boolean | Yes | Yes | Whether the notification needs to be confirmed by the remote end. For a notification, set it to **true**. In this case, the remote end must confirm the receipt of the notification. For an indication, set it to **false**. In this case, the remote end does not need to confirm the receipt of the notification.| -## CharacteristicReadRequest +## CharacteristicReadRequest(deprecated) Defines the parameters of the **CharacteristicReadReq** event received by the server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.CharacteristicReadRequest](js-apis-bluetooth-ble.md#characteristicreadrequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4246,10 +4393,13 @@ Defines the parameters of the **CharacteristicReadReq** event received by the se | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## CharacteristicWriteRequest +## CharacteristicWriteRequest(deprecated) Defines the parameters of the **CharacteristicWriteReq** event received by the server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.CharacteristicWriteRequest](js-apis-bluetooth-ble.md#characteristicwriterequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4262,10 +4412,13 @@ Defines the parameters of the **CharacteristicWriteReq** event received by the s | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## DescriptorReadRequest +## DescriptorReadRequest(deprecated) Defines the parameters of the **DescriptorReadReq** event received by the server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.DescriptorReadRequest](js-apis-bluetooth-ble.md#descriptorreadrequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4278,10 +4431,13 @@ Defines the parameters of the **DescriptorReadReq** event received by the server | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## DescriptorWriteRequest +## DescriptorWriteRequest(deprecated) Defines the parameters of the **DescriptorWriteReq** event received by the server. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.DescriptorWriteRequest](js-apis-bluetooth-ble.md#descriptorwriterequest). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4297,10 +4453,13 @@ Defines the parameters of the **DescriptorWriteReq** event received by the serve | serviceUuid | string | Yes | No | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| -## ServerResponse +## ServerResponse(deprecated) Defines the parameters of the server's response to the GATT client's read/write request. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ServerResponse](js-apis-bluetooth-ble.md#serverresponse). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4312,10 +4471,13 @@ Defines the parameters of the server's response to the GATT client's read/write | value | ArrayBuffer | Yes | No | Binary data in the response. | -## BLEConnectChangedState +## BLEConnectChangedState(deprecated) Defines the parameters of **BLEConnectChangedState**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [BLEConnectionChangeState](js-apis-bluetooth-ble.md#bleconnectionchangestate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable| Writable| Description | @@ -4324,10 +4486,13 @@ Defines the parameters of **BLEConnectChangedState**. | state | [ProfileConnectionState](#profileconnectionstate) | Yes | Yes | BLE connection state. | -## ProfileConnectionState +## ProfileConnectionState(deprecated) Enumerates the profile connection states. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [constant.ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4338,10 +4503,13 @@ Enumerates the profile connection states. | STATE_DISCONNECTING | 3 | Disconnecting.| -## ScanFilter +## ScanFilter(deprecated) Defines the scan filter parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ScanFilter](js-apis-bluetooth-ble.md#scanfilter). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable| Writable| Description | @@ -4359,10 +4527,13 @@ Defines the scan filter parameters. | manufactureDataMask | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.| -## ScanOptions +## ScanOptions(deprecated) Defines the scan configuration parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ScanOptions](js-apis-bluetooth-ble.md#scanoptions). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4372,10 +4543,13 @@ Defines the scan configuration parameters. | matchMode | [MatchMode](#matchmode) | Yes | Yes | Hardware filtering match mode. The default value is **MATCH_MODE_AGGRESSIVE**.| -## ScanDuty +## ScanDuty(deprecated) Enumerates the scan duty options. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ScanDuty](js-apis-bluetooth-ble.md#scanduty). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4385,10 +4559,13 @@ Enumerates the scan duty options. | SCAN_MODE_LOW_LATENCY | 2 | Low-latency mode. | -## MatchMode +## MatchMode(deprecated) Enumerates the hardware match modes of BLE scan filters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.MatchMode](js-apis-bluetooth-ble.md#matchmode). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4397,10 +4574,13 @@ Enumerates the hardware match modes of BLE scan filters. | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | -## ScanResult +## ScanResult(deprecated) Defines the scan result. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ScanResult](js-apis-bluetooth-ble.md#scanresult). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4408,13 +4588,15 @@ Defines the scan result. | deviceId | string | Yes | No | Address of the scanned device, for example, XX:XX:XX:XX:XX:XX.| | rssi | number | Yes | No | RSSI of the device. | | data | ArrayBuffer | Yes | No | Advertisement packets sent by the device. | -| deviceName10+ | string | Yes | No | Name of the device detected. | -## BluetoothState +## BluetoothState(deprecated) Enumerates the Bluetooth states. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [access.BluetoothState](js-apis-bluetooth-access.md#bluetoothstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4428,10 +4610,13 @@ Enumerates the Bluetooth states. | STATE_BLE_TURNING_OFF | 6 | The LE-only mode is being turned off for Bluetooth.| -## AdvertiseSetting +## AdvertiseSetting(deprecated) Defines the BLE advertising parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.AdvertiseSetting](js-apis-bluetooth-ble.md#advertisesetting). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4441,10 +4626,13 @@ Defines the BLE advertising parameters. | connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | -## AdvertiseData +## AdvertiseData(deprecated) Defines the content of a BLE advertisement packet. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.AdvertiseData](js-apis-bluetooth-ble.md#advertisedata). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4452,13 +4640,15 @@ Defines the content of a BLE advertisement packet. | serviceUuids | Array<string> | Yes | Yes | List of service UUIDs to broadcast.| | manufactureData | Array<[ManufactureData](#manufacturedata)> | Yes | Yes | List of manufacturers to broadcast. | | serviceData | Array<[ServiceData](#servicedata)> | Yes | Yes | List of service data to broadcast. | -| includeDeviceName10+ | boolean | Yes | Yes | Whether the device name is contained. This parameter is optional. | -## ManufactureData +## ManufactureData(deprecated) Defines the content of a BLE advertisement packet. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ManufactureData](js-apis-bluetooth-ble.md#manufacturedata). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4467,10 +4657,13 @@ Defines the content of a BLE advertisement packet. | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | -## ServiceData +## ServiceData(deprecated) Defines the service data contained in an advertisement packet. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [ble.ServiceData](js-apis-bluetooth-ble.md#servicedata). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4479,23 +4672,28 @@ Defines the service data contained in an advertisement packet. | serviceValue | ArrayBuffer | Yes | Yes | Service data. | -## PinRequiredParam +## PinRequiredParam(deprecated) Defines the pairing request parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.PinRequiredParam](js-apis-bluetooth-connection.md#pinrequiredparam). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ----------- | | deviceId | string | Yes | No | ID of the device to pair.| | pinCode | string | Yes | No | Key for the device pairing. | -| pinType10+ | [PinType](#pintype10) | Yes | No | Type of the device to pair.
This is a system API. | -## BondStateParam +## BondStateParam(deprecated) Defines the pairing state parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.BondStateParam](js-apis-bluetooth-connection.md#bondstateparam). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4504,10 +4702,13 @@ Defines the pairing state parameters. | state | BondState | Yes | No | State of the device.| -## StateChangeParam +## StateChangeParam(deprecated) Defines the profile state change parameters. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [baseProfile.StateChangeParam](js-apis-bluetooth-baseProfile.md#statechangeparam). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable| Writable| Description | @@ -4516,25 +4717,13 @@ Defines the profile state change parameters. | state | [ProfileConnectionState](#profileconnectionstate) | Yes | No | Profile connection state of the device.| -## GattProperties10+ - -Defines the properties of a GATT characteristic. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -| Name | Type | Mandatory | Description | -| -------- | ------ |---- | ----------- | -| write10+ | boolean | Yes | Permits writes of the characteristic value (with a response).| -| writeNoResponse10+ | boolean | Yes | Permits writes of the characteristic value (without a response).| -| read10+ | boolean | Yes | Permits reads of the characteristic value.| -| notify10+ | boolean | Yes | Permits notifications of the characteristic value.| -| indicate10+ | boolean | Yes | Permits notifications of the characteristic value without acknowledgement.| - - -## DeviceClass +## DeviceClass(deprecated) Defines the class of a Bluetooth device. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [connection.DeviceClass](js-apis-bluetooth-connection.md#deviceclass). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Type | Readable | Writable | Description | @@ -4544,10 +4733,13 @@ Defines the class of a Bluetooth device. | classOfDevice | number | Yes | No | Class of the device. | -## MajorClass +## MajorClass(deprecated) Enumerates the major classes of Bluetooth devices. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [constant.MajorClass](js-apis-bluetooth-constant.md#majorclass). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4565,10 +4757,13 @@ Enumerates the major classes of Bluetooth devices. | MAJOR_UNCATEGORIZED | 0x1F00 | Unclassified device. | -## MajorMinorClass +## MajorMinorClass(deprecated) Enumerates the major and minor classes of Bluetooth devices. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [constant.MajorMinorClass](js-apis-bluetooth-constant.md#majorminorclass). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4661,10 +4856,13 @@ Enumerates the major and minor classes of Bluetooth devices. | HEALTH_PERSONAL_MOBILITY_DEVICE | 0x093C | Personal mobility device. | -## PlayingState +## PlayingState(deprecated) Enumerates the A2DP playing states. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [a2dp.PlayingState](js-apis-bluetooth-a2dp.md#playingstate). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4673,10 +4871,13 @@ Enumerates the A2DP playing states. | STATE_PLAYING | 0x0001 | Playing.| -## ProfileId +## ProfileId(deprecated) Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOST** and **PROFILE_PAN_NETWORK**. +> **NOTE**
+> This API is supported since API version 9 and deprecated since API version 10. You are advised to use [constant.ProfileId](js-apis-bluetooth-constant.md#profileid). + **System capability**: SystemCapability.Communication.Bluetooth.Core | Name | Value | Description | @@ -4685,35 +4886,3 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS | PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | | PROFILE_HID_HOST | 6 | Human Interface Device (HID) profile. | | PROFILE_PAN_NETWORK | 7 | PAN profile. | - - -## BluetoothTransport10+ - -Enumerates the device types. The default device type is **TRANSPORT_BR_EDR**. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -| Name | Value | Description | -| -------------------------------- | ------ | --------------- | -| TRANSPORT_BR_EDR10+ | 0 | Classic Bluetooth (BR/EDR) device.| -| TRANSPORT_LE10+ | 1 | BLE device. | - - -## PinType10+ - -Enumerates the Bluetooth pairing types. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.Bluetooth.Core - -| Name | Value | Description | -| -------------------------------- | ------ | --------------- | -| PIN_TYPE_ENTER_PIN_CODE10+ | 0 | The user needs to enter the PIN displayed on the peer device.
This is a system API.| -| PIN_TYPE_ENTER_PASSKEY10+ | 1 | The user needs to enter the PASSKEY displayed on the peer device.
This is a system API. | -| PIN_TYPE_CONFIRM_PASSKEY10+ | 2 | The user needs to confirm the PASSKEY displayed on the local device.
This is a system API. | -| PIN_TYPE_NO_PASSKEY_CONSENT10+ | 3 | There is no PASSKEY, and the user needs to accept or reject the pairing request.
This is a system API. | -| PIN_TYPE_NOTIFY_PASSKEY10+ | 4 | The user needs to enter the PASSKEY displayed on the local device on the peer device.
This is a system API. | -| PIN_TYPE_DISPLAY_PIN_CODE10+ | 5 | The user needs to enter the PIN displayed on the peer device for Bluetooth 2.0 devices.
This is a system API. | -| PIN_TYPE_OOB_CONSENT10+ | 6 | The user needs to accept or reject the out of band (OOB) pairing request.
This is a system API. | -| PIN_TYPE_PIN_16_DIGITS10+ | 7 | The user needs to enter the 16-digit PIN displayed on the peer device.
This is a system API. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-businessAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-businessAbilityInfo.md index 93d9191f2b7897c387c6ce5160b1e2602befbf70..53d01ef7572136107ddfa5727b613ba100fac495 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-businessAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-businessAbilityInfo.md @@ -9,7 +9,7 @@ The **BusinessAbilityInfo** module provides basic information about a business a **System API**: This is a system API. -**System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- | diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index 1b543b547a9e3904b664e0f2826aa761402ad82b..fb0316a68118bfdb75b9b3a95be09aa835e3584a 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -61,7 +61,7 @@ Subscribes to bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ------------------ | -| type| [BundleChangedEvent](js-apis-bundleMonitor.md#BundleChangedEvent)| Yes | Type of the event to subscribe to.| +| type| [BundleChangedEvent](js-apis-bundleMonitor.md#bundlechangedevent)| Yes | Type of the event to subscribe to.| | callback | callback\| Yes | Callback used for the subscription.| **Example** @@ -94,7 +94,7 @@ Unsubscribes from bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- | -| type| [BundleChangedEvent](js-apis-bundleMonitor.md#BundleChangedEvent)| Yes | Type of the event to unsubscribe from. | +| type| [BundleChangedEvent](js-apis-bundleMonitor.md#bundlechangedevent)| Yes | Type of the event to unsubscribe from. | | callback | callback\| No | Callback used for the unsubscription. By default, no value is passed, and all callbacks of the current event are unsubscribed from.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-distributedBundleManager.md b/en/application-dev/reference/apis/js-apis-distributedBundleManager.md index 71e153396ecfc529530cf2e9fae3869bd398a0fa..8543fd943e44f8e3927562a10d54f602db9da39a 100644 --- a/en/application-dev/reference/apis/js-apis-distributedBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedBundleManager.md @@ -22,7 +22,7 @@ SystemCapability.BundleManager.DistributedBundleFramework | Permission | Permission Level | Description | | ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all bundles.| +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to obtain basic information and other sensitive information about a bundle.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index a098cef0c801348beeb9a0b43dfecfb19232e8e4..24c8730727b438c9efd3bfd4244fa55a5a605add 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -926,6 +926,115 @@ async function Demo() { } ``` +### marshalling10+ + +marshalling(sequence: rpc.MessageSequence): void + +Marshals this **PixelMap** object and writes it to a **MessageSequence** object. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------------- | ------------------------------------------------------ | ---- | ---------------------------------------- | +| sequence | [rpc.MessageSequence](js-apis-rpc.md#messagesequence9) | Yes | **MessageSequence** object. | + +**Error codes** + +For details about the error codes, see [ResponseCode](#responsecode). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 62980115 | If the input parameter invalid | +| 62980097 | If the ipc error | + +**Example** + +```js +import image from '@ohos.multimedia.image' +import rpc from '@ohos.rpc' +class MySequence { + pixel_map; + constructor(pixelmap) { + this.pixel_map = pixelmap; + } + marshalling(messageSequence) { + this.pixel_map.marshalling(messageSequence); + return true; + } + async unmarshalling(messageSequence) { + await image.unmarshalling(messageSequence).then(async (pixelMap) => { + this.pixel_map = pixelMap; + }) + return true; + } +} +async function Demo() { + let parcelable = new MySequence(pixelmap); + let data = rpc.MessageSequence.create(); + data.writeParcelable(parcelable); +} +``` + +### unmarshalling10+ + +unmarshalling(sequence: rpc.MessageSequence): Promise\ + +Unmarshals a **MessageSequence** object to obtain a **PixelMap** object. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------------- | ----------------------------------------------------- | ---- | ---------------------------------------- | +| sequence | [rpc.MessageSequence](js-apis-rpc.md#messagesequence9) | Yes | **MessageSequence** object that stores the **PixelMap** information. | + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| + +**Error codes** + +For details about the error codes, see [ResponseCode](#responsecode). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 62980115 | If the input parameter invalid | +| 62980097 | If the ipc error | + +**Example** + +```js +import image from '@ohos.multimedia.image' +import rpc from '@ohos.rpc' +class MySequence { + pixel_map; + constructor(pixelmap) { + this.pixel_map = pixelmap; + } + marshalling(messageSequence) { + this.pixel_map.marshalling(messageSequence); + return true; + } + async unmarshalling(messageSequence) { + await image.unmarshalling(messageSequence).then(async (pixelMap) => { + this.pixel_map = pixelMap; + }) + return true; + } +} +async function Demo() { + let pixel_map = undefined; + let ret = new MySequence(pixel_map); + let data = rpc.MessageSequence.create(); + await data.readParcelable(ret); +} +``` + ### release7+ release():Promise\ @@ -1590,7 +1699,7 @@ Creates an array of **PixelMap** objects based on image decoding parameters. Thi | Type | Description | | -------------------------------- | --------------------- | -| Promise> | Promise used to return an array of **PixeMap** objects.| +| Promise> | Promise used to return an array of **PixelMap** objects.| **Example** @@ -1618,7 +1727,7 @@ Creates an array of **PixelMap** objects based on the default parameters. This A | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback> | Yes | Callback used to return an array of **PixeMap** objects.| +| callback | AsyncCallback> | Yes | Callback used to return an array of **PixelMap** objects.| **Example** @@ -1641,7 +1750,7 @@ Creates an array of **PixelMap** objects based on image decoding parameters. Thi | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------- | | options | [DecodingOptions](#decodingoptions7) | Yes| Image decoding parameters.| -| callback | AsyncCallback> | Yes | Callback used to return an array of **PixeMap** objects.| +| callback | AsyncCallback> | Yes | Callback used to return an array of **PixelMap** objects.| **Example** @@ -2795,7 +2904,29 @@ Describes the exchangeable image file format (EXIF) data of an image. | SCENE_TYPE9+ | "SceneType" | Shooting scene type, for example, portrait, scenery, motion, and night. | | ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. | | F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. | - +| DATE_TIME10+ | "DateTime" | Date and time. | +| GPS_TIME_STAMP10+ | "GPSTimeStamp" | GPS timestamp. | +| GPS_DATE_STAMP10+ | "GPSDateStamp" | GPS date stamp. | +| IMAGE_DESCRIPTION10+ | "ImageDescription" | Image description. | +| MAKE10+ | "Make" | Vendor. | +| PHOTO_MODE10+ | "PhotoMode " | Photo mode. | +| SENSITIVITY_TYPE10+ | "SensitivityType" | Sensitivity type. | +| STANDARD_OUTPUT_SENSITIVITY10+ | "StandardOutputSensitivity" | Standard output sensitivity. | +| RECOMMENDED_EXPOSURE_INDEX10+ | "RecommendedExposureIndex" | Recommended exposure index. | +| ISO_SPEED10+ | "ISOSpeedRatings" | ISO speed. | +| APERTURE_VALUE10+ | "ApertureValue" | Aperture value. | +| EXPOSURE_BIAS_VALUE10+ | "ExposureBiasValue" | Exposure bias value. | +| METERING_MODE10+ | "MeteringMode" | Metering mode. | +| LIGHT_SOURCE10+ | "LightSource" | Light source. | +| FLASH 10+ | "Flash" | Flash status. | +| FOCAL_LENGTH 10+ | "FocalLength" | Focal length. | +| USER_COMMENT 10+ | "UserComment" | User comment. | +| PIXEL_X_DIMENSION 10+ | "PixelXDimension" | Pixel X dimension. | +| PIXEL_Y_DIMENSION10+ | "PixelYDimension" | Pixel Y dimension. | +| WHITE_BALANCE 10+ | "WhiteBalance" | White balance. | +| FOCAL_LENGTH_IN_35_MM_FILM 10+ | "FocalLengthIn35mmFilm" | Focal length in 35mm film. | +| CAPTURE_MODE 10+ | "HwMnoteCaptureMode" | Capture mode. | +| PHYSICAL_APERTURE 10+ | "HwMnotePhysicalAperture" | Physical aperture. | ## ImageFormat9+ diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index e428eaa609d028073417c7759d3b0c645e5f80a7..41a3fe10bbda7d00fc5aa588ed75072a702971bb 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -135,10 +135,10 @@ For details about the following error codes, see [Telephony Error Codes](../../r **Example** ```js -let sendCallback = function (err, data) { +let sendCallback = function (err, data) { console.log(`sendCallback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); } -let deliveryCallback = function (err, data) { +let deliveryCallback = function (err, data) { console.log(`deliveryCallback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); } let slotId = 0; diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 940b37ae2ad177ae64adaa6caeef0884f4dd2c8f..4e7b2b7b5914f06bc73dea8b88e2ff46b77c3b31 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -2080,7 +2080,7 @@ let result = that.encodeSync(array); ### encodeToStringSync9+ -encodeToStringSync(src: Uint8Array): string +encodeToStringSync(src: Uint8Array, options?: Type): string Encodes the input content. @@ -2091,6 +2091,7 @@ Encodes the input content. | Name| Type | Mandatory| Description | | ------ | ---------- | ---- | ------------------- | | src | Uint8Array | Yes | Uint8Array to encode.| +| options10+ | [Type](#type10) | No | Encoding format.
The following values are available:
- **util.Type.BASIC** (default value): The output can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). There is no carriage return or line feed character.
- **util.Type.MIME**: The output can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). Each line of the output contains a maximum of 76 characters, ended with '\r\n'.| **Return value** @@ -2102,14 +2103,14 @@ Encodes the input content. ```js let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeToStringSync(array); +let array = new Uint8Array([77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101]); +let result = that.encodeToStringSync(array, util.Type.MIME); ``` ### decodeSync9+ -decodeSync(src: Uint8Array | string): Uint8Array +decodeSync(src: Uint8Array | string, options?: Type): Uint8Array Decodes the input content. @@ -2120,6 +2121,7 @@ Decodes the input content. | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ----------------------------- | | src | Uint8Array \| string | Yes | Uint8Array or string to decode.| +| options10+ | [Type](#type10) | No | Encoding format.
The following values are available:
- **util.Type.BASIC** (default value): The input can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). There is no carriage return or line feed character.
- **util.Type.MIME**: The input can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). Each line of the input contains a maximum of 76 characters, ended with '\r\n'.| **Return value** @@ -2131,8 +2133,8 @@ Decodes the input content. ```js let that = new util.Base64Helper(); -let buff = 'czEz'; -let result = that.decodeSync(buff); +let buff = 'TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz\r\naW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl\r\naGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=\r\n'; +let result = that.decodeSync(buff, util.Type.MIME); ``` @@ -2172,7 +2174,7 @@ that.encode(array).then(val=>{ ### encodeToString9+ -encodeToString(src: Uint8Array): Promise<string> +encodeToString(src: Uint8Array, options?: Type): Promise<string> Encodes the input content asynchronously. @@ -2183,6 +2185,7 @@ Encodes the input content asynchronously. | Name| Type | Mandatory| Description | | ------ | ---------- | ---- | ----------------------- | | src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| options10+ | [Type](#type10) | No | Encoding format.
The following values are available:
- **util.Type.BASIC** (default value): The output can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). There is no carriage return or line feed character.
- **util.Type.MIME**: The output can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). Each line of the output contains a maximum of 76 characters, ended with '\r\n'.| **Return value** @@ -2194,16 +2197,16 @@ Encodes the input content asynchronously. ```js let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -that.encodeToString(array).then(val=>{ - console.log(val) +let array = new Uint8Array([77,97,110,105,115,100,105,115,116,105,110,103,117,105,115,104,101,100,110,111,116,111,110,108,121,98,121,104,105,115,114,101,97,115,111,110,98,117,116,98,121,116,104,105,115,115,105,110,103,117,108,97,114,112,97,115,115,105,111,110,102,114,111,109,111,116,104,101,114,97,110,105,109,97,108,115,119,104,105,99,104,105,115,97,108,117,115,116,111,102,116,104,101,109,105,110,100,101,120,99,101,101,100,115,116,104,101,115,104,111,114,116,118,101,104,101,109,101,110,99,101,111,102,97,110,121,99,97,114,110,97,108,112,108,101,97,115,117,114,101]); +that.encodeToString(array, util.Type.MIME).then(val=>{ + // Add information as required. }) ``` ### decode9+ -decode(src: Uint8Array | string): Promise<Uint8Array> +decode(src: Uint8Array | string, options?: Type): Promise<Uint8Array> Decodes the input content asynchronously. @@ -2214,6 +2217,7 @@ Decodes the input content asynchronously. | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | --------------------------------- | | src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| +| options10+ | [Type](#type10) | No | Encoding format.
The following values are available:
- **util.Type.BASIC** (default value): The input can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). There is no carriage return or line feed character.
- **util.Type.MIME**: The input can contain 64 printable characters, which are the uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the special characters plus sign (+) and slash (/). Each line of the input contains a maximum of 76 characters, ended with '\r\n'.| **Return value** @@ -2225,15 +2229,25 @@ Decodes the input content asynchronously. ```js let that = new util.Base64Helper(); -let array = new Uint8Array([99,122,69,122]); -let rarray = new Uint8Array([115,49,51]); -that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } +let array = 'TWFuaXNkaXN0aW5ndWlzaGVkbm90b25seWJ5aGlzcmVhc29uYnV0Ynl0aGlzc2luZ3VsYXJwYXNz\r\naW9uZnJvbW90aGVyYW5pbWFsc3doaWNoaXNhbHVzdG9mdGhlbWluZGV4Y2VlZHN0aGVzaG9ydHZl\r\naGVtZW5jZW9mYW55Y2FybmFscGxlYXN1cmU=\r\n'; +that.decode(array, util.Type.MIME).then(val=>{ + // Add information as required. }) ``` + +## Type10+ + +Enumerates the Base64 encoding formats. + +**System capability**: SystemCapability.Utils.Lang + +| Name | Value | Description | +| -------- | ------------------------ | ---------------- | +| BASIC | 0 | Basic format.| +| MIME | 1 | MIME format.| + + ## types8+ Provides APIs to check different types of built-in objects, such as ArrayBuffer, Map, and Set, so as to avoid exceptions or crashes caused by type errors. diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 83ba617046bba8de2547b82015dbfee8ce9be0a7..9ac2bab02f8bf52a52e25091e1779ef255b68204 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -859,6 +859,15 @@ Subscribes to the gesture navigation status change event. | type | string | Yes | Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event. | | callback | Callback<boolean> | Yes | Callback used to return the gesture navigation status. The value **true** means that the gesture navigation status is changed to enabled, and **false** means that the gesture navigation status is changed to disabled.| +**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 @@ -888,6 +897,15 @@ Unsubscribes from the gesture navigation status change event. | type | string | Yes| Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event.| | callback | Callback<boolean> | No| Callback function that has been used for registering the listener. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| +**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 @@ -2744,7 +2762,7 @@ try { ### on('avoidAreaChange')9+ -on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void +on(type: 'avoidAreaChange', callback: Callback<{ type: AvoidAreaType, area: AvoidArea}>): void Subscribes to the event indicating changes to the area where the window cannot be displayed. @@ -2755,7 +2773,7 @@ Subscribes to the event indicating changes to the area where the window cannot b | 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.| -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | Yes | Callback used to return the area and area type.| +| callback | Callback<{ type: [AvoidAreaType](#avoidareatype7), area: [AvoidArea](#avoidarea7) }> | Yes | Callback used to return the area and area type.| **Example** @@ -2772,7 +2790,7 @@ try { ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}>): void +off(type: 'avoidAreaChange', callback?: Callback<{ type: AvoidAreaType, area: AvoidArea }>): void Unsubscribes from the event indicating changes to the area where the window cannot be displayed. @@ -2783,7 +2801,7 @@ Unsubscribes from the event indicating changes to the area where the window cann | 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.| -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| +| callback | Callback<{ type: [AvoidAreaType](#avoidareatype7), area: [AvoidArea](#avoidarea7) }> | No | Callback used to return the area and area type. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled.| **Example** @@ -3122,7 +3140,16 @@ class TestRemoteObject extends rpc.RemoteObject { } let token = new TestRemoteObject('testObject'); +let windowClass = null; +let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, 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; + }); windowClass.bindDialogTarget(token, () => { console.info('Dialog Window Need Destroy.'); }, (err) => { @@ -3195,7 +3222,16 @@ class TestRemoteObject extends rpc.RemoteObject { } let token = new TestRemoteObject('testObject'); +let windowClass = null; +let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, 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; + }); let promise = windowClass.bindDialogTarget(token, () => { console.info('Dialog Window Need Destroy.'); }); @@ -3246,7 +3282,16 @@ import window from '@ohos.window'; export default class ServiceExtAbility extends ServiceExtensionAbility { onRequest(want, startId) { console.info('onRequest'); + let windowClass = null; + let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, 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; + }); let requestInfo = dialogRequest.getRequestInfo(want) windowClass.bindDialogTarget(requestInfo, () => { console.info('Dialog Window Need Destroy.'); @@ -3258,7 +3303,7 @@ export default class ServiceExtAbility extends ServiceExtensionAbility { console.info('Succeeded in binding dialog target.'); }); } catch(err) { - console.error('getRequestInfo err = ' + JSON.stringify(err)) + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)) } } } @@ -3306,7 +3351,16 @@ import window from '@ohos.window'; export default class ServiceExtAbility extends ServiceExtensionAbility { onRequest(want, startId) { console.info('onRequest'); + let windowClass = null; + let config = {name: "dialogWindow", windowType: window.WindowType.TYPE_DIALOG, 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; + }); let requestInfo = dialogRequest.getRequestInfo(want) let promise = windowClass.bindDialogTarget(requestInfo, () => { console.info('Dialog Window Need Destroy.'); @@ -3317,7 +3371,7 @@ export default class ServiceExtAbility extends ServiceExtensionAbility { console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); }); } catch(err) { - console.error('getRequestInfo err = ' + JSON.stringify(err)) + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)) } } } diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index c1cd550641f09914fe47fafba4a38b84a03513c0..5825347718827b430b434c8cb7a41c8f3b1c4bc8 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -244,7 +244,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). -| ID| Error Message +| ID| Error Message | | -------- | --------------------------------------| | 900001 | The input source file is invalid. | | 900002 | The input destination file is invalid. | diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index e0820748c9835894107fc01fa549602fca25a9b5..dc797984418a04ea512fedca19380592545a3bea 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -164,8 +164,8 @@ - Advanced Components - [@ohos.multimedia.avCastPicker (AVCastPicker)](ohos-multimedia-avcastpicker.md) - Animation - - [AnimatorProperty](ts-animatorproperty.md) - - [Explicit Animatio](ts-explicit-animation.md) + - [Property Animation](ts-animatorproperty.md) + - [Explicit Animation](ts-explicit-animation.md) - Transition Animation - [Page Transition](ts-page-transition-animation.md) - [Component Transition](ts-transition-animation-component.md) diff --git a/en/application-dev/reference/arkui-ts/figures/NestedScroll2.gif b/en/application-dev/reference/arkui-ts/figures/NestedScroll2.gif new file mode 100644 index 0000000000000000000000000000000000000000..fafe05c79f9a23c1e5f3bc3e5a8aa0a43b01648a Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/NestedScroll2.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104386.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104386.gif new file mode 100644 index 0000000000000000000000000000000000000000..07e9d4b49ff85d3a137818b5dc6cafcf6b00640c Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104386.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422896.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422896.gif new file mode 100644 index 0000000000000000000000000000000000000000..65dce0858d00df7ce62b578ce8de8b3f153d006e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422896.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982726.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982726.png new file mode 100644 index 0000000000000000000000000000000000000000..5cd212a78358d5443699725e6a963514768cb9e6 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219982726.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978363.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978363.gif deleted file mode 100644 index fa6a5f8e639b2b8b73bdae505da6b67800c5eb63..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978363.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978381.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978381.gif deleted file mode 100644 index 1cd6ff13714a55e253e9649c007080b47f02f791..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978381.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/gridDrag.png b/en/application-dev/reference/arkui-ts/figures/gridDrag.png new file mode 100644 index 0000000000000000000000000000000000000000..ab2755200c7ec3877b929c9182256f22b0cc5138 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/gridDrag.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/gridDrag1.png b/en/application-dev/reference/arkui-ts/figures/gridDrag1.png new file mode 100644 index 0000000000000000000000000000000000000000..721ec8950cc43af81afefdcd22afb14f50dfdb0e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/gridDrag1.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/gridDrag2.png b/en/application-dev/reference/arkui-ts/figures/gridDrag2.png new file mode 100644 index 0000000000000000000000000000000000000000..5fbb5f43fbb38a3b10d6455abec94bef4c5f98aa Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/gridDrag2.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/list4.gif b/en/application-dev/reference/arkui-ts/figures/list4.gif new file mode 100644 index 0000000000000000000000000000000000000000..d28ffc0be07801b3b8a3050cab0b5c95f6ffda01 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/list4.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md index 00095beb0f5a5739de8a9ab62da63a1807e475c5..ddc44429c9b5c501af18ace6b65806d776df2942 100644 --- a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -1,12 +1,12 @@ -# Property Animator +# Property Animation -You can create a property animator to animate certain universal attributes of a component, including **width**, **height**, **backgroundColor**, **opacity**, **scale**, **rotate**, and **translate**. +You can animate certain properties of a component, including **width**, **height**, **backgroundColor**, **opacity**, **scale**, **rotate**, and **translate**. > **NOTE** > > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void}) +animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations?: number, playMode?: PlayMode, onFinish?: () => void}) Since API version 9, this API is supported in ArkTS widgets. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md index e3681f6afdac7edc34bed701c1905c30857480d8..1c145a93206ecf99984346c0833750bda113d5cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md @@ -44,16 +44,16 @@ Since API version 9, this API is supported in ArkTS widgets. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type| Mandatory| Description| -| ------------- | ------- | ---- | -------- | -| closeEffect | boolean | Yes| Whether to disable the rotation and shadow effects for the component.
Default value: **false**
**NOTE**
This attribute enables or disables the shadow effect only when **trackShadow** is not set.
The shadow effect enabled through this attribute is in the default style.| -| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | Yes| Array of data segment colors. A value of the **ResourceColor** type indicates a solid color, and A value of the **LinearGradient** type indicates a color gradient.| -| trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Yes| Background color.
The value is in hexadecimal ARGB notation. The first two digits indicate opacity.
Default value: **'#08182431'**| -| strokeWidth10+ | [Length](ts-types.md#Length) | Yes| Stroke width of the border.
Default value: **24**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
This attribute does not take effect when the data panel type is **DataPanelType.Line**.| -| trackShadow10+ | [DataPanelShadowOption](#datapanelshadowoption10) | Yes| Shadow style.
**NOTE**
If this attribute is set to **null**, the shadow effect is disabled.| +| Name | Type| Description| +| ------------- | ------- | -------- | +| closeEffect | boolean | Whether to disable the rotation and shadow effects for the component.
Default value: **false**
**NOTE**
This attribute enables or disables the shadow effect only when **trackShadow** is not set.
The shadow effect enabled through this attribute is in the default style.| +| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | Array of data segment colors. A value of the **ResourceColor** type indicates a solid color, and A value of the **LinearGradient** type indicates a color gradient.| +| trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color.
The value is in hexadecimal ARGB notation. The first two digits indicate opacity.
Default value: **'#08182431'**| +| strokeWidth10+ | [Length](ts-types.md#Length) | Stroke width of the border.
Default value: **24**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
This attribute does not take effect when the data panel type is **DataPanelType.Line**.| +| trackShadow10+ | [DataPanelShadowOptions](#datapanelshadowoptions10) | Shadow style.
**NOTE**
If this attribute is set to **null**, the shadow effect is disabled.| -## DataPanelShadowOption10+ +## DataPanelShadowOptions10+ | Name | Type| Mandatory| Description| | ------------- | ------- | ---- | -------- | | radius | number \| [Resource](ts-types.md#resource)| No| Shadow blur radius.
Default value: **5**
Unit: vp
**NOTE**
A value less than or equal to 0 evaluates to the default value.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md index db8fbb1fa0a3e809409aa4afba07eb7696fc539c..9cfb2b31661b0ed834c68aeff4acce07ae0166c0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md @@ -25,11 +25,11 @@ ImageSpan(value: ResourceStr | PixelMap) ## Attributes -Among all the [universal events](ts-universal-attributes-size.md), only **width**, **height**, and **size** are supported. +The [universal attribute](ts-universal-attributes-size.md) methods can be used to set the size, background, and border. | Name| Type| Description| | -------- | -------- | -------- | -| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | Alignment mode of the image with the text.| +| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | Alignment mode of the image with the text.
Default value: **ImageSpanAlignment.BOTTOM**| | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale type.
Default value: **ImageFit.Cover**| ## ImageSpanAlignment @@ -57,7 +57,7 @@ struct SpanExample { Text() { Span('This is the Span and ImageSpan component').fontSize(25).textCase(TextCase.Normal) .decoration({ type: TextDecorationType.None, color: Color.Pink }) - }.width('100%') + }.width('100%').textAlign(TextAlign.Center) Text() { ImageSpan($r('app.media.icon')) .width('200px') @@ -85,7 +85,6 @@ struct SpanExample { .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(50) } .width('100%') - .backgroundColor(Color.Orange) .textIndent(50) }.width('100%').height('100%').padding({ left: 0, right: 0, top: 0 }) } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md b/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md index e14c0aee93857ea01cdec4f6e2843b273de28e97..c8b19032cf4bc784fa8159692f076b2d5ddf5a75 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-marquee.md @@ -30,7 +30,7 @@ Since API version 9, this API is supported in ArkTS widgets. | src | string | Yes| Text to scroll.| ## Attributes - +In addition to the universal text attributes **fontColor**, **fontSize**, **fontWeight**, and **fontFamily**, the following attributes are supported. | Name | Type| Description | | ---------- | -------- | ------------------------------------------------------------ | | allowScale | boolean | Whether to allow text to scale.
This attribute is not supported currently.
Default value: **false** | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md index d69ec2a9e833bec992c52ccd759519d131145487..23d1dd164423c71f692e07fe8600a791f94466e7 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md @@ -1,6 +1,6 @@ # RichEditor -The \ is a component that supports interactive text editing and mixture of text and imagery. +The **\** is a component that supports interactive text editing and mixture of text and imagery. > **NOTE** > @@ -114,7 +114,7 @@ Provides the image span style information returned by the backend. | ------ | -------- | ---- | -------------------------------------- | | size | [number, number] | Yes| Width and height of the image.| | verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | Yes | Vertical alignment mode of the image.| -| objectFit | [ImageFit]((ts-basic-components-imagespan.md#imagefit)) | Yes| Scale mode of the image.| +| objectFit | [ImageFit](ts-basic-components-imagespan.md#imagefit) | Yes| Scale mode of the image.| ## RichEditorOptions @@ -158,7 +158,7 @@ Sets the cursor position. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| offset | number | Yes| Offset of the cursor.| +| offset | number | Yes| Offset of the cursor. If the value is out of the text range, the setting fails.| **Return value** @@ -265,8 +265,8 @@ Defines the text span style options. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| start | number | No| Start position of the text span whose style needs to be updated. If this parameter is omitted, the value **0** will be used.| -| end | number | No| End position of the text span whose style needs to be updated. If this parameter is omitted, it indicates the end of the text span.| +| start | number | No| Start position of the text span whose style needs to be updated. If this parameter is omitted or set to a negative value, the value **0** will be used.| +| end | number | No| End position of the text span whose style needs to be updated. If this parameter is omitted or set to a value beyond the text range, it indicates the end of the text span.| | textStyle | [RichEditorTextStyle](#richeditortextstyle) | Yes| Text style.| @@ -276,8 +276,8 @@ Defines the image span style options. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| start | number | No| Start position of the image span whose style needs to be updated. If this parameter is omitted, the value **0** will be used.| -| end | number | No| End position of the image span whose style needs to be updated. If this parameter is omitted, it indicates the end of the image span.| +| start | number | No| Start position of the image span whose style needs to be updated. If this parameter is omitted or set to a negative value, the value **0** will be used.| +| end | number | No| End position of the image span whose style needs to be updated. If this parameter is omitted or set to a value beyond the text range, it indicates the end of the image span.| | imageStyle | [RichEditorImageSpanStyle](#richeditorimagespanstyle) | Yes| Image style.| @@ -296,12 +296,12 @@ Provides the text style information. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.| -| fontSize | [Length](ts-types.md#length) \| number | No| Font size.| -| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No| Font style.| -| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight.| -| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. Default value: **'HarmonyOS Sans'**.
Currently, only the default font is supported.| -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} \| number \| string | No| Style and color of the text decorative line.| +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.
Default value: **Color.Black**| +| fontSize | [Length](ts-types.md#length) \| number | No| Font size.
Default value: **16fp**| +| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No| Font style.
Default value: **FontStyle.Normal**| +| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight.
Default value: **FontWeight.Normal**| +| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. Default value: **'HarmonyOS Sans'**.
Currently, only the default font is supported.
Default font: **'HarmonyOS Sans'**| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | No| Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}| ## RichEditorImageSpanOptions @@ -320,8 +320,8 @@ Provides the image span style information. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | | size | [Dimension, Dimension] | No| Width and height of the image.| -| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | No | Vertical alignment mode of the image.| -| objectFit | [ImageFit]((ts-basic-components-imagespan.md#imagefit)) | No| Scale mode of the image.| +| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | No | Vertical alignment mode of the image.
Default value: **ImageSpanAlignment.BASELINE**| +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | No| Scale mode of the image.
Default value: **ImageFit.Cover**| ## RichEditorRange @@ -329,8 +329,8 @@ Provides the span range information. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | -------------------------------------- | -| start | number | No| Start position. If this parameter is omitted, the value **0** will be used.| -| end | number | No| End position. If this parameter is omitted, it indicates the very end.| +| start | number | No| Start position. If this parameter is omitted or set to a negative value, the value **0** will be used.| +| end | number | No| End position of the image span whose style needs to be updated. If this parameter is omitted or set to a value beyond the text range, it indicates the very end.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 6ab3c683bb77721868f160850eba311054ed5c5c..e7093230c1146b5c18238ea115189f13ce8de2cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -52,6 +52,19 @@ Among the [universal attributes](ts-universal-attributes-size.md), only the **wi | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \

This is a heading\

\

This is text\

| | \ | Embeds or references a client-side script, such as JavaScript.| \ | + +## Precautions + +The underlying layer of the **\** component uses the **\** component to provide basic capabilities, including but not limited to HTML page parsing and rendering. However, the **\** component is resources consuming. In scenarios where the **\** component is repeatedly used, for example, when it is repeatedly used in a list, frame freezing or slow response may occur. + +The **\** component complies with the constraints of the **\** component. A typical scenario is as follows: + +The default viewport size of a mobile device is 980 px. This default value ensures that most web pages can be browsed properly on the mobile device. If the width of the **\** component is less than this value, the HTML content specified by **content** may generate a scrollable page that is wrapped by the **\** component. If you want to replace the default value, add the following tags to **content**: + +```html + +``` + ## Example You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. @@ -83,7 +96,7 @@ struct RichTextExample { console.info('RichText onComplete'); }) .width(500) - .height(400) + .height(500) .backgroundColor(0XBDDB69) RichText('layoutWeight(1)') .onStart(() => { @@ -111,7 +124,3 @@ struct RichTextExample { ``` ![richText](figures/richText.png) - -## Precautions - -The underlying layer of the **\** component reuses the **\** component to provide basic capabilities, including but not limited to HTML page parsing and rendering. However, the **\** component is resources consuming. In scenarios where the **\** component is repeatedly used, for example, when it is repeatedly used in a list, frame freezing or slow response may occur. diff --git a/en/application-dev/reference/arkui-ts/ts-container-grid.md b/en/application-dev/reference/arkui-ts/ts-container-grid.md index 2f4cdeb53724cc6d716abff4298e25f3c0f9f5f6..6726cf4455e448bc64f7a54af59d4d2fb9477c6a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/en/application-dev/reference/arkui-ts/ts-container-grid.md @@ -45,8 +45,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column will be used.
For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.| -| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row will be used.
For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.
**NOTE**
If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.| +| columnsTemplate | string | Number of columns or minimum column width in the grid. If this attribute is not set, one column will be used.
For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.
**'repeat(auto-fit, 90px)'** means to automatically work out the number of columns and the actual column width, with the minimum column width of 90.
**NOTE**
If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.| +| rowsTemplate | string | Number of rows or minimum row height in the grid. If this attribute is not set, one row will be used.
For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.
**'repeat(auto-fit, 90px)'** means to automatically work out the number of rows and the actual v, with the minimum row height of 90.
**NOTE**
If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.| | columnsGap | [Length](ts-types.md#length) | Gap between columns.
Default value: **0**
**NOTE**
A value less than 0 evaluates to the default value.| | rowsGap | [Length](ts-types.md#length) | Gap between rows.
Default value: **0**
**NOTE**
A value less than 0 evaluates to the default value.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| @@ -55,8 +55,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | cachedCount | number | Number of grid items to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
**NOTE**
The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns.
Grid items that exceed the display and cache range are released.
A value less than 0 evaluates to the default value.| | editMode 8+ | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\** component.
Default value: **false**| | layoutDirection8+ | [GridDirection](#griddirection8) | Main axis direction of the grid.
Default value: **GridDirection.Row**| -| maxCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.
Default value: **Infinity**
**NOTE**
If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.
A value less than 0 evaluates to the default value.| -| minCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.
Default value: **1**
**NOTE**
A value less than 0 evaluates to the default value.| +| maxCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.
Default value: **Infinity**
**NOTE**
If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.
A value less than 1 evaluates to the default value.| +| minCount8+ | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.
When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.
Default value: **1**
**NOTE**
A value less than 1 evaluates to the default value.| | cellLength8+ | number | When **layoutDirection** is **Row** or **RowReverse**: fixed height per row.
When **layoutDirection** is **Column** or **ColumnReverse**: fixed width per column.
Default value: size of the first element| | multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.| | supportAnimation8+ | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.
Default value: **false**| @@ -187,11 +187,12 @@ struct GridExample { .columnsGap(10) .rowsGap(10) .edgeEffect(EdgeEffect.Spring) + .scrollBar(BarState.On) .onScrollIndex((first: number) => { console.info(first.toString()) }) .onScrollBarUpdate((index: number, offset: number) => { - return {totalOffset: (index / 5) * (80 + 10) - 10 - offset, totalLength: 80 * 5 + 10 * 4} + return {totalOffset: (index / 5) * (80 + 10) - offset, totalLength: 80 * 5 + 10 * 4} }) .width('90%') .backgroundColor(0xFAEEE0) @@ -284,4 +285,17 @@ struct GridExample { } } ``` - \ No newline at end of file + +Below are some examples. + +Below shows how the grid looks when dragging of grid items starts. + +![gridDrag](figures/gridDrag.png) + +Below shows how the grid looks when dragging of grid items is in progress. + +![gridDrag](figures/gridDrag1.png) + +Below shows how the grid looks after grid item 1 and grid item 6 swap their positions. + +![gridDrag](figures/gridDrag2.png) diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index 0456b0eabd821d1df0d4996900b88b98d8aed26d..c7eff1d8791375735a9d7dedc2baa217d41a32f1 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -49,21 +49,23 @@ Since API version 9, this API is supported in ArkTS widgets. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ----------------------------------- | ---------------------------------------- | ---------------------------------------- | -| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| +| Name | Type | Description | +| ----------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| | divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| | cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| | editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| -| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Edge scrolling effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| +| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge scrolling effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| | chainAnimationOptions10+ | [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API. | | multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain),
gutter10+?:[Dimension](ts-types.md#dimension10) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
If the value is set to the **gutter** type, it indicates the column spacing. It takes effect when the number of columns is greater than 1.
Default value: **0**
This API is supported in ArkTS widgets.| | alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| | sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| +| scrollSnapAlign10+ | [ScrollSnapAlign](#scrollsnapalign10) | Alignment mode of list items when scrolling ends.
Default value: **ScrollSnapAlign.NONE**
**NOTE**
This attribute is available only when the heights of list items are the same.| | enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | +| nestedScroll10+ | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.| ## ListItemAlign9+ @@ -87,7 +89,7 @@ This API is supported in ArkTS widgets. ## ChainEdgeEffect10+ -Describes the chained animation edge effect. +Describes the chained animation edge scrolling effect. **System API**: This is a system API. @@ -98,7 +100,7 @@ Describes the chained animation edge effect. ## chainAnimationOptions10+ -Provides the chained animation settings, which cover the maximum spacing, minimum spacing, intensity, conductivity, and edge effect. +Provides the chained animation settings, which cover the maximum spacing, minimum spacing, intensity, conductivity, and edge scrolling effect. **System API**: This is a system API. @@ -108,22 +110,38 @@ Provides the chained animation settings, which cover the maximum spacing, minimu | maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations. | | conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7**| | intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| -| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| +| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge scrolling effect.
Default value: **ChainEdgeEffect.DEFAULT**| > **NOTE** > > The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\** component. +## ScrollSnapAlign10+ + +Enumerates the alignment modes of list items when scrolling ends. + +Since API version 10, this API is supported in ArkTS widgets. + +When list items are left-, right-, top-, or bottom-aligned, the items at the end must be completely displayed, without exposure of any blank area of the boundary; the items at the other end can be out of alignment. + +This API is available only when the heights of list items are the same. + +| Name | Description | +| ------ | ------------------------------------------------------------ | +| NONE | No alignment. This is the default value. When scrolling ends, the list items are not aligned. | +| START | The first item in the view is aligned at the start of the list.
**NOTE**
When the list hits the end, the items at the end must be completely displayed. In this case, the items at the start may not be aligned.| +| CENTER | The middle items in the view are aligned in the center of the list.
**NOTE**
The items at the start and end can be aligned in the center of the list. In this case, the list may have a blank area exposed, and the first or last item is aligned to the center.| +| END | The last item in the view is aligned at the end of the list.
**NOTE**
When the list hits the start, the items at the start must be completely displayed. In this case, the items at the end may not be aligned.| ## Events | Name | Description | | ---------------------------------------- | ---------------------------------------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| -| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.
Since API version 9, this API is supported in ArkTS widgets.| -| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or leaves the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| -| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| -| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| +| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollIndex(event: (start: number, end: number, center10+: number) => void) | Triggered when a child component enters or leaves the list display area. Since API version 10, this event is also triggered when the child component in the center of the list display area changes.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the first child component in the list display area.
- **end**: index of the last child component in the list display area.
- **center**: index of the center child component in the list display area.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes. Since API version 10, this event is also triggered when the child component in the center of the list display area changes.
When the list edge scrolling effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| +| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge scrolling effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| +| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge scrolling effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current scrolling state.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| | onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
This API is supported in ArkTS widgets.| | onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| @@ -139,9 +157,21 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Description | | ------ | ------------------------------ | -| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged. | -| Scroll | Finger dragging. Triggered when the user drags the list to scroll. | -| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| +| Idle | Idle. The list enters this state when an API in the controller is used to scroll the list or when the scrollbar is dragged.
**NOTE**
Since API version 10, the list enters this state when it is not scrolling or an API in the controller that does not apply an animation is called.| +| Scroll | Scrolling. The list enters this state when the user drags the list to scroll.
**NOTE**
Since API version 10, the list also enters this state when the user drags the scrollbar or the mouse wheel to scroll the list. | +| Fling | Inertial scrolling. The list enters this state when inertial scrolling occurs or when the list bounces back after being released from a fling.
**NOTE**
Since API version 10, the list enters this state when: inertial scrolling occurs after a fling; the list bounces back after being released from a fling; inertial scrolling occurs after quick dragging of the built-in scrollbar; scrolling occurs after an API in the controller that applies an animation is called.| + +The table below lists the changes in the **ScrollState** enums. + +| Scenario | API version 9 and earlier |API version 10 and later | +| ------ | ------------------------------ |------------------------------ | +| Finger dragging | Scroll | Scroll | +| Inertial scrolling | Fling | Fling | +| Cross-boundary bouncing | Fling | Fling | +| Scrolling by mouse wheel | Idle | Scroll | +| Scrollbar dragging | Idle | Scroll | +| Scrolling by the scrolling controller (with animation) | Idle | Fling | +| Scrolling by the scrolling controller (without animation) | Idle | Idle | > **NOTE** > @@ -184,10 +214,14 @@ struct ListExample { .listDirection(Axis.Vertical) // Arrangement direction .scrollBar(BarState.Off) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider - .edgeEffect(EdgeEffect.Spring) // No effect when the list scrolls to the edge. - .onScrollIndex((firstIndex: number, lastIndex: number) => { + .edgeEffect(EdgeEffect.Spring) // Set the edge scrolling effect to Spring. + .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => { console.info('first' + firstIndex) console.info('last' + lastIndex) + console.info('center' + centerIndex) + }) + .onScroll((scrollOffset: number, scrollState: ScrollState) => { + console.info(`onScroll scrollState = ${ScrollState[scrollState]}, scrollOffset = ${[scrollOffset]}`) }) .width('90%') } @@ -305,3 +339,50 @@ struct ListExample{ ``` ![list](figures/list3.gif) + +### Example 4 + +```ts +// xxx.ets +@Entry +@Component +struct ListExample { + private arr: number[] = Array.apply(this, {length: 20}).map((item, i) => i) + private scrollerForList: Scroller = new Scroller() + + build() { + Column() { + Row() { + List({ space: 20, initialIndex: 0, scroller: this.scrollerForList }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%').height(100).fontSize(16) + .textAlign(TextAlign.Center) + } + .borderRadius(10).backgroundColor(0xFFFFFF) + .width('60%') + .height('80%') + }, item => item) + } + .chainAnimation(true) + .edgeEffect(EdgeEffect.Spring) + .listDirection(Axis.Horizontal) + .height('100%') + .width('100%') + .scrollSnapAlign(ScrollSnapAlign.CENTER) + .borderRadius(10) + .backgroundColor(0xDCDCDC) + .listDirection(Axis.Horizontal) + .width('100%') + } + .width('100%') + .height('100%') + .backgroundColor(0xDCDCDC) + .padding({ top: 10}) + } + } +} +``` + +![list](figures/list4.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-panel.md b/en/application-dev/reference/arkui-ts/ts-container-panel.md index 395f32d6e9ec42c8578e76084631319f935be6b9..b0359c645851f1e28e8f3ab8a3371d3f501df89d 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-panel.md +++ b/en/application-dev/reference/arkui-ts/ts-container-panel.md @@ -103,4 +103,4 @@ struct PanelExample { } ``` -![en-us_image_0000001256978381](figures/en-us_image_0000001256978381.gif) +![en-us_image_0000001174422896](figures/en-us_image_0000001174422896.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index 8fd15ac0a038142180ee2705ee4b6026ba6ac5e9..8c13e893b7a6ceea454cfbef8511153c5eda4bfb 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -35,6 +35,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.| | scrollBarWidth | string \| number | Width of the scrollbar. This attribute cannot be set in percentage.
Default value: **4**
Unit: vp
**NOTE**
If the width of the scrollbar exceeds its height, it will change to the default value.| | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.None**| +| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | +| nestedScroll10+ | [NestedScrollOptions](#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.| ## ScrollDirection | Name | Description | @@ -42,18 +44,18 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Horizontal | Only horizontal scrolling is supported. | | Vertical | Only vertical scrolling is supported. | | None | Scrolling is disabled. | -| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9. | +| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9.| ## Events -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: actual amount by which the component scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is not triggered when the controller API is called.
3. This event does not support the out-of-bounds bounce effect.
**NOTE**
The value of **offsetRemain** can be a negative value.
If the **onScrollFrameBegine** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\** is nested in the **\** component, **edgeEffect** of the **\** must be set to **EdgeEffect.None**. | -| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect. | -| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge.
**NOTE**
1. This event is triggered when scrolling reaches the edge after being started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect. | -| onScrollEnd(deprecated) (event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation. | -| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation. | -| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation. | +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: actual amount by which the component scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is not triggered when the controller API is called.
3. This event does not support the out-of-bounds bounce effect.
**NOTE**
The value of **offsetRemain** can be a negative value.
If the **onScrollFrameBegine** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\** is nested in the **\** component, **edgeEffect** of the **\** must be set to **EdgeEffect.None**.| +| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.| +| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge.
**NOTE**
1. This event is triggered when scrolling reaches the edge after being started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.| +| onScrollEnd(deprecated) (event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.| +| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.
**NOTE**
1. This event is triggered when scrolling is started by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.| +| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.
**NOTE**
1. This event is triggered when scrolling is stopped by the **\** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.| > **NOTE** > @@ -73,7 +75,7 @@ scroller: Scroller = new Scroller() ### scrollTo -scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration: number, curve: Curve } }): void +scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration?: number, curve?: Curve | ICurve } | boolean }): void Scrolls to the specified position. @@ -84,7 +86,7 @@ Scrolls to the specified position. | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | xOffset | number \| string | Yes | Horizontal scrolling offset.
**NOTE**
This parameter cannot be set in percentage.
This parameter is valid only when the scroll axis is the x-axis.| | yOffset | number \| string | Yes | Vertical scrolling offset.
**NOTE**
This parameter cannot be set in percentage.
This parameter is valid only when the scroll axis is the y-axis.| -| animation | {
duration: number,
curve: [Curve](ts-appendix-enums.md#curve)
} | No | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve.
Default value:
{
duration: 0,
curve: Curve.Ease
}
**NOTE**
A value less than 0 evaluates to the default value.| +| animation | {duration?: number, curve?: [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)10+ } \| boolean10+ | No | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve.
- **boolean**: whether to enable the default spring animation.
Default value:
{
duration: 1000,
curve: Curve.Ease
}
boolean: false
**NOTE**
A value less than 0 evaluates to the default value.
Currently, the **\**, **\**, **\**, and **\** support the **Boolean** type and **ICurve**.| ### scrollEdge @@ -112,7 +114,7 @@ Scrolls to the next or previous page. | Name | Type | Mandatory | Description | | --------- | ------- | ---- | ------------------------------ | | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| -| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | +| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | ### currentOffset @@ -146,7 +148,7 @@ When **smooth** is set to **true**, all passed items are loaded and counted in l | Name | Type| Mandatory| Description | | --------------------- | -------- | ---- | ------------------------------------------------------------ | -| value | number | Yes | Index of the item to be scrolled to in the list. | +| value | number | Yes | Index of the item to be scrolled to in the list.
**NOTE**
If the value set is a negative value or greater than the maximum index of the list items, the value is abnormal, and no scrolling will be performed. | | smooth10+ | boolean | No | Whether to enable the smooth animation for scrolling to the item with the specified index. The value **true** means to enable that the smooth animation, and **false** means the opposite.
Default value: **false**
**NOTE**
Currently, only the **\** component supports this parameter.| | align10+ | [ScrollAlign](#scrollalign10) | No | How the list item to scroll to is aligned with the list.
Default value: **ScrollAlign.START**
**NOTE**
Currently, only the **\** component supports this parameter.| @@ -169,6 +171,22 @@ Scrolls by the specified amount. | dx | Length | Yes | Amount to scroll by in the horizontal direction. The percentage format is not supported.| | dy | Length | Yes | Amount to scroll by in the vertical direction. The percentage format is not supported.| +### isAtEnd10+ + +isAtEnd(): boolean + +Checks whether the component has scrolled to the bottom. + +> **NOTE** +> +> This API is available for the **\**, **\**, **\**, and **\** components. + +**Return value** + +| Type | Description | +| ------- | -------- | +| boolean | The value **true** means that the component has scrolled to the bottom, and **false** means the opposite.| + ## ScrollAlign10+ | Name | Description | @@ -178,11 +196,27 @@ Scrolls by the specified amount. | END | The end edge of the list item is flush with the end edge of the list.| | AUTO | The list item is automatically aligned.
If the list item is fully contained within the display area, no adjustment is performed. Otherwise, the list item is aligned so that its start or end edge is flush with the start or end edge of the list, whichever requires a shorter scrolling distance.| +## NestedScrollOptions10+ +| Name | Type | Description | +| ----- | ------ | ----------------- | +| scrollForward | NestedScrollMode | Nested scrolling option when the component scrolls forward.| +| scrollBackward | NestedScrollMode | Nested scrolling option when the component scrolls backward.| + +## NestedScrollMode10+ +| Name | Description | +| ------ | ------------------------------ | +| SELF_ONLY | The scrolling is contained within the component, and no scroll chaining occurs, that is, the parent component does not scroll when the component scrolling reaches the boundary. | +| SELF_FIRST | The component scrolls first, and when it hits the boundary, the parent component scrolls. When the parent component hits the boundary, its edge effect is displayed. If no edge effect is specified for the parent component, the edge effect of the child component is displayed instead. | +| PARENT_FIRST | The parent component scrolls first, and when it hits the boundary, the component scrolls. When the component hits the boundary, its edge effect is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead.| +| PARALLEL | The component and its parent component scroll at the same time. When both the component and its parent component hit the boundary, the edge effect of the component is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead.| + ## Example ### Example 1 ```ts // xxx.ets +import Curves from '@ohos.curves' + @Entry @Component struct ScrollExample { @@ -223,7 +257,7 @@ struct ScrollExample { Button('scroll 150') .height('5%') .onClick(() => { // Click to scroll down to 150.0 vp. - this.scroller.scrollBy(0,150) + this.scroller.scrollBy(0, 150) }) .margin({ top: 10, left: 20 }) Button('scroll 100') @@ -232,24 +266,31 @@ struct ScrollExample { this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) }) .margin({ top: 60, left: 20 }) + Button('scroll 100') + .height('5%') + .onClick(() => {// Click to scroll down by 100.0 vp. An animation is applied to the scrolling. + let curve = Curves.interpolatingSpring(100, 1, 228, 30) // Create a step curve. + this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100, animation: { duration: 1000, curve: curve }}) + }) + .margin({ top: 110, left: 20 }) Button('back top') .height('5%') .onClick(() => { // Click to go back to the top. this.scroller.scrollEdge(Edge.Top) }) - .margin({ top: 110, left: 20 }) + .margin({ top: 160, left: 20 }) Button('next page') .height('5%') .onClick(() => { // Click to go to the next page. this.scroller.scrollPage({ next: true }) }) - .margin({ top: 170, left: 20 }) + .margin({ top: 210, left: 20 }) }.width('100%').height('100%').backgroundColor(0xDCDCDC) } } ``` -![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif) +![en-us_image_0000001174104386](figures/en-us_image_0000001174104386.gif) ### Example 2 ```ts @@ -311,3 +352,63 @@ struct NestedScroll { ``` ![NestedScroll](figures/NestedScroll.gif) + +### Example 3 +```ts +@Entry +@Component +struct StickyNestedScroll { + @State message: string = 'Hello World' + @State arr: number[] = [] + + @Styles listCard() { + .backgroundColor(Color.White) + .height(72) + .width("100%") + .borderRadius(12) + } + build() { + Scroll() { + Column() { + Text("Scroll Area") + .width("100%") + .height("40%") + .backgroundColor('#0080DC') + .textAlign(TextAlign.Center) + Tabs({barPosition:BarPosition.Start}) { + TabContent() { + List({space:10}) { + ForEach(this.arr, (item) => { + ListItem() { + Text("item" + item) + .fontSize(16) + }.listCard() + }, item => item) + }.width("100%") + .edgeEffect(EdgeEffect.Spring) + .nestedScroll({ + scrollForward:NestedScrollMode.PARENT_FIRST, + scrollBackward:NestedScrollMode.SELF_FIRST + }) + }.tabBar("Tab1") + TabContent() { + }.tabBar("Tab2") + } + .vertical(false) + .height("100%") + }.width("100%") + } + .edgeEffect(EdgeEffect.Spring) + .backgroundColor('#DCDCDC') + .scrollBar(BarState.Off) + .width('100%') + .height('100%') + } + aboutToAppear() { + for (let i = 0; i < 30; i++) { + this.arr.push(i) + } + } +} +``` +![NestedScroll2](figures/NestedScroll2.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 3ebb5c039cfcec05cbe209e7d58a5142a1169c95..52263bc0068469f680c269d4599c281394ca34c9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -50,7 +50,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | | curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.
Default value: **Curve.Linear**| | indicatorStyle(deprecated) | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | Style of the navigation point indicator.
\- **left**: distance between the navigation point indicator and the left edge of the **\** component.
\- **top**: distance between the navigation point indicator and the top edge of the **\** component.
\- **right**: distance between the navigation point indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation point indicator. The value cannot be in percentage. Default value: **6vp**
\- **mask**: whether to enable the mask for the navigation point indicator.
\- **color**: color of the navigation point indicator.
\- **selectedColor**: color of the selected navigation dot.
This API is supported since API version 8 and is deprecated since API version 10. You are advised to use [indicator](#indicator10) instead.| -| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is set to a number less than or equal to 0, the default value **1** is used.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount – 1)] is evenly distributed among them on the main axis.
If the value is of the SwiperAutoFill type, the system automatically calculates and changes the number of elements to display per page based on the **\** component width and the **minSize** settings for the child component. If **minSize** is left empty or set to a value less than or equal to 0, the **\** component displays one column.| +| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is set to a number less than or equal to 0, the default value **1** is used.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount - 1)] is evenly distributed among them on the main axis.
If the value is of the SwiperAutoFill type, the system automatically calculates and changes the number of elements to display per page based on the **\** component width and the **minSize** settings for the child component. If **minSize** is left empty or set to a value less than or equal to 0, the **\** component displays one column.| | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**
**NOTE**
The spring effect does not take effect when the controller API is called.| | displayArrow10+ | value:[ArrowStyle](#arrowstyle10) \| boolean,
isHoverShow?: boolean | Arrow style of the navigation point indicator.
- **value**: arrow and background to set. In abnormal scenarios, the default values in the **ArrowStyle** object are used.
\- **isHoverShow**: whether to show the arrow only when the mouse pointer hovers over the navigation point indicator.
Default value: **false**
**NOTE**
When **isHoverShow** is set to **false**, the arrow is always displayed and can be clicked to turn pages.
When **isHoverShow** is set to **true**, the arrow is displayed only when the mouse pointer hovers over the navigation point indicator, and it can be clicked to turn pages.| | nextMargin10+ |
[Length](ts-types.md#length)
| Next margin, used to reveal a small part of the next item.
Default value: **0**
**NOTE**
This attribute is available only when **SwiperDisplayMode** is set to **STRETCH**.
When the main axis runs horizontally and either the next margin or previous margin is greater than the calculated width of the child component, neither the next margin nor previous margin is displayed.
When the main axis runs vertically and either the next margin or previous margin is greater than the calculated height of the child component, neither the next margin nor previous margin is displayed.| @@ -112,8 +112,8 @@ Defines the navigation point indicator of the dot style, which inherits attribut | ------------------ | ---------------------------------------- | ---- | ---------------------------------------- | | itemWidth | [Length](ts-types.md#length) | No | Width of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| | itemHeight | [Length](ts-types.md#length) | No | Height of the navigation point indicator of the dot style.
Default value: **6**
Unit: vp| -| selectedItemWidth | [Length](ts-types.md#length) | No | Width of the selected indicator dot.
Default value: **6**
Unit: vp| -| selectedItemHeight | [Length](ts-types.md#length) | No | Height of the selected indicator dot.
Default value: **6**
Unit: vp| +| selectedItemWidth | [Length](ts-types.md#length) | No | Width of the selected navigation point indicator of the dot style.
Default value: **6**
Unit: vp| +| selectedItemHeight | [Length](ts-types.md#length) | No | Height of the selected navigation point indicator of the dot style.
Default value: **6**
Unit: vp| | mask | boolean | No | Whether to enable the mask for the navigation point indicator of the dot style.
Default value: **false**| | color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the navigation point indicator of the dot style.
Default value: **'\#182431'** (10% opacity)| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the selected indicator dot.
Default value: **'\#007DFF'**| @@ -125,9 +125,9 @@ Defines the navigation point indicator of the digit style, which inherits attrib | Name | Type | Mandatory. | Description | | ----------------- | ---------------------------------------- | ---- | ---------------------------------------- | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the navigation point indicator of the digit style.
Default value: **'\#ff182431'**| -| selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the selected indicator digit.
Default value: **'\#ff182431'**| +| selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the selected navigation point indicator of the digit style.
Default value: **'\#ff182431'**| | digitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the navigation point indicator of the digit style.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| -| selectedDigitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the selected indicator digit.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| +| selectedDigitFont | {
size?:[Length](ts-types.md#length)
weight?:number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string
} | No | Font style of the selected navigation point indicator of the digit style.
\- **size**: font size.
Default value: **14vp**
\- **weight**: font weight.| ## ArrowStyle10+ Describes the left and right arrow attributes. diff --git a/en/application-dev/reference/arkui-ts/ts-container-waterflow.md b/en/application-dev/reference/arkui-ts/ts-container-waterflow.md index 44d2eeda5df735e9f81dbb9713b899cbd66037be..70e392f7164156d01da02d69b9b0e6fdb3f77903 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-waterflow.md +++ b/en/application-dev/reference/arkui-ts/ts-container-waterflow.md @@ -44,6 +44,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | columnsGap | Length |Gap between columns.
Default value: **0**| | rowsGap | Length |Gap between rows.
Default value: **0**| | layoutDirection | [FlexDirection](ts-appendix-enums.md#flexdirection) |Main axis direction of the layout.
Default value: **FlexDirection.Column**| +| enableScrollInteraction10+ | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.
Default value: **true** | +| nestedScroll10+ | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.| The priority of **layoutDirection** is higher than that of **rowsTemplate** and **columnsTemplate**. Depending on the **layoutDirection** settings, there are three layout modes: @@ -68,8 +70,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | | onReachStart(event: () => void) | Triggered when the component reaches the start.| -| onReachEnd(event: () => void) | Triggered when the component reaches the end.| - +| onReachEnd(event: () => void) | Triggered when the component reaches the end position.| +| onScrollFrameBegin10+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the component starts to scroll. The input parameters indicate the amount by which the component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current scrolling state.
- **offsetRemain**: actual amount by which the component scrolls, in vp.
This event is triggered when the user starts dragging the component or the component starts inertial scrolling. This event is not triggered when the component rebounds or the scrolling controller is used.| ## auto-fill diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 1ba996fc0ef670359687c3e94bb6cadf704f92c5..0b61ab7aa573d325cbcc563e584313aebea45085 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -33,7 +33,7 @@ Since API version 9, this API is supported in ArkTS widgets. | [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'**
Since API version 9, this API is supported in ArkTS widgets.| | [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'**
Since API version 9, this API is supported in ArkTS widgets.| | [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10**
Since API version 9, this API is supported in ArkTS widgets.| -| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and line height. The unit must be specified and can only be px or vp.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'**
Since API version 9, this API is supported in ArkTS widgets.| +| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and line height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and line height. The unit can be px or vp and must be specified.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'**
Since API version 9, this API is supported in ArkTS widgets.| | [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
**NOTE**

In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'**
Since API version 9, this API is supported in ArkTS widgets.| | [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'**
Since API version 9, this API is supported in ArkTS widgets.| | [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | @@ -61,7 +61,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct FillStyleExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -70,9 +70,41 @@ struct FillStyleExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillStyle = '#0000ff' - this.offContext.fillRect(20, 20, 150, 100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = '#0000ff' + offContext.fillRect(20, 20, 150, 100) + var image = this.offCanvas.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + + +```ts +// xxx.ets +@Entry +@Component +struct FillStyleExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = 0x0000FF + offContext.fillRect(20, 20, 150, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -94,7 +126,7 @@ struct FillStyleExample { struct LineWidthExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -103,9 +135,10 @@ struct LineWidthExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.lineWidth = 5 - this.offContext.strokeRect(25, 25, 85, 105) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.lineWidth = 5 + offContext.strokeRect(25, 25, 85, 105) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -127,7 +160,7 @@ struct LineWidthExample { struct StrokeStyleExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -136,10 +169,43 @@ struct StrokeStyleExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.lineWidth = 10 - this.offContext.strokeStyle = '#0000ff' - this.offContext.strokeRect(25, 25, 155, 105) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.lineWidth = 10 + offContext.strokeStyle = '#0000ff' + offContext.strokeRect(25, 25, 155, 105) + var image = this.offCanvas.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + + +```ts +// xxx.ets +@Entry +@Component +struct StrokeStyleExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.lineWidth = 10 + offContext.strokeStyle = 0x0000ff + offContext.strokeRect(25, 25, 155, 105) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -161,7 +227,7 @@ struct StrokeStyleExample { struct LineCapExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -170,13 +236,14 @@ struct LineCapExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.lineWidth = 8 - this.offContext.beginPath() - this.offContext.lineCap = 'round' - this.offContext.moveTo(30, 50) - this.offContext.lineTo(220, 50) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.lineWidth = 8 + offContext.beginPath() + offContext.lineCap = 'round' + offContext.moveTo(30, 50) + offContext.lineTo(220, 50) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -198,7 +265,7 @@ struct LineCapExample { struct LineJoinExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -207,14 +274,15 @@ struct LineJoinExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.lineWidth = 8 - this.offContext.lineJoin = 'miter' - this.offContext.moveTo(30, 30) - this.offContext.lineTo(120, 60) - this.offContext.lineTo(30, 110) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.lineWidth = 8 + offContext.lineJoin = 'miter' + offContext.moveTo(30, 30) + offContext.lineTo(120, 60) + offContext.lineTo(30, 110) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -236,7 +304,7 @@ struct LineJoinExample { struct MiterLimit { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -245,14 +313,15 @@ struct MiterLimit { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.lineWidth = 8 - this.offContext.lineJoin = 'miter' - this.offContext.miterLimit = 3 - this.offContext.moveTo(30, 30) - this.offContext.lineTo(60, 35) - this.offContext.lineTo(30, 37) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.lineWidth = 8 + offContext.lineJoin = 'miter' + offContext.miterLimit = 3 + offContext.moveTo(30, 30) + offContext.lineTo(60, 35) + offContext.lineTo(30, 37) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -274,7 +343,7 @@ struct MiterLimit { struct Fonts { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -283,9 +352,10 @@ struct Fonts { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.font = '30px sans-serif' - this.offContext.fillText("Hello World", 20, 60) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.font = '30px sans-serif' + offContext.fillText("Hello World", 20, 60) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -307,7 +377,7 @@ struct Fonts { struct CanvasExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -316,24 +386,25 @@ struct CanvasExample { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeStyle = '#0000ff' - this.offContext.moveTo(140, 10) - this.offContext.lineTo(140, 160) - this.offContext.stroke() - - this.offContext.font = '18px sans-serif' - - this.offContext.textAlign = 'start' - this.offContext.fillText('textAlign=start', 140, 60) - this.offContext.textAlign = 'end' - this.offContext.fillText('textAlign=end', 140, 80) - this.offContext.textAlign = 'left' - this.offContext.fillText('textAlign=left', 140, 100) - this.offContext.textAlign = 'center' - this.offContext.fillText('textAlign=center',140, 120) - this.offContext.textAlign = 'right' - this.offContext.fillText('textAlign=right',140, 140) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.strokeStyle = '#0000ff' + offContext.moveTo(140, 10) + offContext.lineTo(140, 160) + offContext.stroke() + + offContext.font = '18px sans-serif' + + offContext.textAlign = 'start' + offContext.fillText('textAlign=start', 140, 60) + offContext.textAlign = 'end' + offContext.fillText('textAlign=end', 140, 80) + offContext.textAlign = 'left' + offContext.fillText('textAlign=left', 140, 100) + offContext.textAlign = 'center' + offContext.fillText('textAlign=center',140, 120) + offContext.textAlign = 'right' + offContext.fillText('textAlign=right',140, 140) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -355,7 +426,7 @@ struct CanvasExample { struct TextBaseline { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -364,24 +435,25 @@ struct TextBaseline { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeStyle = '#0000ff' - this.offContext.moveTo(0, 120) - this.offContext.lineTo(400, 120) - this.offContext.stroke() - - this.offContext.font = '20px sans-serif' - - this.offContext.textBaseline = 'top' - this.offContext.fillText('Top', 10, 120) - this.offContext.textBaseline = 'bottom' - this.offContext.fillText('Bottom', 55, 120) - this.offContext.textBaseline = 'middle' - this.offContext.fillText('Middle', 125, 120) - this.offContext.textBaseline = 'alphabetic' - this.offContext.fillText('Alphabetic', 195, 120) - this.offContext.textBaseline = 'hanging' - this.offContext.fillText('Hanging', 295, 120) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.strokeStyle = '#0000ff' + offContext.moveTo(0, 120) + offContext.lineTo(400, 120) + offContext.stroke() + + offContext.font = '20px sans-serif' + + offContext.textBaseline = 'top' + offContext.fillText('Top', 10, 120) + offContext.textBaseline = 'bottom' + offContext.fillText('Bottom', 55, 120) + offContext.textBaseline = 'middle' + offContext.fillText('Middle', 125, 120) + offContext.textBaseline = 'alphabetic' + offContext.fillText('Alphabetic', 195, 120) + offContext.textBaseline = 'hanging' + offContext.fillText('Hanging', 295, 120) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -403,7 +475,7 @@ struct TextBaseline { struct GlobalAlpha { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -412,12 +484,13 @@ struct GlobalAlpha { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0, 0, 50, 50) - this.offContext.globalAlpha = 0.4 - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(50, 50, 50, 50) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(0, 0, 50, 50) + offContext.globalAlpha = 0.4 + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(50, 50, 50, 50) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -439,7 +512,7 @@ struct GlobalAlpha { struct LineDashOffset { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -448,11 +521,12 @@ struct LineDashOffset { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.arc(100, 75, 50, 0, 6.28) - this.offContext.setLineDash([10,20]) - this.offContext.lineDashOffset = 10.0 - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.arc(100, 75, 50, 0, 6.28) + offContext.setLineDash([10,20]) + offContext.lineDashOffset = 10.0 + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -488,7 +562,7 @@ struct LineDashOffset { struct GlobalCompositeOperation { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -497,17 +571,18 @@ struct GlobalCompositeOperation { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(20, 20, 50, 50) - this.offContext.globalCompositeOperation = 'source-over' - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(50, 50, 50, 50) - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(120, 20, 50, 50) - this.offContext.globalCompositeOperation = 'destination-over' - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(150, 50, 50, 50) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(20, 20, 50, 50) + offContext.globalCompositeOperation = 'source-over' + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(50, 50, 50, 50) + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(120, 20, 50, 50) + offContext.globalCompositeOperation = 'destination-over' + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(150, 50, 50, 50) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -529,7 +604,7 @@ struct GlobalCompositeOperation { struct ShadowBlur { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -538,11 +613,12 @@ struct ShadowBlur { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.shadowBlur = 30 - this.offContext.shadowColor = 'rgb(0,0,0)' - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(20, 20, 100, 80) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.shadowBlur = 30 + offContext.shadowColor = 'rgb(0,0,0)' + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(20, 20, 100, 80) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -564,7 +640,7 @@ struct ShadowBlur { struct ShadowColor { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -573,11 +649,12 @@ struct ShadowColor { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.shadowBlur = 30 - this.offContext.shadowColor = 'rgb(0,0,255)' - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(30, 30, 100, 100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.shadowBlur = 30 + offContext.shadowColor = 'rgb(0,0,255)' + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(30, 30, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -599,7 +676,7 @@ struct ShadowColor { struct ShadowOffsetX { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -608,12 +685,13 @@ struct ShadowOffsetX { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.shadowBlur = 10 - this.offContext.shadowOffsetX = 20 - this.offContext.shadowColor = 'rgb(0,0,0)' - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(20, 20, 100, 80) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.shadowBlur = 10 + offContext.shadowOffsetX = 20 + offContext.shadowColor = 'rgb(0,0,0)' + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(20, 20, 100, 80) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -635,7 +713,7 @@ struct ShadowOffsetX { struct ShadowOffsetY { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -644,12 +722,13 @@ struct ShadowOffsetY { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.shadowBlur = 10 - this.offContext.shadowOffsetY = 20 - this.offContext.shadowColor = 'rgb(0,0,0)' - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(30, 30, 100, 100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.shadowBlur = 10 + offContext.shadowOffsetY = 20 + offContext.shadowColor = 'rgb(0,0,0)' + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(30, 30, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -672,7 +751,7 @@ struct ImageSmoothingEnabled { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -681,9 +760,10 @@ struct ImageSmoothingEnabled { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.imageSmoothingEnabled = false - this.offContext.drawImage( this.img,0,0,400,200) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.imageSmoothingEnabled = false + offContext.drawImage(this.img,0,0,400,200) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -725,7 +805,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct FillRect { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -734,8 +814,9 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillRect(30,30,100,100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillRect(30,30,100,100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -774,7 +855,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct StrokeRect { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -783,8 +864,9 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeRect(30, 30, 200, 150) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.strokeRect(30, 30, 200, 150) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -823,7 +905,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct ClearRect { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -832,10 +914,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(20,20,200,200) - this.offContext.clearRect(30,30,150,100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(20,20,200,200) + offContext.clearRect(30,30,150,100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -874,7 +957,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct FillText { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -883,9 +966,10 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.font = '30px sans-serif' - this.offContext.fillText("Hello World!", 20, 100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.font = '30px sans-serif' + offContext.fillText("Hello World!", 20, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -924,7 +1008,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct StrokeText { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -933,9 +1017,10 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.font = '55px sans-serif' - this.offContext.strokeText("Hello World!", 20, 60) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.font = '55px sans-serif' + offContext.strokeText("Hello World!", 20, 60) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -995,7 +1080,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct MeasureText { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1004,10 +1089,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.font = '50px sans-serif' - this.offContext.fillText("Hello World!", 20, 100) - this.offContext.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.font = '50px sans-serif' + offContext.fillText("Hello World!", 20, 100) + offContext.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1043,7 +1129,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Stroke { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1052,13 +1138,14 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.moveTo(25, 25) - this.offContext.lineTo(25, 105) - this.offContext.lineTo(75, 105) - this.offContext.lineTo(75, 25) - this.offContext.strokeStyle = 'rgb(0,0,255)' - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.moveTo(25, 25) + offContext.lineTo(25, 105) + offContext.lineTo(75, 105) + offContext.lineTo(75, 25) + offContext.strokeStyle = 'rgb(0,0,255)' + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1088,7 +1175,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct BeginPath { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1097,13 +1184,14 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.lineWidth = 6 - this.offContext.strokeStyle = '#0000ff' - this.offContext.moveTo(15, 80) - this.offContext.lineTo(280, 160) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.lineWidth = 6 + offContext.strokeStyle = '#0000ff' + offContext.moveTo(15, 80) + offContext.lineTo(280, 160) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1140,7 +1228,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct MoveTo { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1149,11 +1237,12 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.moveTo(10, 10) - this.offContext.lineTo(280, 160) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.moveTo(10, 10) + offContext.lineTo(280, 160) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1190,7 +1279,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct LineTo { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1199,11 +1288,12 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.moveTo(10, 10) - this.offContext.lineTo(280, 160) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.moveTo(10, 10) + offContext.lineTo(280, 160) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1233,7 +1323,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct ClosePath { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1242,13 +1332,14 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.moveTo(30, 30) - this.offContext.lineTo(110, 30) - this.offContext.lineTo(70, 90) - this.offContext.closePath() - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.moveTo(30, 30) + offContext.lineTo(110, 30) + offContext.lineTo(70, 90) + offContext.closePath() + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1292,7 +1383,7 @@ Since API version 9, this API is supported in ArkTS widgets. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1301,10 +1392,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var pattern = this.offContext.createPattern(this.img, 'repeat') - this.offContext.fillStyle = pattern - this.offContext.fillRect(0, 0, 200, 200) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + var pattern = offContext.createPattern(this.img, 'repeat') + offContext.fillStyle = pattern + offContext.fillRect(0, 0, 200, 200) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1345,7 +1437,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct BezierCurveTo { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1354,11 +1446,12 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.moveTo(10, 10) - this.offContext.bezierCurveTo(20, 100, 200, 100, 200, 20) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.moveTo(10, 10) + offContext.bezierCurveTo(20, 100, 200, 100, 200, 20) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1397,7 +1490,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct QuadraticCurveTo { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1406,11 +1499,12 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.moveTo(20, 20) - this.offContext.quadraticCurveTo(100, 100, 200, 20) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.moveTo(20, 20) + offContext.quadraticCurveTo(100, 100, 200, 20) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1451,7 +1545,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Arc { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1460,10 +1554,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.arc(100, 75, 50, 0, 6.28) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.arc(100, 75, 50, 0, 6.28) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1503,7 +1598,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct ArcTo { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1512,10 +1607,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.moveTo(100, 20) - this.offContext.arcTo(150, 20, 150, 70, 50) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.moveTo(100, 20) + offContext.arcTo(150, 20, 150, 70, 50) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1558,7 +1654,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct CanvasExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1566,10 +1662,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.beginPath() - this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.beginPath() + offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1608,7 +1705,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct CanvasExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1617,9 +1714,10 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1653,7 +1751,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Fill { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1662,9 +1760,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20) - this.offContext.fill() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = '#ffffff' + offContext.rect(20, 20, 100, 100) // Create a 100*100 rectangle at (20, 20) + offContext.fill() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1700,7 +1800,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Fill { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1709,6 +1809,7 @@ struct Fill { .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ + var offContext = this.offCanvas.getContext("2d", this.settings) let region = new Path2D() region.moveTo(30, 90) region.lineTo(110, 20) @@ -1718,9 +1819,9 @@ struct Fill { region.lineTo(270, 90) region.closePath() // Fill path - this.offContext.fillStyle = '#00ff00' - this.offContext.fill(region, "evenodd") - var image = this.offContext.transferToImageBitmap() + offContext.fillStyle = '#00ff00' + offContext.fill(region, "evenodd") + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1757,7 +1858,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Clip { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1766,12 +1867,13 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(0, 0, 100, 200) - this.offContext.stroke() - this.offContext.clip() - this.offContext.fillStyle = "rgb(255,0,0)" - this.offContext.fillRect(0, 0, 200, 200) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.rect(0, 0, 100, 200) + offContext.stroke() + offContext.clip() + offContext.fillStyle = "rgb(255,0,0)" + offContext.fillRect(0, 0, 200, 200) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1806,7 +1908,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Clip { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1815,6 +1917,7 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ + var offContext = this.offCanvas.getContext("2d", this.settings) let region = new Path2D() region.moveTo(30, 90) region.lineTo(110, 20) @@ -1823,10 +1926,10 @@ Since API version 9, this API is supported in ArkTS widgets. region.lineTo(190, 20) region.lineTo(270, 90) region.closePath() - this.offContext.clip(region,"evenodd") - this.offContext.fillStyle = "rgb(0,255,0)" - this.offContext.fillRect(0, 0, 600, 600) - var image = this.offContext.transferToImageBitmap() + offContext.clip(region,"evenodd") + offContext.fillStyle = "rgb(0,255,0)" + offContext.fillRect(0, 0, 600, 600) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1862,7 +1965,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct FilterDemoOff { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); build() { @@ -1872,7 +1975,8 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let offctx = this.offContext + var offContext = this.offCanvas.getContext("2d", this.settings) + let offctx = offContext let img = this.img offctx.drawImage(img, 0, 0, 100, 100); @@ -1904,7 +2008,7 @@ Since API version 9, this API is supported in ArkTS widgets. offctx.filter = 'blur(5px)'; offctx.drawImage(img, 0, 300, 100, 100); - var image = offctx.transferToImageBitmap() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -1917,20 +2021,6 @@ Since API version 9, this API is supported in ArkTS widgets. ![filterDemo](figures/filterDemo.jpeg) -### getTransform - -getTransform(): Matrix2D - -Obtains the current transformation matrix being applied to the context. This API is a void API. - -Since API version 9, this API is supported in ArkTS widgets. - -**Return value** - -| Type | Description | -| ---------------------------------------- | ----- | -| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | Matrix object.| - ### resetTransform resetTransform(): void @@ -1956,7 +2046,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct DirectionDemoOff { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1965,7 +2055,8 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let offctx = this.offContext + var offContext = this.offCanvas.getContext("2d", this.settings) + let offctx = offContext offctx.font = '48px serif'; offctx.textAlign = 'start' offctx.fillText("Hi ltr!", 200, 50); @@ -2010,7 +2101,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Rotate { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2019,9 +2110,10 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rotate(45 * Math.PI / 180) - this.offContext.fillRect(70, 20, 50, 50) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.rotate(45 * Math.PI / 180) + offContext.fillRect(70, 20, 50, 50) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2058,7 +2150,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Scale { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2067,11 +2159,12 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.lineWidth = 3 - this.offContext.strokeRect(30, 30, 50, 50) - this.offContext.scale(2, 2) // Scale to 200% - this.offContext.strokeRect(30, 30, 50, 50) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.lineWidth = 3 + offContext.strokeRect(30, 30, 50, 50) + offContext.scale(2, 2) // Scale to 200% + offContext.strokeRect(30, 30, 50, 50) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2119,7 +2212,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Transform { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2128,15 +2221,16 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillStyle = 'rgb(0,0,0)' - this.offContext.fillRect(0, 0, 100, 100) - this.offContext.transform(1, 0.5, -0.5, 1, 10, 10) - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(0, 0, 100, 100) - this.offContext.transform(1, 0.5, -0.5, 1, 10, 10) - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0, 0, 100, 100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = 'rgb(0,0,0)' + offContext.fillRect(0, 0, 100, 100) + offContext.transform(1, 0.5, -0.5, 1, 10, 10) + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(0, 0, 100, 100) + offContext.transform(1, 0.5, -0.5, 1, 10, 10) + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(0, 0, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2177,7 +2271,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct SetTransform { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2186,12 +2280,13 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillStyle = 'rgb(255,0,0)' - this.offContext.fillRect(0, 0, 100, 100) - this.offContext.setTransform(1,0.5, -0.5, 1, 10, 10) - this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0, 0, 100, 100) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillStyle = 'rgb(255,0,0)' + offContext.fillRect(0, 0, 100, 100) + offContext.setTransform(1,0.5, -0.5, 1, 10, 10) + offContext.fillStyle = 'rgb(0,0,255)' + offContext.fillRect(0, 0, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2204,6 +2299,86 @@ Since API version 9, this API is supported in ArkTS widgets. ![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png) +### setTransform + +setTransform(transform?: Matrix2D): void + +Resets the current transformation and creates a new transformation matrix based on the specified **Matrix2D** object. + +Since API version 9, this API is supported in ArkTS widgets. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| --------- | ---------------------------------------- | ---- | ---- | ----- | +| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | null | Matrix object. | + +### getTransform + +getTransform(): Matrix2D + +Obtains the current transformation matrix being applied to the context. + +Since API version 9, this API is supported in ArkTS widgets. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----- | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | Matrix object.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct TransFormDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context1: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private offcontext1: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 100, this.settings); + private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private offcontext2: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 100, this.settings); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('context1'); + Canvas(this.context1) + .width('230vp') + .height('120vp') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offcontext1.fillRect(50, 50, 50, 50); + this.offcontext1.setTransform(1.2, Math.PI/8, Math.PI/6, 0.5, 30, -25); + this.offcontext1.fillRect(50, 50, 50, 50); + var image = this.offcontext1.transferToImageBitmap(); + this.context1.transferFromImageBitmap(image); + }) + Text('context2'); + Canvas(this.context2) + .width('230vp') + .height('120vp') + .backgroundColor('#0ffff0') + .onReady(() =>{ + this.offcontext2.fillRect(50, 50, 50, 50); + let storedTransform = this.offcontext1.getTransform(); + console.log("Matrix [scaleX = " + storedTransform.scaleX + ", scaleY = " + storedTransform.scaleY + + ", rotateX = " + storedTransform.rotateX + ", rotateY = " + storedTransform.rotateY + + ", translateX = " + storedTransform.translateX + ", translateY = " + storedTransform.translateY + "]") + this.offcontext2.setTransform(storedTransform); + this.offcontext2.fillRect(50,50,50,50); + var image = this.offcontext2.transferToImageBitmap(); + this.context2.transferFromImageBitmap(image); + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ![en-us_image_0000001219982726.png](figures/en-us_image_0000001219982726.png) + ### translate translate(x: number, y: number): void @@ -2228,7 +2403,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct Translate { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2237,10 +2412,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.fillRect(10, 10, 50, 50) - this.offContext.translate(70, 70) - this.offContext.fillRect(10, 10, 50, 50) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.fillRect(10, 10, 50, 50) + offContext.translate(70, 70) + offContext.fillRect(10, 10, 50, 50) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2290,7 +2466,7 @@ Since API version 9, this API is supported in ArkTS widgets, except that **Pixel private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2298,8 +2474,9 @@ Since API version 9, this API is supported in ArkTS widgets, except that **Pixel .height('100%') .backgroundColor('#ffff00') .onReady(() => { - this.offContext.drawImage( this.img,0,0,400,200) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.drawImage( this.img,0,0,400,200) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2422,7 +2599,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct GetImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") build() { @@ -2432,10 +2609,11 @@ Since API version 9, this API is supported in ArkTS widgets. .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) - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.drawImage(this.img,0,0,130,130) + var imagedata = offContext.getImageData(50,50,130,130) + offContext.putImageData(imagedata,150,150) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2479,7 +2657,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct PutImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2487,15 +2665,16 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var imageData = this.offContext.createImageData(100, 100) + var offContext = this.offCanvas.getContext("2d", this.settings) + var imageData = offContext.createImageData(100, 100) for (var i = 0; i < imageData.data.length; i += 4) { imageData.data[i + 0] = 255 imageData.data[i + 1] = 0 imageData.data[i + 2] = 255 imageData.data[i + 3] = 255 } - this.offContext.putImageData(imageData, 10, 10) - var image = this.offContext.transferToImageBitmap() + offContext.putImageData(imageData, 10, 10) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2529,7 +2708,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct SetLineDash { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2538,10 +2717,11 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.arc(100, 75, 50, 0, 6.28) - this.offContext.setLineDash([10,20]) - this.offContext.stroke() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.arc(100, 75, 50, 0, 6.28) + offContext.setLineDash([10,20]) + offContext.stroke() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2577,7 +2757,7 @@ Since API version 9, this API is supported in ArkTS widgets. @State message: string = 'Hello World' private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Row() { Column() { @@ -2586,7 +2766,8 @@ Since API version 9, this API is supported in ArkTS widgets. .fontWeight(FontWeight.Bold) .onClick(()=>{ console.error('before getlinedash clicked') - let res = this.offContext.getLineDash() + var offContext = this.offCanvas.getContext("2d", this.settings) + let res = offContext.getLineDash() console.error(JSON.stringify(res)) }) Canvas(this.context) @@ -2594,11 +2775,12 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() => { - this.offContext.arc(100, 75, 50, 0, 6.28) - this.offContext.setLineDash([10,20]) - this.offContext.stroke() - let res = this.offContext.getLineDash() - var image = this.offContext.transferToImageBitmap() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.arc(100, 75, 50, 0, 6.28) + offContext.setLineDash([10,20]) + offContext.stroke() + let res = offContext.getLineDash() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2642,7 +2824,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct ToDataURL { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2651,7 +2833,8 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var dataURL = this.offContext.toDataURL() + var offContext = this.offCanvas.getContext("2d", this.settings) + var dataURL = offContext.toDataURL() }) } .width('100%') @@ -2683,7 +2866,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct ImageSmoothingQualityDemoOff { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); build() { @@ -2693,12 +2876,13 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - let offctx = this.offContext + var offContext = this.offCanvas.getContext("2d", this.settings) + let offctx = offContext offctx.imageSmoothingEnabled = true offctx.imageSmoothingQuality = 'high' offctx.drawImage(this.img, 0, 0, 400, 200) - var image = offctx.transferToImageBitmap() + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2732,7 +2916,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O struct PutImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2741,15 +2925,16 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var imageData = this.offContext.createImageData(100, 100) + var offContext = this.offCanvas.getContext("2d", this.settings) + var imageData = offContext.createImageData(100, 100) for (var i = 0; i < imageData.data.length; i += 4) { imageData.data[i + 0] = 255 imageData.data[i + 1] = 0 imageData.data[i + 2] = 255 imageData.data[i + 3] = 255 } - this.offContext.putImageData(imageData, 10, 10) - var image = this.offContext.transferToImageBitmap() + offContext.putImageData(imageData, 10, 10) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2777,7 +2962,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct CanvasExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2786,12 +2971,13 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.save() // save the default state - this.offContext.fillStyle = "#00ff00" - 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() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.save() // save the default state + offContext.fillStyle = "#00ff00" + offContext.fillRect(20, 20, 100, 100) + offContext.restore() // restore to the default state + offContext.fillRect(150, 75, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2820,7 +3006,7 @@ Since API version 9, this API is supported in ArkTS widgets. struct CanvasExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2829,12 +3015,13 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.save() // save the default state - this.offContext.fillStyle = "#00ff00" - 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() + var offContext = this.offCanvas.getContext("2d", this.settings) + offContext.save() // save the default state + offContext.fillStyle = "#00ff00" + offContext.fillRect(20, 20, 100, 100) + offContext.restore() // restore to the default state + offContext.fillRect(150, 75, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2872,8 +3059,8 @@ Since API version 9, this API is supported in ArkTS widgets. struct CreateLinearGradient { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2881,13 +3068,14 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var grad = this.offContext.createLinearGradient(50,0, 300,100) + var offContext = this.offCanvas.getContext("2d", this.settings) + var grad = offContext.createLinearGradient(50,0, 300,100) grad.addColorStop(0.0, '#ff0000') grad.addColorStop(0.5, '#ffffff') grad.addColorStop(1.0, '#00ff00') - this.offContext.fillStyle = grad - this.offContext.fillRect(0, 0, 400, 400) - var image = this.offContext.transferToImageBitmap() + offContext.fillStyle = grad + offContext.fillRect(0, 0, 400, 400) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2928,8 +3116,8 @@ Since API version 9, this API is supported in ArkTS widgets. struct CreateRadialGradient { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2937,13 +3125,14 @@ Since API version 9, this API is supported in ArkTS widgets. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - var grad = this.offContext.createRadialGradient(200,200,50, 200,200,200) + var offContext = this.offCanvas.getContext("2d", this.settings) + var grad = offContext.createRadialGradient(200,200,50, 200,200,200) grad.addColorStop(0.0, '#ff0000') grad.addColorStop(0.5, '#ffffff') grad.addColorStop(1.0, '#00ff00') - this.offContext.fillStyle = grad - this.offContext.fillRect(0, 0, 440, 440) - var image = this.offContext.transferToImageBitmap() + offContext.fillStyle = grad + offContext.fillRect(0, 0, 440, 440) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -2978,8 +3167,7 @@ Creates a conic gradient. struct OffscreenCanvasConicGradientPage { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2988,13 +3176,14 @@ struct OffscreenCanvasConicGradientPage { .height('100%') .backgroundColor('#ffffff') .onReady(() =>{ - var grad = this.offContext.createConicGradient(0, 50, 80) + var offContext = this.offCanvas.getContext("2d", this.settings) + var grad = offContext.createConicGradient(0, 50, 80) grad.addColorStop(0.0, '#ff0000') grad.addColorStop(0.5, '#ffffff') grad.addColorStop(1.0, '#00ff00') - this.offContext.fillStyle = grad - this.offContext.fillRect(0, 30, 100, 100) - var image = this.offContext.transferToImageBitmap() + offContext.fillStyle = grad + offContext.fillRect(0, 30, 100, 100) + var image = this.offCanvas.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } diff --git a/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md b/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md index e0a3bb339e1db622d902737a7f3a1d4f61d2cf64..e43e8f0007c77fc55206ff51a2cc0ecaa7749549 100644 --- a/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-page-transition-animation.md @@ -10,8 +10,8 @@ You can customize the page entrance and exit animations in the **pageTransition* | Name | Parameter | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | No | Page entrance animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
- **duration**: animation duration.
Unit: ms
Default value: **1000**
- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".
Default value: **Curve.Linear**
- **delay**: animation delay.
Unit: ms
Default value: **0**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.| -| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | No | Page exit animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
- **duration**: animation duration.
Unit: ms
Default value: **1000**
- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.
Default value: **Curve.Linear**
- **delay**: animation delay.
Unit: ms
Default value: **0**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.| +| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | No | Page entrance animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
- **duration**: animation duration.
Unit: ms
Default value: **1000**
- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".
Default value: **Curve.Linear**
- **delay**: animation delay.
Unit: ms
Default value: **0**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.| +| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | No | Page exit animation.
- **type**: route type for the page transition effect to take effect.
Default value: **RouteType.None**
- **duration**: animation duration.
Unit: ms
Default value: **1000**
- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.
Default value: **Curve.Linear**
- **delay**: animation delay.
Unit: ms
Default value: **0**
**NOTE**
If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.| ## RouteType diff --git a/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index c741d2973743543c25e430e7575c8162053780bf..d37a8923e07eb70eee30e748dd3002cc0edbc7c2 100644 --- a/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -12,7 +12,7 @@ A shared element transition is a transition animation applied to a component tha | Name | Parameter | Description | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| sharedTransition | id: string,
{
duration?: number,
curve?: Curve \| string,
delay?: number,
motionPath?:
{
path: string,
form?: number,
to?: number,
rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.
- **id**: component ID.
- **duration**: animation duration.
Default value: **1000**
Unit: ms
Value range: [0, +∞)
The value **0** indicates that no animation is applied. A value less than 0 evaluates to the default value **1000**.
- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).
- **delay**: animation delay.
Default value: **0**
Unit: ms
Value range: [0, +∞)
A value less than 0 evaluates to the value **0**.
- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).
- **path**: path.
- **from**: start value.
- **to**: end value.
- **rotatable**: whether to rotate.
- **zIndex**: z-axis.
- **type**: animation type.| +| sharedTransition | id: string,
{
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number,
motionPath?:
{
path: string,
form?: number,
to?: number,
rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.
- **id**: component ID.
- **duration**: animation duration.
Default value: **1000**
Unit: ms
Value range: [0, +∞)
The value **0** indicates that no animation is applied. A value less than 0 evaluates to the default value **1000**.
- **curve**: animation curve. The default curve is **Curve.Linear**.
- **delay**: animation delay.
Default value: **0**
Unit: ms
Value range: [0, +∞)
A value less than 0 evaluates to the value **0**.
- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).
- **path**: path.
- **from**: start value.
- **to**: end value.
- **rotatable**: whether to rotate.
- **zIndex**: z-axis.
- **type**: animation type.| ## Example diff --git a/en/application-dev/reference/native-api-intro.md b/en/application-dev/reference/native-api-intro.md index ab4abf60501d680249973f16bc2b35eadc1f6bca..b3e77ed151c7c88186b987b445160a0d6e1e117f 100644 --- a/en/application-dev/reference/native-api-intro.md +++ b/en/application-dev/reference/native-api-intro.md @@ -49,7 +49,7 @@ Native APIs are stored in the **$(SDK_ROOT)/native** directory of the SDK. * [Native API Reference](native-apis/_o_h___native_x_component.md): provides reference for Native APIs. * [Standard Libraries Supported by Native APIs](../reference/native-lib/third_party_libc/musl.md): describes the open-source standard libraries supported by Native APIs. * [Native API Development](../napi/napi-guidelines.md): describes how to use Native APIs. -* [Using NDK to Build a CMake C/C++ Project](../faqs/howto-migrate-cmake-with-ohosndk.md): describes how to use Native APIs to develop a CMake project. +* [Using NDK to Build a CMake C/C++ Project](../faqs/cmake-with-ndk.md): describes how to use Native APIs to develop a CMake project. * [Using Node-APIs in Application Projects](../napi/napi-guidelines.md): describes how to use Node-APIs. ## How to Use diff --git a/en/application-dev/reference/native-apis/Readme-EN.md b/en/application-dev/reference/native-apis/Readme-EN.md index 7df15ff27960734f7d9386bdcf807d6cb6d9ecc5..e9198c7331b2ab1709da5917799cf88999903bb9 100644 --- a/en/application-dev/reference/native-apis/Readme-EN.md +++ b/en/application-dev/reference/native-apis/Readme-EN.md @@ -48,6 +48,7 @@ - [native_buffer.h](native__buffer_8h.md) - [native_image.h](native__image_8h.md) - [native_interface_xcomponent.h](native__interface__xcomponent_8h.md) + - [native_xcomponent_key_event.h](native__xcomponent__key__event_8h.md) - [native_vsync.h](native__vsync_8h.md) - [raw_dir.h](raw__dir_8h.md) - [raw_file_manager.h](raw__file__manager_8h.md) diff --git a/en/application-dev/reference/native-apis/_huks_key_api.md b/en/application-dev/reference/native-apis/_huks_key_api.md index a8fffd18de8c4e9aa8f687b7c221aad24d89d41b..3d0508969b2060af91cf92ec5c65e8ae114cbe42 100644 --- a/en/application-dev/reference/native-apis/_huks_key_api.md +++ b/en/application-dev/reference/native-apis/_huks_key_api.md @@ -7,37 +7,36 @@ Describes the OpenHarmony Universal KeyStore (HUKS) capabilities, including key \@syscap SystemCapability.Security.Huks -**Since:** + **Since**: 9 - ## Summary ### Files -| Name | Description | +| Name| Description| | -------- | -------- | -| [native_huks_api.h](native__huks__api_8h.md) | Declares the APIs used to access the HUKS.
File to Include: | +| [native_huks_api.h](native__huks__api_8h.md) | Declares the APIs used to access the HUKS.
**File to include**:
**Library**: libhuks_ndk.z.so | ### Functions -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Huks_GetSdkVersion](#oh_huks_getsdkversion) (struct [OH_Huks_Blob](_o_h___huks___blob.md) \*sdkVersion) | Obtains the current HUKS SDK version. | -| [OH_Huks_GenerateKeyItem](#oh_huks_generatekeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetIn, struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetOut) | Generates a key. | -| [OH_Huks_ImportKeyItem](#oh_huks_importkeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*key) | Imports a key in plaintext. | -| [OH_Huks_ImportWrappedKeyItem](#oh_huks_importwrappedkeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*wrappingKeyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*wrappedKeyData) | Imports a wrapped key. | -| [OH_Huks_ExportPublicKeyItem](#oh_huks_exportpublickeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*key) | Exports a public key. | -| [OH_Huks_DeleteKeyItem](#oh_huks_deletekeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Deletes a key. | -| [OH_Huks_GetKeyItemParamSet](#oh_huks_getkeyitemparamset) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetIn, struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetOut) | Obtains the attributes of a key. | -| [OH_Huks_IsKeyItemExist](#oh_huks_iskeyitemexist) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Checks whether a key exists. | -| [OH_Huks_AttestKeyItem](#oh_huks_attestkeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, struct [OH_Huks_CertChain](_o_h___huks___cert_chain.md) \*certChain) | Obtain the key certificate chain. | -| [OH_Huks_InitSession](#oh_huks_initsession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*challenge) | Initializes the key session interface and obtains a handle (mandatory) and challenge value (optional). | -| [OH_Huks_UpdateSession](#oh_huks_updatesession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*inData, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*outData) | Adds data by segment for the key operation, performs the related key operation, and outputs the processed data. | -| [OH_Huks_FinishSession](#oh_huks_finishsession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*inData, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*outData) | Ends the key session. | -| [OH_Huks_AbortSession](#oh_huks_abortsession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Aborts a key session. | +| [OH_Huks_GetSdkVersion](#oh_huks_getsdkversion) (struct [OH_Huks_Blob](_o_h___huks___blob.md) \*sdkVersion) | Obtains the current HUKS SDK version. | +| [OH_Huks_GenerateKeyItem](#oh_huks_generatekeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetIn, struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetOut) | Generates a key. | +| [OH_Huks_ImportKeyItem](#oh_huks_importkeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*key) | Imports a key in plaintext. | +| [OH_Huks_ImportWrappedKeyItem](#oh_huks_importwrappedkeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*wrappingKeyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*wrappedKeyData) | Imports a wrapped (encrypted) key. | +| [OH_Huks_ExportPublicKeyItem](#oh_huks_exportpublickeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*key) | Exports a public key. | +| [OH_Huks_DeleteKeyItem](#oh_huks_deletekeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Deletes a key. | +| [OH_Huks_GetKeyItemParamSet](#oh_huks_getkeyitemparamset) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetIn, struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSetOut) | Obtains the properties of a key. | +| [OH_Huks_IsKeyItemExist](#oh_huks_iskeyitemexist) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Checks whether a key exists. | +| [OH_Huks_AttestKeyItem](#oh_huks_attestkeyitem) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, struct [OH_Huks_CertChain](_o_h___huks___cert_chain.md) \*certChain) | Obtains the certificate chain of a key. | +| [OH_Huks_InitSession](#oh_huks_initsession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*keyAlias, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*token) | Initializes a key session to obtain a handle (mandatory) and a token (optional). | +| [OH_Huks_UpdateSession](#oh_huks_updatesession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*inData, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*outData) | Adds data by segment for the key operation, performs the related key operation, and outputs the processed data. | +| [OH_Huks_FinishSession](#oh_huks_finishsession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*inData, struct [OH_Huks_Blob](_o_h___huks___blob.md) \*outData) | Finishes a key session. | +| [OH_Huks_AbortSession](#oh_huks_abortsession) (const struct [OH_Huks_Blob](_o_h___huks___blob.md) \*handle, const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Aborts a key session. | ## Function Description @@ -45,25 +44,26 @@ Describes the OpenHarmony Universal KeyStore (HUKS) capabilities, including key ### OH_Huks_AbortSession() - + ``` struct OH_Huks_Result OH_Huks_AbortSession (const struct OH_Huks_Blob * handle, const struct OH_Huks_ParamSet * paramSet ) ``` -**Description**
+**Description** + Aborts a key session. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| handle | Indicates the pointer to the key session handle, which is generated by [OH_Huks_InitSession](#oh_huks_initsession). | -| paramSet | Indicates the pointer to the parameters required for aborting the key session. By default, this parameter is a null pointer. | +| handle | Indicates the pointer to the key session handle, which is generated by [OH_Huks_InitSession](#oh_huks_initsession). | +| paramSet | Indicates the pointer to the parameters required for aborting the key session. By default, this parameter is a null pointer. | **Returns** Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. - **See** +**See** [OH_Huks_InitSession](#oh_huks_initsession) @@ -74,20 +74,21 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_AttestKeyItem() - + ``` struct OH_Huks_Result OH_Huks_AttestKeyItem (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet, struct OH_Huks_CertChain * certChain ) ``` -**Description**
-Obtain the key certificate chain. +**Description** - **Parameters** +Obtains the certificate chain of a key. -| Name | Description | +**Parameters** + +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the target key. | -| paramSet | Indicates the pointer to the parameters required for obtaining the key certificate. | -| certChain | Indicates the pointer to the key certificate chain obtained. | +| keyAlias | Indicates the pointer to the alias of the target key. | +| paramSet | Indicates the pointer to the parameters required for obtaining the certificate chain. | +| certChain | Indicates the pointer to the certificate chain obtained. | **Returns** @@ -96,19 +97,20 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_DeleteKeyItem() - + ``` struct OH_Huks_Result OH_Huks_DeleteKeyItem (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet ) ``` -**Description**
+**Description** + Deletes a key. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the key to delete. The alias must be the same as the alias for the key generated. | -| paramSet | Indicates the pointer to the parameters required for deleting the key. By default, this parameter is a null pointer. | +| keyAlias | Indicates the pointer to the alias of the key to delete. It must be the same as the alias used for generating the key. | +| paramSet | Indicates the pointer to the parameters required for deleting the key. By default, this parameter is a null pointer. | **Returns** @@ -117,20 +119,21 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_ExportPublicKeyItem() - + ``` struct OH_Huks_Result OH_Huks_ExportPublicKeyItem (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet, struct OH_Huks_Blob * key ) ``` -**Description**
+**Description** + Exports a public key. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the public key to export. The alias must be the same as the alias for the key generated. | -| paramSet | Indicates the pointer to the parameters required for exporting the public key. | -| key | Indicates the pointer to the public key exported. | +| keyAlias | Indicates the pointer to the alias of the public key to export. It must be the same as the alias used for generating the key. | +| paramSet | Indicates the pointer to the parameters required for exporting the public key. | +| key | Indicates the pointer to the public key exported. | **Returns** @@ -139,27 +142,28 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_FinishSession() - + ``` struct OH_Huks_Result OH_Huks_FinishSession (const struct OH_Huks_Blob * handle, const struct OH_Huks_ParamSet * paramSet, const struct OH_Huks_Blob * inData, struct OH_Huks_Blob * outData ) ``` -**Description**
-Ends the key session. +**Description** - **Parameters** +Finishes a key session. -| Name | Description | +**Parameters** + +| Name| Description| | -------- | -------- | -| handle | Indicates the pointer to the key session handle, which is generated by [OH_Huks_InitSession](#oh_huks_initsession). | -| paramSet | Indicates the pointer to the parameters required for the key operation. | -| inData | Indicates the pointer to the data to be processed. | -| outData | Indicates the pointer to the output data. | +| handle | Indicates the pointer to the key session handle, which is generated by [OH_Huks_InitSession](#oh_huks_initsession). | +| paramSet | Indicates the pointer to the parameters required for the key operation. | +| inData | Indicates the pointer to the data to be passed in. | +| outData | Indicates the pointer to the output data. | **Returns** Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. - **See** +**See** [OH_Huks_InitSession](#oh_huks_initsession) @@ -170,20 +174,21 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_GenerateKeyItem() - + ``` struct OH_Huks_Result OH_Huks_GenerateKeyItem (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSetIn, struct OH_Huks_ParamSet * paramSetOut ) ``` -**Description**
+**Description** + Generates a key. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the key to generate. The alias must be unique in the process of the service. Otherwise, the key will be overwritten. | -| paramSetIn | Indicates the pointer to the parameter set for generating the key. | -| paramSetOut | Indicates the pointer to a temporary key generated. If the generated key is not of a temporary type, this parameter is a null pointer. | +| keyAlias | Indicates the pointer to the alias of the key to generate. The alias must be unique in the process of the service. | +| paramSetIn | Indicates the pointer to the parameters for generating the key. | +| paramSetOut | Indicates the pointer to a temporary key generated. If the generated key is not of a temporary type, this parameter is a null pointer. | **Returns** @@ -192,20 +197,21 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_GetKeyItemParamSet() - + ``` struct OH_Huks_Result OH_Huks_GetKeyItemParamSet (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSetIn, struct OH_Huks_ParamSet * paramSetOut ) ``` -**Description**
-Obtains the attributes of a key. +**Description** + +Obtains the properties of a key. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the target key. | -| paramSetIn | Indicates the pointer to the attribute tag required for obtaining the attributes. By default, this parameter is a null pointer. | -| paramSetOut | Indicates the pointer to the attributes obtained. | +| keyAlias | Indicates the pointer to the alias of the target key. | +| paramSetIn | Indicates the pointer to the tag required for obtaining the properties. By default, this parameter is a null pointer. | +| paramSetOut | Indicates the pointer to the key properties obtained. | **Returns** @@ -214,18 +220,19 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_GetSdkVersion() - + ``` struct OH_Huks_Result OH_Huks_GetSdkVersion (struct OH_Huks_Blob * sdkVersion) ``` -**Description**
+**Description** + Obtains the current HUKS SDK version. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| sdkVersion | Indicates the pointer to the SDK version (in string format) obtained. | +| sdkVersion | Indicates the pointer to the SDK version (string) obtained. | **Returns** @@ -234,20 +241,21 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_ImportKeyItem() - + ``` struct OH_Huks_Result OH_Huks_ImportKeyItem (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet, const struct OH_Huks_Blob * key ) ``` -**Description**
+**Description** + Imports a key in plaintext. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the key to import. The alias must be unique in the process of the service. Otherwise, the key will be overwritten. | -| paramSet | Indicates the pointer to the parameters of the key to import. | -| key | Indicates the pointer to the key to import. The key must be in the format required by the HUKS. For details, see [HuksTypeApi](_huks_type_api.md). | +| keyAlias | Indicates the pointer to the alias of the key to import. The alias must be unique in the process of the service. | +| paramSet | Indicates the pointer to the properties of the key to import. | +| key | Indicates the pointer to the key to import. The key data must be in format defined in [HuksTypeApi](_huks_type_api.md). | **Returns** @@ -256,21 +264,22 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_ImportWrappedKeyItem() - + ``` struct OH_Huks_Result OH_Huks_ImportWrappedKeyItem (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_Blob * wrappingKeyAlias, const struct OH_Huks_ParamSet * paramSet, const struct OH_Huks_Blob * wrappedKeyData ) ``` -**Description**
-Imports a wrapped key. +**Description** + +Imports a wrapped (encrypted) key. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the key to import. The alias must be unique in the process of the service. Otherwise, the key will be overwritten. | -| wrappingKeyAlias | Indicates the pointer to the alias of the wrapping key, which is obtained through key agreement and used to decrypt the key to import. | -| paramSet | Indicates the pointer to the parameters of the wrapped key to import. | -| wrappedKeyData | Indicates the pointer to the wrapped key to import. The key must be in the format required by the HUKS. For details, see [OH_Huks_AlgSuite](_huks_type_api.md#oh_huks_algsuite). | +| keyAlias | Indicates the pointer to the alias of the key to import. The alias must be unique in the process of the service. | +| wrappingKeyAlias | Indicates the pointer to the alias of the wrapping key, which is obtained through key agreement and used to decrypt the key to import. | +| paramSet | Indicates the pointer to the parameters for importing the wrapped key. | +| wrappedKeyData | Indicates the pointer to the wrapped key to import. The data must be in the format defined in [OH_Huks_AlgSuite](_huks_type_api.md#oh_huks_algsuite).| **Returns** @@ -279,27 +288,28 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_InitSession() - + ``` -struct OH_Huks_Result OH_Huks_InitSession (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet, struct OH_Huks_Blob * handle, struct OH_Huks_Blob * challenge ) +struct OH_Huks_Result OH_Huks_InitSession (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet, struct OH_Huks_Blob * handle, struct OH_Huks_Blob * token ) ``` -**Description**
-Initializes the key session interface and obtains a handle (mandatory) and challenge value (optional). +**Description** - **Parameters** +Initializes a key session to obtain a handle (mandatory) and a token (optional). -| Name | Description | +**Parameters** + +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the target key. | -| paramSet | Indicates the pointer to the parameters for the initialization operation. | -| handle | Indicates the pointer to the handle of the key session obtained. This handle is required for subsequent operations, including [OH_Huks_UpdateSession](#oh_huks_updatesession), [OH_Huks_FinishSession](#oh_huks_finishsession), and [OH_Huks_AbortSession](#oh_huks_abortsession). | -| challenge | Indicates the pointer to the challenge value obtained. | +| keyAlias | Indicates the pointer to the alias of the target key. | +| paramSet | Indicates the pointer to the parameters for the initialization operation. | +| handle | Indicates the pointer to the handle of the key session. This handle is required for subsequent operations of the same key, including [OH_Huks_UpdateSession](#oh_huks_updatesession), [OH_Huks_FinishSession](#oh_huks_finishsession), and [OH_Huks_AbortSession](#oh_huks_abortsession). | +| token | Indicates the pointer to the token used for key access control. | **Returns** Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. - **See** +**See** [OH_Huks_UpdateSession](#oh_huks_updatesession) @@ -310,52 +320,50 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_IsKeyItemExist() - + ``` struct OH_Huks_Result OH_Huks_IsKeyItemExist (const struct OH_Huks_Blob * keyAlias, const struct OH_Huks_ParamSet * paramSet ) ``` -**Description**
+**Description** + Checks whether a key exists. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| keyAlias | Indicates the pointer to the alias of the target key. | -| paramSet | Indicates the pointer to the attribute tag required for checking the key. By default, this parameter is a null pointer. | +| keyAlias | Indicates the pointer to the alias of the key to check. | +| paramSet | Indicates the pointer to the parameters required for checking the key. By default, this parameter is a null pointer. | **Returns** -Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the key exists. - -Returns [OH_Huks_ErrCode#OH_HUKS_ERR_CODE_ITEM_NOT_EXIST](_huks_type_api.md) if the key does not exist. - -Returns any other error code for other cases. +Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the key exists.
Returns [OH_Huks_ErrCode#OH_HUKS_ERR_CODE_ITEM_NOT_EXIST](_huks_type_api.md) if the key does not exist.
Returns any other error code for other cases. ### OH_Huks_UpdateSession() - + ``` struct OH_Huks_Result OH_Huks_UpdateSession (const struct OH_Huks_Blob * handle, const struct OH_Huks_ParamSet * paramSet, const struct OH_Huks_Blob * inData, struct OH_Huks_Blob * outData ) ``` -**Description**
+**Description** + Adds data by segment for the key operation, performs the related key operation, and outputs the processed data. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| handle | Indicates the pointer to the key session handle, which is generated by [OH_Huks_InitSession](#oh_huks_initsession). | -| paramSet | Indicates the pointer to the parameters required for the key operation. | -| inData | Indicates the pointer to the data to be processed. This API can be called multiples time to process large data by segment. | -| outData | Indicates the pointer to the output data. | +| handle | Indicates the pointer to the key session handle, which is generated by [OH_Huks_InitSession](#oh_huks_initsession). | +| paramSet | Indicates the pointer to the parameters required for the key operation. | +| inData | Indicates the pointer to the data to be processed. This API can be called multiple times to process large data by segment. | +| outData | Indicates the pointer to the output data. | **Returns** Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. - **See** +**See** [OH_Huks_InitSession](#oh_huks_initsession) diff --git a/en/application-dev/reference/native-apis/_huks_param_set_api.md b/en/application-dev/reference/native-apis/_huks_param_set_api.md index f04d09f0c48991b4371394a09e97cfeb4a25eeda..dd80b661759f8d304159ad4422b89ec35f3d6767 100644 --- a/en/application-dev/reference/native-apis/_huks_param_set_api.md +++ b/en/application-dev/reference/native-apis/_huks_param_set_api.md @@ -3,11 +3,11 @@ ## Overview -Defines the capabilities of OpenHarmony Universal KeyStore (HUKS) parameter sets. The HUKS APIs can be used to perform parameter set lifecycle management, including initializing a parameter set, adding parameters to a parameter set, constructing a parameter set, and destroying a parameter set. They can also be used to obtain parameters, copy parameter sets, and check parameter validity. +Defines HUKS parameter set management capabilities, including HUKS parameter set lifecycle management such as initializing a parameter set, adding parameters, building a parameter set, and freeing a parameter set, as well as functions such as obtaining parameters, copying a parameter set, querying a parameter set, and checking the validity of a parameter set. \@syscap SystemCapability.Security.Huks -**Since:** + **Since**: 9 @@ -16,25 +16,25 @@ Defines the capabilities of OpenHarmony Universal KeyStore (HUKS) parameter sets ### Files -| Name | Description | +| Name| Description| | -------- | -------- | -| [native_huks_param.h](native__huks__param_8h.md) | Provides APIs for constructing, using, and destroying parameter sets.
File to Include: | +| [native_huks_param.h](native__huks__param_8h.md) | Provides APIs for constructing, using, and destroying parameter sets.
**File to include**:
**Library**: libhuks_ndk.z.so| ### Functions -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Huks_InitParamSet](#oh_huks_initparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Initializes a parameter set. | -| [OH_Huks_AddParams](#oh_huks_addparams) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Param](_o_h___huks___param.md) \*params, uint32_t paramCnt) | Adds parameters to a parameter set. | -| [OH_Huks_BuildParamSet](#oh_huks_buildparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Constructs a parameter set. | -| [OH_Huks_FreeParamSet](#oh_huks_freeparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Destroys a parameter set. | -| [OH_Huks_CopyParamSet](#oh_huks_copyparamset) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*fromParamSet, uint32_t fromParamSetSize, struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Copies a parameter set (deep copy). | -| [OH_Huks_GetParam](#oh_huks_getparam) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, uint32_t tag, struct [OH_Huks_Param](_o_h___huks___param.md) \*\*param) | Obtains parameters from a parameter set. | -| [OH_Huks_FreshParamSet](#oh_huks_freshparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, bool isCopy) | Refreshes data of the **Blob** type in a parameter set. | -| [OH_Huks_isParamSetTagValid](#oh_huks_isparamsettagvalid) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Checks whether the parameters in a parameter set are valid. | -| [OH_Huks_isParamSetValid](#oh_huks_isparamsetvalid) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, uint32_t size) | Checks whether a parameter set is of the valid size. | -| [OH_Huks_CheckParamMatch](#oh_huks_checkparammatch) (const struct [OH_Huks_Param](_o_h___huks___param.md) \*baseParam, const struct [OH_Huks_Param](_o_h___huks___param.md) \*param) | Checks whether two parameters are the same. | +| [OH_Huks_InitParamSet](#oh_huks_initparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Initializes a parameter set. | +| [OH_Huks_AddParams](#oh_huks_addparams) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, const struct [OH_Huks_Param](_o_h___huks___param.md) \*params, uint32_t paramCnt) | Adds parameters to a parameter set. | +| [OH_Huks_BuildParamSet](#oh_huks_buildparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Builds a parameter set. | +| [OH_Huks_FreeParamSet](#oh_huks_freeparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Frees a parameter set. | +| [OH_Huks_CopyParamSet](#oh_huks_copyparamset) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*fromParamSet, uint32_t fromParamSetSize, struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*\*paramSet) | Copies a parameter set (deep copy). | +| [OH_Huks_GetParam](#oh_huks_getparam) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, uint32_t tag, struct [OH_Huks_Param](_o_h___huks___param.md) \*\*param) | Obtains a parameter from a parameter set. | +| [OH_Huks_FreshParamSet](#oh_huks_freshparamset) (struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, bool isCopy) | Refreshes data of the Blob type in a parameter set. | +| [OH_Huks_isParamSetTagValid](#oh_huks_isparamsettagvalid) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet) | Checks whether the parameters in a parameter set are valid. | +| [OH_Huks_isParamSetValid](#oh_huks_isparamsetvalid) (const struct [OH_Huks_ParamSet](_o_h___huks___param_set.md) \*paramSet, uint32_t size) | Checks whether a parameter set is of the valid size. | +| [OH_Huks_CheckParamMatch](#oh_huks_checkparammatch) (const struct [OH_Huks_Param](_o_h___huks___param.md) \*baseParam, const struct [OH_Huks_Param](_o_h___huks___param.md) \*param) | Checks whether two parameters are the same. | ## Function Description @@ -42,20 +42,21 @@ Defines the capabilities of OpenHarmony Universal KeyStore (HUKS) parameter sets ### OH_Huks_AddParams() - + ``` int32_t OH_Huks_AddParams (struct OH_Huks_ParamSet * paramSet, const struct OH_Huks_Param * params, uint32_t paramCnt ) ``` -**Description**
+**Description** + Adds parameters to a parameter set. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| paramSet | Indicates the pointer to the parameter set to which parameters are to be added. | -| params | Indicates the pointer to the array of parameters to add. | -| paramCnt | Indicates the number of parameters to add. | +| paramSet | Indicates the pointer to the parameter set to which parameters are to be added. | +| params | Indicates the pointer to an array of parameters to add. | +| paramCnt | Indicates the number of parameters to add. | **Returns** @@ -64,18 +65,19 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_BuildParamSet() - + ``` int32_t OH_Huks_BuildParamSet (struct OH_Huks_ParamSet ** paramSet) ``` -**Description**
-Constructs a parameter set. +**Description** - **Parameters** +Builds a parameter set. -| Name | Description | +**Parameters** + +| Name| Description| | -------- | -------- | -| paramSet | Indicates the double pointer to the parameter set to construct. | +| paramSet | Indicates the double pointer to the parameter set to build. | **Returns** @@ -84,19 +86,20 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_CheckParamMatch() - + ``` int32_t OH_Huks_CheckParamMatch (const struct OH_Huks_Param * baseParam, const struct OH_Huks_Param * param ) ``` -**Description**
+**Description** + Checks whether two parameters are the same. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| baseParam | Indicates the pointer to the first parameter. | -| param | Indicates the pointer to the second parameter. | +| baseParam | Indicates the pointer to the first parameter to compare. | +| param | Indicates the pointer to the second parameter to compare. | **Returns** @@ -105,20 +108,21 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the two paramete ### OH_Huks_CopyParamSet() - + ``` int32_t OH_Huks_CopyParamSet (const struct OH_Huks_ParamSet * fromParamSet, uint32_t fromParamSetSize, struct OH_Huks_ParamSet ** paramSet ) ``` -**Description**
+**Description** + Copies a parameter set (deep copy). - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| fromParamSet | Indicates the pointer to the parameter set to copy. | -| fromParamSetSize | Indicates the memory size occupied by the source parameter set. | -| paramSet | Indicates the double pointer to the new parameter set generated. | +| fromParamSet | Indicates the pointer to the parameter set to copy. | +| fromParamSetSize | Indicates the size of the memory occupied by the copied parameter set. | +| paramSet | Indicates the double pointer to the new parameter set generated. | **Returns** @@ -127,119 +131,125 @@ Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is ### OH_Huks_FreeParamSet() - + ``` void OH_Huks_FreeParamSet (struct OH_Huks_ParamSet ** paramSet) ``` -**Description**
-Destroys a parameter set. +**Description** - **Parameters** +Frees a parameter set. -| Name | Description | +**Parameters** + +| Name| Description| | -------- | -------- | -| paramSet | Indicates the double pointer to the parameter set to destroy. | +| paramSet | Indicates the pointer to the parameter set to free. | ### OH_Huks_FreshParamSet() - + ``` int32_t OH_Huks_FreshParamSet (struct OH_Huks_ParamSet * paramSet, bool isCopy ) ``` -**Description**
-Refreshes data of the **Blob** type in a parameter set. +**Description** + +Refreshes data of the Blob type in a parameter set. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| paramSet | Indicates the pointer to the target parameter set. | -| isCopy | Specifies whether to copy the data of the **Blob** type to the parameter set. If yes, the data of the **Blob** type will be copied to the parameter set. Otherwise, only the address of the **Blob** data will be refreshed. | +| paramSet | Indicates the pointer to the target parameter set. | +| isCopy | Specifies whether to copy the data of the HksBlob type to the parameter set. | **Returns** -Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if operation is successful; returns an error code otherwise. +Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. ### OH_Huks_GetParam() - + ``` int32_t OH_Huks_GetParam (const struct OH_Huks_ParamSet * paramSet, uint32_t tag, struct OH_Huks_Param ** param ) ``` -**Description**
-Obtains parameters from a parameter set. +**Description** + +Obtains a parameter from a parameter set. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| paramSet | Indicates the pointer to the target parameter set. | -| tag | Indicates the value of the parameter to be obtained. | -| param | Indicates the double pointer to the parameter obtained. | +| paramSet | Indicates the pointer to the target parameter set. | +| tag | Indicates the name of the parameter to obtain. | +| param | Indicates the double pointer to the obtained parameter. | **Returns** -Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful, returns an error code otherwise. +Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. ### OH_Huks_InitParamSet() - + ``` int32_t OH_Huks_InitParamSet (struct OH_Huks_ParamSet ** paramSet) ``` -**Description**
+**Description** + Initializes a parameter set. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| paramSet | Indicates the double pointer to the parameter set to initialize. | +| paramSet | Indicates the pointer to the parameter set to initialize. | **Returns** -Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the initialization is successful; returns an error code otherwise. +Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the operation is successful; returns an error code otherwise. ### OH_Huks_isParamSetTagValid() - + ``` int32_t OH_Huks_isParamSetTagValid (const struct OH_Huks_ParamSet * paramSet) ``` -**Description**
+**Description** + Checks whether the parameters in a parameter set are valid. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| paramSet | Indicates the pointer to the parameter set to check. | +| paramSet | Indicates the pointer to the parameter set to check. | **Returns** -Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the parameters in the parameter set are valid; returns other values if the parameter set has invalid, duplicate, or incorrect parameters. +Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the parameters in the parameter set are valid; returns an error code otherwise. ### OH_Huks_isParamSetValid() - + ``` int32_t OH_Huks_isParamSetValid (const struct OH_Huks_ParamSet * paramSet, uint32_t size ) ``` -**Description**
+**Description** + Checks whether a parameter set is of the valid size. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| paramSet | Indicates the pointer to the parameter set to check. | -| size | Indicates the memory size occupied by the parameter set. | +| paramSet | Indicates the pointer to the parameter set to check. | +| size | Indicates the memory size occupied by the parameter set. | **Returns** -Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the parameter set is of the valid size; returns an error code otherwise. +Returns [OH_Huks_ErrCode#OH_HUKS_SUCCESS](_huks_type_api.md) if the size of the parameter set is valid; returns an error code otherwise. diff --git a/en/application-dev/reference/native-apis/_o_h___native_x_component.md b/en/application-dev/reference/native-apis/_o_h___native_x_component.md index 37dd107c618fdd0f6ce9ce2f2e786387c407373d..9f9ceb24f000c898e0ad802f0df1f07a529ce681 100644 --- a/en/application-dev/reference/native-apis/_o_h___native_x_component.md +++ b/en/application-dev/reference/native-apis/_o_h___native_x_component.md @@ -3,117 +3,131 @@ ## Overview -Describes the surface and touch event held by the ArkUI XComponent, which can be used for the EGL/OpenGL ES and media data input and displayed on the ArkUI XComponent. +Describes the surface and touch event held by the ArkUI XComponent, which can be used for the EGL/OpenGL ES and media data input and displayed on the ArkUI XComponent. For details, see [XComponent Development](../../napi/xcomponent-guidelines.md) +**Since** -**Since:** 8 + ## Summary ### Files -| Name | Description | -| -------- | -------- | -| [native_interface_xcomponent.h](native__interface__xcomponent_8h.md) | Declare the APIs used to access the native XComponent.
File to Include: | +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| [native_interface_xcomponent.h](native__interface__xcomponent_8h.md) | Declares the APIs for accessing **NativeXComponent**.
File to include: <ace/xcomponent/native_interface_xcomponent.h> | +| [native_xcomponent_key_event.h](native__xcomponent__key__event_8h.md) | Declares the enums used to access **NativeXComponent** key events.
File to include: <ace/xcomponent/native_xcomponent_key_event.h> | ### Structs -| Name | Description | -| -------- | -------- | -| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | Describes the touch point of the touch event. | -| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | Describes the touch event. | -| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | Describes the mouse event. | -| [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) | Registers a callback for the surface lifecycle and touch event. | -| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | Registers a callback for the mouse event. | +| Name | Description | +| ---------------------------------------- | --------------------- | +| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | Describes the touch point of the touch event. | +| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | Describes the touch event. | +| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | Describes the mouse event. | +| [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) | Registers callbacks for the surface lifecycle and touch event.| +| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | Registers callbacks for the mouse event. | ### Types -| Name | Description | -| -------- | -------- | -| [OH_NativeXComponent](#oh_nativexcomponent) | Provides an encapsulated OH_NativeXComponent instance. | -| [OH_NativeXComponent_Callback](#oh_nativexcomponent_callback) | Registers a callback for the surface lifecycle and touch event. | -| [OH_NativeXComponent_MouseEvent_Callback](#oh_nativexcomponent_mouseevent_callback) | Registers a callback for the mouse event. | +| Name | Description | +| ---------------------------------------- | ------------------------------------ | +| [OH_NativeXComponent](#oh_nativexcomponent) | Provides an encapsulated **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_Callback](#oh_nativexcomponent_callback) | Registers callbacks for the surface lifecycle and touch event. | +| [OH_NativeXComponent_MouseEvent_Callback](#oh_nativexcomponent_mouseevent_callback) | Registers callbacks for the mouse event. | +| [OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) | Provides an encapsulated **OH_NativeXComponent_KeyEvent** instance.| ### Enums -| Name | Description | -| -------- | -------- | -| {OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0,
OH_NATIVEXCOMPONENT_RESULT_FAILED = -1,
OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2 } | [Enumerates](#anonymous-enum) the API access states. | -| [OH_NativeXComponent_TouchEventType](#oh_nativexcomponent_toucheventtype) {
OH_NATIVEXCOMPONENT_DOWN = 0,
OH_NATIVEXCOMPONENT_UP,
OH_NATIVEXCOMPONENT_MOVE,
OH_NATIVEXCOMPONENT_CANCEL,
OH_NATIVEXCOMPONENT_UNKNOWN } | Enumerates the touch event types. | -| [OH_NativeXComponent_TouchPointToolType](#oh_nativexcomponent_touchpointtooltype) {
OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN = 0,
OH_NATIVEXCOMPONENT_TOOL_TYPE_FINGER,
OH_NATIVEXCOMPONENT_TOOL_TYPE_PEN,
OH_NATIVEXCOMPONENT_TOOL_TYPE_RUBBER,
OH_NATIVEXCOMPONENT_TOOL_TYPE_BRUSH,
OH_NATIVEXCOMPONENT_TOOL_TYPE_PENCIL,
OH_NATIVEXCOMPONENT_TOOL_TYPE_AIRBRUSH,
OH_NATIVEXCOMPONENT_TOOL_TYPE_MOUSE,
OH_NATIVEXCOMPONENT_TOOL_TYPE_LENS } | Enumerates the contact point tool types. | -| [OH_NativeXComponent_EventSourceType](#oh_nativexcomponent_eventsourcetype) {
OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN = 0,
OH_NATIVEXCOMPONENT_SOURCE_TYPE_MOUSE, OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHSCREEN,
OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHPAD,
OH_NATIVEXCOMPONENT_SOURCE_TYPE_JOYSTICK} | Enumerates the source types of the touch event. | -| [OH_NativeXComponent_MouseEventAction](#oh_nativexcomponent_mouseeventaction) {
OH_NATIVEXCOMPONENT_MOUSE_NONE = 0,
OH_NATIVEXCOMPONENT_MOUSE_PRESS,
OH_NATIVEXCOMPONENT_MOUSE_RELEASE,
OH_NATIVEXCOMPONENT_MOUSE_MOVE } | Enumerates the mouse event actions. | -| [OH_NativeXComponent_MouseEventButton](#oh_nativexcomponent_mouseeventbutton) {
OH_NATIVEXCOMPONENT_NONE_BUTTON = 0,
OH_NATIVEXCOMPONENT_LEFT_BUTTON = 0x01,
OH_NATIVEXCOMPONENT_RIGHT_BUTTON = 0x02,
OH_NATIVEXCOMPONENT_MIDDLE_BUTTON = 0x04,
OH_NATIVEXCOMPONENT_BACK_BUTTON = 0x08,
OH_NATIVEXCOMPONENT_FORWARD_BUTTON = 0x10 } | Enumerates the mouse event buttons. | +| Name | Description | +| ---------------------------------------- | ---------- | +| { OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0, OH_NATIVEXCOMPONENT_RESULT_FAILED = -1, OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2 } | Enumerates the API access states.| +| [OH_NativeXComponent_TouchEventType](#oh_nativexcomponent_toucheventtype) {
OH_NATIVEXCOMPONENT_DOWN = 0, OH_NATIVEXCOMPONENT_UP, OH_NATIVEXCOMPONENT_MOVE, OH_NATIVEXCOMPONENT_CANCEL,
OH_NATIVEXCOMPONENT_UNKNOWN
} | Enumerates the touch event types. | +| [OH_NativeXComponent_TouchPointToolType](#oh_nativexcomponent_touchpointtooltype) {
OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN = 0, OH_NATIVEXCOMPONENT_TOOL_TYPE_FINGER, OH_NATIVEXCOMPONENT_TOOL_TYPE_PEN, OH_NATIVEXCOMPONENT_TOOL_TYPE_RUBBER,
OH_NATIVEXCOMPONENT_TOOL_TYPE_BRUSH, OH_NATIVEXCOMPONENT_TOOL_TYPE_PENCIL, OH_NATIVEXCOMPONENT_TOOL_TYPE_AIRBRUSH, OH_NATIVEXCOMPONENT_TOOL_TYPE_MOUSE,
OH_NATIVEXCOMPONENT_TOOL_TYPE_LENS
} | Enumerates the touch point tool types. | +| [OH_NativeXComponent_EventSourceType](#oh_nativexcomponent_eventsourcetype) {
OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN = 0, OH_NATIVEXCOMPONENT_SOURCE_TYPE_MOUSE, OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHSCREEN, OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHPAD,
OH_NATIVEXCOMPONENT_SOURCE_TYPE_JOYSTICK, OH_NATIVEXCOMPONENT_SOURCE_TYPE_KEYBOARD
} | Enumerates the touch event source types. | +| [OH_NativeXComponent_MouseEventAction](#oh_nativexcomponent_mouseeventaction) { OH_NATIVEXCOMPONENT_MOUSE_NONE = 0, OH_NATIVEXCOMPONENT_MOUSE_PRESS, OH_NATIVEXCOMPONENT_MOUSE_RELEASE, OH_NATIVEXCOMPONENT_MOUSE_MOVE } | Enumerates the mouse event actions. | +| [OH_NativeXComponent_MouseEventButton](#oh_nativexcomponent_mouseeventbutton) {
OH_NATIVEXCOMPONENT_NONE_BUTTON = 0, OH_NATIVEXCOMPONENT_LEFT_BUTTON = 0x01, OH_NATIVEXCOMPONENT_RIGHT_BUTTON = 0x02, OH_NATIVEXCOMPONENT_MIDDLE_BUTTON = 0x04,
OH_NATIVEXCOMPONENT_BACK_BUTTON = 0x08, OH_NATIVEXCOMPONENT_FORWARD_BUTTON = 0x10
} | Enumerates the mouse event buttons. | +| [OH_NativeXComponent_KeyCode](#oh_nativexcomponent_keycode) {
KEY_UNKNOWN = -1, KEY_FN = 0, KEY_HOME = 1, KEY_BACK = 2,KEY_MEDIA_PLAY_PAUSE = 10, KEY_MEDIA_STOP = 11, KEY_MEDIA_NEXT = 12, KEY_MEDIA_PREVIOUS = 13,
KEY_MEDIA_REWIND = 14, KEY_MEDIA_FAST_FORWARD = 15, KEY_VOLUME_UP = 16, KEY_VOLUME_DOWN = 17,
KEY_POWER = 18, KEY_CAMERA = 19, KEY_VOLUME_MUTE = 22, KEY_MUTE = 23,KEY_BRIGHTNESS_UP = 40, KEY_BRIGHTNESS_DOWN = 41, KEY_0 = 2000, KEY_1 = 2001,
KEY_2 = 2002, KEY_3 = 2003, KEY_4 = 2004, KEY_5 = 2005,
KEY_6 = 2006, KEY_7 = 2007, KEY_8 = 2008, KEY_9 = 2009,
KEY_STAR = 2010, KEY_POUND = 2011, KEY_DPAD_UP = 2012, KEY_DPAD_DOWN = 2013,KEY_DPAD_LEFT = 2014, KEY_DPAD_RIGHT = 2015, KEY_DPAD_CENTER = 2016,
KEY_A = 2017,
KEY_B = 2018, KEY_C = 2019, KEY_D = 2020, KEY_E = 2021,
KEY_F = 2022, KEY_G = 2023, KEY_H = 2024, KEY_I = 2025,
KEY_J = 2026, KEY_K = 2027, KEY_L = 2028, KEY_M = 2029,
KEY_N = 2030, KEY_O = 2031, KEY_P = 2032, KEY_Q = 2033,
KEY_R = 2034, KEY_S = 2035, KEY_T = 2036, KEY_U = 2037,
KEY_V = 2038, KEY_W = 2039, KEY_X = 2040, KEY_Y = 2041,
KEY_Z = 2042, KEY_COMMA = 2043, KEY_PERIOD = 2044, KEY_ALT_LEFT = 2045,
KEY_ALT_RIGHT = 2046, KEY_SHIFT_LEFT = 2047, KEY_SHIFT_RIGHT = 2048, KEY_TAB = 2049,
KEY_SPACE = 2050, KEY_SYM = 2051, KEY_EXPLORER = 2052, KEY_ENVELOPE = 2053,
KEY_ENTER = 2054, KEY_DEL = 2055, KEY_GRAVE = 2056, KEY_MINUS = 2057,
KEY_EQUALS = 2058, KEY_LEFT_BRACKET = 2059, KEY_RIGHT_BRACKET = 2060, KEY_BACKSLASH = 2061,
KEY_SEMICOLON = 2062, KEY_APOSTROPHE = 2063, KEY_SLASH = 2064, KEY_AT = 2065,
KEY_PLUS = 2066, KEY_MENU = 2067, KEY_PAGE_UP = 2068, KEY_PAGE_DOWN = 2069,
KEY_ESCAPE = 2070, KEY_FORWARD_DEL = 2071, KEY_CTRL_LEFT = 2072, KEY_CTRL_RIGHT = 2073,
KEY_CAPS_LOCK = 2074, KEY_SCROLL_LOCK = 2075, KEY_META_LEFT = 2076, KEY_META_RIGHT = 2077,
KEY_FUNCTION = 2078, KEY_SYSRQ = 2079, KEY_BREAK = 2080, KEY_MOVE_HOME = 2081,
KEY_MOVE_END = 2082, KEY_INSERT = 2083, KEY_FORWARD = 2084, KEY_MEDIA_PLAY = 2085,
KEY_MEDIA_PAUSE = 2086, KEY_MEDIA_CLOSE = 2087, KEY_MEDIA_EJECT = 2088, KEY_MEDIA_RECORD = 2089,
KEY_F1 = 2090, KEY_F2 = 2091, KEY_F3 = 2092, KEY_F4 = 2093,
KEY_F5 = 2094, KEY_F6 = 2095, KEY_F7 = 2096, KEY_F8 = 2097,
KEY_F9 = 2098, KEY_F10 = 2099, KEY_F11 = 2100, KEY_F12 = 2101,
KEY_NUM_LOCK = 2102, KEY_NUMPAD_0 = 2103, KEY_NUMPAD_1 = 2104, KEY_NUMPAD_2 = 2105,
KEY_NUMPAD_3 = 2106, KEY_NUMPAD_4 = 2107, KEY_NUMPAD_5 = 2108, KEY_NUMPAD_6 = 2109,
KEY_NUMPAD_7 = 2110, KEY_NUMPAD_8 = 2111, KEY_NUMPAD_9 = 2112, KEY_NUMPAD_DIVIDE = 2113,
KEY_NUMPAD_MULTIPLY = 2114, KEY_NUMPAD_SUBTRACT = 2115, KEY_NUMPAD_ADD = 2116, KEY_NUMPAD_DOT = 2117,
KEY_NUMPAD_COMMA = 2118, KEY_NUMPAD_ENTER = 2119, KEY_NUMPAD_EQUALS = 2120, KEY_NUMPAD_LEFT_PAREN = 2121,
KEY_NUMPAD_RIGHT_PAREN = 2122, KEY_VIRTUAL_MULTITASK = 2210, KEY_SLEEP = 2600, KEY_ZENKAKU_HANKAKU = 2601,
KEY_102ND = 2602, KEY_RO = 2603, KEY_KATAKANA = 2604, KEY_HIRAGANA = 2605,
KEY_HENKAN = 2606, KEY_KATAKANA_HIRAGANA = 2607, KEY_MUHENKAN = 2608, KEY_LINEFEED = 2609,
KEY_MACRO = 2610, KEY_NUMPAD_PLUSMINUS = 2611, KEY_SCALE = 2612, KEY_HANGUEL = 2613,
KEY_HANJA = 2614, KEY_YEN = 2615, KEY_STOP = 2616, KEY_AGAIN = 2617,
KEY_PROPS = 2618, KEY_UNDO = 2619, KEY_COPY = 2620, KEY_OPEN = 2621,
KEY_PASTE = 2622, KEY_FIND = 2623, KEY_CUT = 2624, KEY_HELP = 2625,
KEY_CALC = 2626, KEY_FILE = 2627, KEY_BOOKMARKS = 2628, KEY_NEXT = 2629,
KEY_PLAYPAUSE = 2630, KEY_PREVIOUS = 2631, KEY_STOPCD = 2632, KEY_CONFIG = 2634,
KEY_REFRESH = 2635, KEY_EXIT = 2636, KEY_EDIT = 2637, KEY_SCROLLUP = 2638,
KEY_SCROLLDOWN = 2639, KEY_NEW = 2640, KEY_REDO = 2641, KEY_CLOSE = 2642,
KEY_PLAY = 2643, KEY_BASSBOOST = 2644, KEY_PRINT = 2645, KEY_CHAT = 2646,
KEY_FINANCE = 2647, KEY_CANCEL = 2648, KEY_KBDILLUM_TOGGLE = 2649, KEY_KBDILLUM_DOWN = 2650,
KEY_KBDILLUM_UP = 2651, KEY_SEND = 2652, KEY_REPLY = 2653, KEY_FORWARDMAIL = 2654,
KEY_SAVE = 2655, KEY_DOCUMENTS = 2656, KEY_VIDEO_NEXT = 2657, KEY_VIDEO_PREV = 2658,
KEY_BRIGHTNESS_CYCLE = 2659, KEY_BRIGHTNESS_ZERO = 2660, KEY_DISPLAY_OFF = 2661, KEY_BTN_MISC = 2662,
KEY_GOTO = 2663, KEY_INFO = 2664, KEY_PROGRAM = 2665, KEY_PVR = 2666,
KEY_SUBTITLE = 2667, KEY_FULL_SCREEN = 2668, KEY_KEYBOARD = 2669, KEY_ASPECT_RATIO = 2670,
KEY_PC = 2671, KEY_TV = 2672, KEY_TV2 = 2673, KEY_VCR = 2674,
KEY_VCR2 = 2675, KEY_SAT = 2676, KEY_CD = 2677, KEY_TAPE = 2678,
KEY_TUNER = 2679, KEY_PLAYER = 2680, KEY_DVD = 2681, KEY_AUDIO = 2682,
KEY_VIDEO = 2683, KEY_MEMO = 2684, KEY_CALENDAR = 2685, KEY_RED = 2686,
KEY_GREEN = 2687, KEY_YELLOW = 2688, KEY_BLUE = 2689, KEY_CHANNELUP = 2690,
KEY_CHANNELDOWN = 2691, KEY_LAST = 2692, KEY_RESTART = 2693, KEY_SLOW = 2694,
KEY_SHUFFLE = 2695, KEY_VIDEOPHONE = 2696, KEY_GAMES = 2697, KEY_ZOOMIN = 2698,
KEY_ZOOMOUT = 2699, KEY_ZOOMRESET = 2700, KEY_WORDPROCESSOR = 2701, KEY_EDITOR = 2702,
KEY_SPREADSHEET = 2703, KEY_GRAPHICSEDITOR = 2704, KEY_PRESENTATION = 2705, KEY_DATABASE = 2706,
KEY_NEWS = 2707, KEY_VOICEMAIL = 2708, KEY_ADDRESSBOOK = 2709, KEY_MESSENGER = 2710,
KEY_BRIGHTNESS_TOGGLE = 2711, KEY_SPELLCHECK = 2712, KEY_COFFEE = 2713, KEY_MEDIA_REPEAT = 2714,
KEY_IMAGES = 2715, KEY_BUTTONCONFIG = 2716, KEY_TASKMANAGER = 2717, KEY_JOURNAL = 2718,
KEY_CONTROLPANEL = 2719, KEY_APPSELECT = 2720, KEY_SCREENSAVER = 2721, KEY_ASSISTANT = 2722,
KEY_KBD_LAYOUT_NEXT = 2723, KEY_BRIGHTNESS_MIN = 2724, KEY_BRIGHTNESS_MAX = 2725, KEY_KBDINPUTASSIST_PREV = 2726,
KEY_KBDINPUTASSIST_NEXT = 2727, KEY_KBDINPUTASSIST_PREVGROUP = 2728, KEY_KBDINPUTASSIST_NEXTGROUP = 2729, KEY_KBDINPUTASSIST_ACCEPT = 2730,
KEY_KBDINPUTASSIST_CANCEL = 2731, KEY_FRONT = 2800, KEY_SETUP = 2801, KEY_WAKEUP = 2802,
KEY_SENDFILE = 2803, KEY_DELETEFILE = 2804, KEY_XFER = 2805, KEY_PROG1 = 2806,
KEY_PROG2 = 2807, KEY_MSDOS = 2808, KEY_SCREENLOCK = 2809, KEY_DIRECTION_ROTATE_DISPLAY = 2810,
KEY_CYCLEWINDOWS = 2811, KEY_COMPUTER = 2812, KEY_EJECTCLOSECD = 2813, KEY_ISO = 2814,
KEY_MOVE = 2815, KEY_F13 = 2816, KEY_F14 = 2817, KEY_F15 = 2818,
KEY_F16 = 2819, KEY_F17 = 2820, KEY_F18 = 2821, KEY_F19 = 2822,
KEY_F20 = 2823, KEY_F21 = 2824, KEY_F22 = 2825, KEY_F23 = 2826,
KEY_F24 = 2827, KEY_PROG3 = 2828, KEY_PROG4 = 2829, KEY_DASHBOARD = 2830,
KEY_SUSPEND = 2831, KEY_HP = 2832, KEY_SOUND = 2833, KEY_QUESTION = 2834,
KEY_CONNECT = 2836, KEY_SPORT = 2837, KEY_SHOP = 2838, KEY_ALTERASE = 2839,
KEY_SWITCHVIDEOMODE = 2841, KEY_BATTERY = 2842, KEY_BLUETOOTH = 2843, KEY_WLAN = 2844,
KEY_UWB = 2845, KEY_WWAN_WIMAX = 2846, KEY_RFKILL = 2847, KEY_CHANNEL = 3001,
KEY_BTN_0 = 3100, KEY_BTN_1 = 3101, KEY_BTN_2 = 3102, KEY_BTN_3 = 3103,
KEY_BTN_4 = 3104, KEY_BTN_5 = 3105, KEY_BTN_6 = 3106, KEY_BTN_7 = 3107,
KEY_BTN_8 = 3108, KEY_BTN_9 = 3109
} | Enumerates the mouse event key codes. | +| [OH_NativeXComponent_KeyAction](#oh_nativexcomponent_keyaction) { OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN = -1, OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN = 0, OH_NATIVEXCOMPONENT_KEY_ACTION_UP } | Enumerates the key event actions. | ### Functions -| Name | Description | -| -------- | -------- | -| [OH_NativeXComponent_GetXComponentId](#oh_nativexcomponent_getxcomponentid) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, char \*id, uint64_t \*size) | Obtains the ID of the ArkUI XComponent. | -| [OH_NativeXComponent_GetXComponentSize](#oh_nativexcomponent_getxcomponentsize) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, uint64_t \*width, uint64_t \*height) | Obtains the size of the surface held by the ArkUI XComponent. | -| [OH_NativeXComponent_GetXComponentOffset](#oh_nativexcomponent_getxcomponentoffset) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, double \*x, double \*y) | Obtains the offset of the ArkUI XComponent relative to the upper left vertex of the screen. | -| [OH_NativeXComponent_GetTouchEvent](#oh_nativexcomponent_gettouchevent) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) \*touchEvent) | Obtains the touch event scheduled by the ArkUI XComponent. | -| [OH_NativeXComponent_GetTouchPointToolType](#oh_nativexcomponent_gettouchpointtooltype) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, [OH_NativeXComponent_TouchPointToolType](#oh_nativexcomponent_touchpointtooltype) \*toolType) | Obtains the ArkUI XComponent touch point tool type. | -| [OH_NativeXComponent_GetTouchPointTiltX](#oh_nativexcomponent_gettouchpointtiltx) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltX) | Obtains the angle between the tilt of the ArkUI XComponent touch point and the x-axis. | -| [OH_NativeXComponent_GetTouchPointTiltY](#oh_nativexcomponent_gettouchpointtilty) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltY) | Obtains the angle between the tilt of the ArkUI XComponent touch point and the y-axis. | -| [OH_NativeXComponent_GetMouseEvent](#oh_nativexcomponent_getmouseevent) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) \*mouseEvent) | Obtains the mouse event scheduled by ArkUI XComponent. | -| [OH_NativeXComponent_RegisterCallback](#oh_nativexcomponent_registercallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) \*callback) | Registers a callback for this **OH_NativeXComponent** instance. | -| [OH_NativeXComponent_RegisterMouseEventCallback](#oh_nativexcomponent_registermouseeventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) \*callback) | Registers a mouse event callback for this **OH_NativeXComponent** instance. | +| Name | Description | +| ---------------------------------------- | -------------------------------------- | +| [OH_NativeXComponent_GetXComponentId](#oh_nativexcomponent_getxcomponentid) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, char \*id, uint64_t \*size) | Obtains the ID of the ArkUI XComponent. | +| [OH_NativeXComponent_GetXComponentSize](#oh_nativexcomponent_getxcomponentsize) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, uint64_t \*width, uint64_t \*height) | Obtains the size of the surface held by the ArkUI XComponent. | +| [OH_NativeXComponent_GetXComponentOffset](#oh_nativexcomponent_getxcomponentoffset) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, double \*x, double \*y) | Obtains the offset of the ArkUI XComponent relative to the upper left vertex of the screen.| +| [OH_NativeXComponent_GetTouchEvent](#oh_nativexcomponent_gettouchevent) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) \*touchEvent) | Obtains the touch event scheduled by the ArkUI XComponent. | +| [OH_NativeXComponent_GetTouchPointToolType](#oh_nativexcomponent_gettouchpointtooltype) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, [OH_NativeXComponent_TouchPointToolType](#oh_nativexcomponent_touchpointtooltype) \*toolType) | Obtains the ArkUI XComponent touch point tool type. | +| [OH_NativeXComponent_GetTouchPointTiltX](#oh_nativexcomponent_gettouchpointtiltx) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltX) | Obtains the angle between the Y-Z plane of the ArkUI XComponent touch point and the x-axis. | +| [OH_NativeXComponent_GetTouchPointTiltY](#oh_nativexcomponent_gettouchpointtilty) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltY) | Obtains the angle between the X-Z plane of the ArkUI XComponent touch point and the y-axis. | +| [OH_NativeXComponent_GetMouseEvent](#oh_nativexcomponent_getmouseevent) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) \*mouseEvent) | Obtains the mouse event scheduled by ArkUI XComponent. | +| [OH_NativeXComponent_RegisterCallback](#oh_nativexcomponent_registercallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) \*callback) | Registers a callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterMouseEventCallback](#oh_nativexcomponent_registermouseeventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) \*callback) | Registers the mouse event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterFocusEventCallback](#oh_nativexcomponent_registerfocuseventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](#oh_nativexcomponent) \*component, void \*window)) | Registers the focus obtaining event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterKeyEventCallback](#oh_nativexcomponent_registerkeyeventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](#oh_nativexcomponent) \*component, void \*window)) | Registers the key event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterBlurEventCallback](#oh_nativexcomponent_registerblureventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](#oh_nativexcomponent) \*component, void \*window)) | Registers the focus loss event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_GetKeyEvent](#oh_nativexcomponent_getkeyevent) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*\*keyEvent) | Obtains the key event scheduled by the ArkUI XComponent. | +| [OH_NativeXComponent_GetKeyEventAction](#oh_nativexcomponent_getkeyeventaction) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_KeyAction](#oh_nativexcomponent_keyaction) \*action) | Obtains the action of the specified key event. | +| [OH_NativeXComponent_GetKeyEventCode](#oh_nativexcomponent_getkeyeventcode) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_KeyCode](#oh_nativexcomponent_keycode) \*code) | Obtains the key code of the specified key event. | +| [OH_NativeXComponent_GetKeyEventSourceType](#oh_nativexcomponent_getkeyeventsourcetype) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_EventSourceType](#oh_nativexcomponent_eventsourcetype) \*sourceType) | Obtains the source type of the specified key event. | +| [OH_NativeXComponent_GetKeyEventDeviceId](#oh_nativexcomponent_getkeyeventdeviceid) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, int64_t \*deviceId) | Obtains the device ID of the specified key event. | +| [OH_NativeXComponent_GetKeyEventTimeStamp](#oh_nativexcomponent_getkeyeventtimestamp) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, int64_t \*timeStamp) | Obtains the timestamp of the specified key event. | ### Variables -| Name | Description | -| -------- | -------- | -| [OH_XCOMPONENT_ID_LEN_MAX](#oh_xcomponent_id_len_max) = 128 | Maximum length of an ArkUI XComponent ID. | -| [OH_MAX_TOUCH_POINTS_NUMBER](#oh_max_touch_points_number) = 10 | Maximum number of identifiable touch points in a touch event. | -| [OH_NativeXComponent_TouchPoint::id](#id-12) = 0 | Unique identifier of the finger. | -| [OH_NativeXComponent_TouchPoint::screenX](#screenx-13) = 0.0 | X coordinate of the touch point relative to the left edge of the screen. | -| [OH_NativeXComponent_TouchPoint::screenY](#screeny-13) = 0.0 | Y coordinate of the touch point relative to the left edge of the screen. | -| [OH_NativeXComponent_TouchPoint::x](#x-13) = 0.0 | X coordinate of the touch point relative to the left edge of the XComponent. | -| [OH_NativeXComponent_TouchPoint::y](#y-13) = 0.0 | Y coordinate of the touch point relative to the upper edge of the XComponent. | -| [OH_NativeXComponent_TouchPoint::type](#type-12) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | Touch type of the touch event. | -| [OH_NativeXComponent_TouchPoint::size](#size-12) = 0.0 | Contact area between the finger pad and the screen. | -| [OH_NativeXComponent_TouchPoint::force](#force-12) = 0.0 | Pressure of the current touch event. | -| [OH_NativeXComponent_TouchPoint::timeStamp](#timestamp-12) = 0 | Timestamp of the current touch event. | -| [OH_NativeXComponent_TouchPoint::isPressed](#ispressed) = false | Whether the current point is pressed. | -| [OH_NativeXComponent_TouchEvent::id](#id-22) = 0 | Unique identifier of the finger. | -| [OH_NativeXComponent_TouchEvent::screenX](#screenx-23) = 0.0 | X coordinate of the touch point relative to the left edge of the screen. | -| [OH_NativeXComponent_TouchEvent::screenY](#screeny-23) = 0.0 | Y coordinate of the touch point relative to the left edge of the screen. | -| [OH_NativeXComponent_TouchEvent::x](#x-23) = 0.0 | X coordinate of the touch point relative to the left edge of the XComponent. | -| [OH_NativeXComponent_TouchEvent::y](#y-23) = 0.0 | Y coordinate of the touch point relative to the upper edge of the XComponent. | -| [OH_NativeXComponent_TouchEvent::type](#type-22) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | Touch type of the touch event. | -| [OH_NativeXComponent_TouchEvent::size](#size-22) = 0.0 | Contact area between the finger pad and the screen. | -| [OH_NativeXComponent_TouchEvent::force](#force-22) = 0.0 | Pressure of the current touch event. | -| [OH_NativeXComponent_TouchEvent::deviceId](#deviceid) = 0 | ID of the device where the current touch event is triggered. | -| [OH_NativeXComponent_TouchEvent::timeStamp](#timestamp-22) = 0 | Timestamp of the current touch event. | -| [OH_NativeXComponent_TouchEvent::touchPoints](#touchpoints) [OH_MAX_TOUCH_POINTS_NUMBER] | Array of the current touch points. | -| [OH_NativeXComponent_TouchEvent::numPoints](#numpoints) = 0 | Number of current touch points. | -| [OH_NativeXComponent_MouseEvent::x](#x-33) = 0.0 | X coordinate of the clicked point relative to the upper left corner of the component. | -| [OH_NativeXComponent_MouseEvent::y](#y-33) = 0.0 | Y coordinate of the clicked point relative to the upper left corner of the component. | -| [OH_NativeXComponent_MouseEvent::screenX](#screenx-33) = 0.0 | X coordinate of the clicked point relative to the upper left corner of the screen. | -| [OH_NativeXComponent_MouseEvent::screenY](#screeny-33) = 0.0 | Y coordinate of the clicked point relative to the upper left corner of the screen. | -| [OH_NativeXComponent_MouseEvent::timestamp](#timestamp) = 0 | Timestamp of the current mouse event. | -| [OH_NativeXComponent_MouseEvent::action](#action) = [OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE](#oh_nativexcomponent_mouseeventaction) | Current mouse event action. | -| [OH_NativeXComponent_MouseEvent::button](#button) = [OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON](#oh_nativexcomponent_mouseeventbutton) | Mouse event button | -| [OH_NativeXComponent_Callback::OnSurfaceCreated](#onsurfacecreated) | Invoked when a surface is created. | -| [OH_NativeXComponent_Callback::OnSurfaceChanged](#onsurfacechanged) | Invoked when the surface changes. | -| [OH_NativeXComponent_Callback::OnSurfaceDestroyed](#onsurfacedestroyed) | Invoked when the surface is destroyed. | -| [OH_NativeXComponent_Callback::DispatchTouchEvent](#dispatchtouchevent) | Invoked when a touch event is triggered. | -| [OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent](#dispatchmouseevent) | Invoked when a mouse event is triggered. | -| [OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent](#dispatchhoverevent) | Invoked when a hover event is triggered. | +| Name | Description | +| ---------------------------------------- | ------------------------------ | +| **OH_XCOMPONENT_ID_LEN_MAX** = 128 | Maximum length of the ArkUI XComponent ID. | +| **OH_MAX_TOUCH_POINTS_NUMBER** = 10 | Maximum number of identifiable touch points in a touch event. | +| [OH_NativeXComponent_TouchPoint::id](#id-12) = 0 | Unique identifier of the finger. | +| [OH_NativeXComponent_TouchPoint::screenX](#screenx-13) = 0.0 | X coordinate of the touch point relative to the left edge of the application window where the XComponent is located.| +| [OH_NativeXComponent_TouchPoint::screenY](#screeny-13) = 0.0 | Y coordinate of the touch point relative to the left edge of the application window where the XComponent is located.| +| [OH_NativeXComponent_TouchPoint::x](#x-13) = 0.0 | X coordinate of the touch point relative to the left edge of the XComponent. | +| [OH_NativeXComponent_TouchPoint::y](#y-13) = 0.0 | Y coordinate of the touch point relative to the upper edge of the XComponent. | +| [OH_NativeXComponent_TouchPoint::type](#type-12) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | Touch type of the touch event. | +| [OH_NativeXComponent_TouchPoint::size](#size-12) = 0.0 | Contact area between the finger pad and the screen. | +| [OH_NativeXComponent_TouchPoint::force](#force-12) = 0.0 | Pressure of the touch event. | +| [OH_NativeXComponent_TouchPoint::timeStamp](#timestamp-12) = 0 | Timestamp of the touch point. | +| [OH_NativeXComponent_TouchPoint::isPressed](#ispressed) = false | Whether the current point is pressed. | +| [OH_NativeXComponent_TouchEvent::id](#id-22) = 0 | Unique identifier of the finger. | +| [OH_NativeXComponent_TouchEvent::screenX](#screenx-23) = 0.0 | X coordinate of the touch point relative to the left edge of the screen. | +| [OH_NativeXComponent_TouchEvent::screenY](#screeny-23) = 0.0 | Y coordinate of the touch point relative to the upper edge of the screen. | +| [OH_NativeXComponent_TouchEvent::x](#x-23) = 0.0 | X coordinate of the touch point relative to the left edge of the XComponent. | +| [OH_NativeXComponent_TouchEvent::y](#y-23) = 0.0 | Y coordinate of the touch point relative to the upper edge of the XComponent. | +| [OH_NativeXComponent_TouchEvent::type](#type-22) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | Touch type of the touch event. | +| [OH_NativeXComponent_TouchEvent::size](#size-22) = 0.0 | Contact area between the finger pad and the screen. | +| [OH_NativeXComponent_TouchEvent::force](#force-22) = 0.0 | Pressure of the touch event. | +| [OH_NativeXComponent_TouchEvent::deviceId](#deviceid) = 0 | ID of the device where the current touch event is triggered. | +| [OH_NativeXComponent_TouchEvent::timeStamp](#timestamp-22) = 0 | Timestamp of the touch event. | +| [OH_NativeXComponent_TouchEvent::touchPoints](#touchpoints) [OH_MAX_TOUCH_POINTS_NUMBER] | Array of the touch points. | +| [OH_NativeXComponent_TouchEvent::numPoints](#numpoints) = 0 | Number of current touch points. | +| [OH_NativeXComponent_MouseEvent::x](#x-33) = 0.0 | X coordinate of the clicked point relative to the upper left corner of the component. | +| [OH_NativeXComponent_MouseEvent::y](#y-33)= 0.0 | Y coordinate of the clicked point relative to the upper left corner of the component. | +| [OH_NativeXComponent_MouseEvent::screenX](#screenx-33)= 0.0 | X coordinate of the clicked point relative to the upper left corner of the screen. | +| [OH_NativeXComponent_MouseEvent::screenY](#screeny-33)= 0.0 | Y coordinate of the clicked point relative to the upper left corner of the screen. | +| [OH_NativeXComponent_MouseEvent::timestamp](#timestamp)= 0 | Timestamp of the mouse event. | +| [OH_NativeXComponent_MouseEvent::action](#action)= [OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE](#oh_nativexcomponent_mouseeventaction) | Action of the mouse event. | +| [OH_NativeXComponent_MouseEvent::button](#button)= [OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON](#oh_nativexcomponent_mouseeventbutton) | Enumerates the mouse event buttons. | +| [OH_NativeXComponent_Callback::OnSurfaceCreated](#onsurfacecreated) | Invoked when a surface is created. | +| [OH_NativeXComponent_Callback::OnSurfaceChanged](#onsurfacechanged) | Invoked when the surface changes. | +| [OH_NativeXComponent_Callback::OnSurfaceDestroyed](#onsurfacedestroyed) | Invoked when the surface is destroyed. | +| [OH_NativeXComponent_Callback::DispatchTouchEvent](#dispatchtouchevent) | Invoked when a touch event is triggered. | +| [OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent](#dispatchmouseevent) | Invoked when a mouse event is triggered. | +| [OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent](#dispatchhoverevent) | Invoked when a hover event is triggered. | ## Type Description -### OH_NativeXComponent +### OH_NativeXComponent ``` typedef struct OH_NativeXComponent OH_NativeXComponent @@ -121,31 +135,44 @@ typedef struct OH_NativeXComponent OH_NativeXComponent **Description** -Provides an encapsulated OH_NativeXComponent instance. +Provides an encapsulated **OH_NativeXComponent** instance. -**Since:** +**Since** 8 ### OH_NativeXComponent_Callback - ``` typedef struct OH_NativeXComponent_Callback OH_NativeXComponent_Callback ``` **Description** -Registers a callback for the surface lifecycle and touch event. +Registers callbacks for the surface lifecycle and touch event. -**Since:** +**Since** 8 -### OH_NativeXComponent_MouseEvent_Callback +### OH_NativeXComponent_KeyEvent + +``` +typedef struct OH_NativeXComponent_KeyEvent OH_NativeXComponent_KeyEvent +``` + +**Description** + +Provides an encapsulated **OH_NativeXComponent_KeyEvent** instance. +**Since** + +10 + + +### OH_NativeXComponent_MouseEvent_Callback ``` typedef struct OH_NativeXComponent_MouseEvent_Callback OH_NativeXComponent_MouseEvent_Callback @@ -153,17 +180,17 @@ typedef struct OH_NativeXComponent_MouseEvent_Callback OH_NativeXComponent_Mouse **Description** -Registers a callback for the mouse event. +Registers callbacks for the mouse event. -**Since:** +**Since** 9 ## Enum Description -### anonymous enum +### anonymous enum ``` anonymous enum @@ -173,43 +200,411 @@ anonymous enum Enumerates the API access states. -| Name | Description | -| ---------------------------------------- | ---------- | -| OH_NATIVEXCOMPONENT_RESULT_SUCCESS | Success result. | -| OH_NATIVEXCOMPONENT_RESULT_FAILED | Failure. | -| OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER | Invalid parameter. | +| Value | Description | +| ---------------------------------------- | ----- | +| OH_NATIVEXCOMPONENT_RESULT_SUCCESS | Success.| +| OH_NATIVEXCOMPONENT_RESULT_FAILED | Failure.| +| OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER | Invalid parameter.| -**Since:** +**Since** 8 -### OH_NativeXComponent_EventSourceType -OH_NativeXComponent_EventSourceType +### OH_NativeXComponent_EventSourceType - ``` enum OH_NativeXComponent_EventSourceType ``` **Description** -Enumerates the source types of the touch event. +Enumerates the touch event source types. -| Name | Description | -| -------- | -------- | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN | Unknown source type. | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_MOUSE | Source that generates a mouse multi-touch event. | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHSCREEN | Source that generates a touchscreen multi-touch event. | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHPAD | Source that generates a touchpad multi-touch event. | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_JOYSTICK | Source that generates a joystick multi-touch event. | +| Value | Description | +| ---------------------------------------- | ------------------- | +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN | Unknown source type. | +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_MOUSE | Source that generates a mouse multi-click event. | +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHSCREEN | Source that generates a touchscreen multi-touch event.| +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHPAD | Source that generates a touchpad multi-touch event.| +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_JOYSTICK | Source that generates a joystick multi-touch event.| +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_KEYBOARD | Source that generates a key event. | -**Since:** +**Since** 9 -### OH_NativeXComponent_MouseEventAction +### OH_NativeXComponent_KeyAction + +``` +enum OH_NativeXComponent_KeyAction +``` + +**Description** + +Enumerates the key event actions. + +| Value | Description | +| -------------------------------------- | -------- | +| OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN | Unknown key event action.| +| OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN | Button press. | +| OH_NATIVEXCOMPONENT_KEY_ACTION_UP | Button release. | + +**Since** + +10 + + +### OH_NativeXComponent_KeyCode + +``` +enum OH_NativeXComponent_KeyCode +``` + +**Description** + +Enumerates the mouse event key codes. + +| Value | Description | +| ---------------------------- | --------------------------- | +| KEY_UNKNOWN | Unknown key. | +| KEY_FN | Function (Fn) key. | +| KEY_HOME | Function (Home) key. | +| KEY_BACK | Back key. | +| KEY_MEDIA_PLAY_PAUSE | Multimedia key - play/pause. | +| KEY_MEDIA_STOP | Multimedia key - stop. | +| KEY_MEDIA_NEXT | Multimedia key - next song. | +| KEY_MEDIA_PREVIOUS | Multimedia key - previous song. | +| KEY_MEDIA_REWIND | Multimedia key - rewind. | +| KEY_MEDIA_FAST_FORWARD | Multimedia key - fast-forward. | +| KEY_VOLUME_UP | Volume Up key. | +| KEY_VOLUME_DOWN | Volume Down key. | +| KEY_POWER | Power key. | +| KEY_CAMERA | Camera key. | +| KEY_VOLUME_MUTE | Speaker Mute key. | +| KEY_MUTE | Microphone Mute key. | +| KEY_BRIGHTNESS_UP | Brightness key - turn up. | +| KEY_BRIGHTNESS_DOWN | Brightness key - turn down. | +| KEY_0 | Key **0**. | +| KEY_1 | Key **1**. | +| KEY_2 | Key **2**. | +| KEY_3 | Key **3**. | +| KEY_4 | Key **4**. | +| KEY_5 | Key **5**. | +| KEY_6 | Key **6**. | +| KEY_7 | Key **7**. | +| KEY_8 | Key **8**. | +| KEY_9 | Key **9**. | +| KEY_STAR | Key **\***. | +| KEY_POUND | Key **\#**. | +| KEY_DPAD_UP | Navigation key - up. | +| KEY_DPAD_DOWN | Navigation key - down. | +| KEY_DPAD_LEFT | Navigation key - left. | +| KEY_DPAD_RIGHT | Navigation key - right. | +| KEY_DPAD_CENTER | Navigation key - OK. | +| KEY_A | Key **A**. | +| KEY_B | Key **B**. | +| KEY_C | Key **C**. | +| KEY_D | Key **D**. | +| KEY_E | Key **E**. | +| KEY_F | Key **F**. | +| KEY_G | Key **G**. | +| KEY_H | Key **H**. | +| KEY_I | Key **I**. | +| KEY_J | Key **J**. | +| KEY_K | Key **K**. | +| KEY_L | Key **L**. | +| KEY_M | Key **M**. | +| KEY_N | Key **N**. | +| KEY_O | Key **O**. | +| KEY_P | Key **P**. | +| KEY_Q | Key **Q**. | +| KEY_R | Key **R**. | +| KEY_S | Key **S**. | +| KEY_T | Key **T**. | +| KEY_U | Key **U**. | +| KEY_V | Key **V**. | +| KEY_W | Key **W**. | +| KEY_X | Key **X**. | +| KEY_Y | Key **Y**. | +| KEY_Z | Key **Z**. | +| KEY_COMMA | Key **,**. | +| KEY_PERIOD | Key **.**. | +| KEY_ALT_LEFT | Left Alt key. | +| KEY_ALT_RIGHT | Right Alt key. | +| KEY_SHIFT_LEFT | Left Shift key. | +| KEY_SHIFT_RIGHT | Right Shift key. | +| KEY_TAB | Tab key. | +| KEY_SPACE | Space key. | +| KEY_SYM | Symbol key. | +| KEY_EXPLORER | Explorer key, which is used to start the explorer application. | +| KEY_ENVELOPE | Email key, which is used to start the email application. | +| KEY_ENTER | Enter key. | +| KEY_DEL | Delete key. | +| KEY_GRAVE | Key **`**. | +| KEY_MINUS | Key **-**. | +| KEY_EQUALS | Key **=**. | +| KEY_LEFT_BRACKET | Key **[**. | +| KEY_RIGHT_BRACKET | Key **]**. | +| KEY_BACKSLASH | Key **\**. | +| KEY_SEMICOLON | Key **;**. | +| KEY_APOSTROPHE | Key **'**. | +| KEY_SLASH | Key **/**. | +| KEY_AT | Key **\@**. | +| KEY_PLUS | Key **+**. | +| KEY_MENU | Menu key. | +| KEY_PAGE_UP | Page Up key. | +| KEY_PAGE_DOWN | Page Down key. | +| KEY_ESCAPE | ESC key. | +| KEY_FORWARD_DEL | Delete key. | +| KEY_CTRL_LEFT | Left Ctrl key. | +| KEY_CTRL_RIGHT | Right Ctrl key. | +| KEY_CAPS_LOCK | Caps Lock key. | +| KEY_SCROLL_LOCK | Scroll Lock key. | +| KEY_META_LEFT | Left Meta key. | +| KEY_META_RIGHT | Right Meta key. | +| KEY_FUNCTION | Function key. | +| KEY_SYSRQ | System Request/Print Screen key. | +| KEY_BREAK | Break/Pause key. | +| KEY_MOVE_HOME | Move to Home key. | +| KEY_MOVE_END | Move to End key. | +| KEY_INSERT | Insert key. | +| KEY_FORWARD | Forward key. | +| KEY_MEDIA_PLAY | Multimedia key - play. | +| KEY_MEDIA_PAUSE | Multimedia key - pause. | +| KEY_MEDIA_CLOSE | Multimedia key - close. | +| KEY_MEDIA_EJECT | Multimedia key - eject. | +| KEY_MEDIA_RECORD | Multimedia key - record. | +| KEY_F1 | F1 key. | +| KEY_F2 | F2 key. | +| KEY_F3 | F3 key. | +| KEY_F4 | F4 key. | +| KEY_F5 | F5 key. | +| KEY_F6 | F6 key. | +| KEY_F7 | F7 key. | +| KEY_F8 | F8 key. | +| KEY_F9 | F9 key. | +| KEY_F10 | F10 key. | +| KEY_F11 | F11 key. | +| KEY_F12 | F12 key. | +| KEY_NUM_LOCK | Number Lock key. | +| KEY_NUMPAD_0 | Key **0** on numeric keypad. | +| KEY_NUMPAD_1 | Key **1** on numeric keypad. | +| KEY_NUMPAD_2 | Key **2** on numeric keypad. | +| KEY_NUMPAD_3 | Key **3** on numeric keypad. | +| KEY_NUMPAD_4 | Key **4** on numeric keypad. | +| KEY_NUMPAD_5 | Key **5** on numeric keypad. | +| KEY_NUMPAD_6 | Key **6** on numeric keypad. | +| KEY_NUMPAD_7 | Key **7** on numeric keypad. | +| KEY_NUMPAD_8 | Key **8** on numeric keypad. | +| KEY_NUMPAD_9 | Key **9** on numeric keypad. | +| KEY_NUMPAD_DIVIDE | Key **/** on numeric keypad. | +| KEY_NUMPAD_MULTIPLY | Key ***** on numeric keypad. | +| KEY_NUMPAD_SUBTRACT | Key **-** on numeric keypad. | +| KEY_NUMPAD_ADD | Key **+** on numeric keypad. | +| KEY_NUMPAD_DOT | Key **.** on numeric keypad. | +| KEY_NUMPAD_COMMA | Key **,** on numeric keypad. | +| KEY_NUMPAD_ENTER | Enter key on numeric keypad. | +| KEY_NUMPAD_EQUALS | Key **=** on numeric keypad. | +| KEY_NUMPAD_LEFT_PAREN | Key **(** on numeric keypad. | +| KEY_NUMPAD_RIGHT_PAREN | Key **)** on numeric keypad. | +| KEY_VIRTUAL_MULTITASK | Multi-task key. | +| KEY_SLEEP | Sleep key. | +| KEY_ZENKAKU_HANKAKU | Zenkaku/Hankaku key. | +| KEY_102ND | 102nd key. | +| KEY_RO | Ro key. | +| KEY_KATAKANA | Katakana key. | +| KEY_HIRAGANA | Hiragana key. | +| KEY_HENKAN | Henkan key. | +| KEY_KATAKANA_HIRAGANA | Katakana/Hiragana key. | +| KEY_MUHENKAN | Muhenkan key. | +| KEY_LINEFEED | Linefeed key. | +| KEY_MACRO | Macro key. | +| KEY_NUMPAD_PLUSMINUS | Plus/Minus key on the numeric keypad. | +| KEY_SCALE | Scale key. | +| KEY_HANGUEL | Hanguel key. | +| KEY_HANJA | Hanja key. | +| KEY_YEN | Yen key. | +| KEY_STOP | Stop key. | +| KEY_AGAIN | Again key. | +| KEY_PROPS | Props key. | +| KEY_UNDO | Undo key. | +| KEY_COPY | Copy key. | +| KEY_OPEN | Open key. | +| KEY_PASTE | Paste key. | +| KEY_FIND | Find key. | +| KEY_CUT | Cut key. | +| KEY_HELP | Help key. | +| KEY_CALC | Calc key, which is used to start the calculator application. | +| KEY_FILE | File key. | +| KEY_BOOKMARKS | Bookmarks key. | +| KEY_NEXT | Next key. | +| KEY_PLAYPAUSE | Play/Pause key. | +| KEY_PREVIOUS | Previous key. | +| KEY_STOPCD | Stop CD key. | +| KEY_CONFIG | Config key. | +| KEY_REFRESH | Refresh key. | +| KEY_EXIT | Exit key. | +| KEY_EDIT | Edit key. | +| KEY_SCROLLUP | Scroll Up key. | +| KEY_SCROLLDOWN | Scroll Down key. | +| KEY_NEW | New key. | +| KEY_REDO | Redo key. | +| KEY_CLOSE | Close key. | +| KEY_PLAY | Play key. | +| KEY_BASSBOOST | Bass Boost key. | +| KEY_PRINT | Print key. | +| KEY_CHAT | Chat key. | +| KEY_FINANCE | Finance key. | +| KEY_CANCEL | Cancel key. | +| KEY_KBDILLUM_TOGGLE | Keyboard Illumination Toggle key. | +| KEY_KBDILLUM_DOWN | Keyboard Illumination Up key. | +| KEY_KBDILLUM_UP | Keyboard Illumination Down key. | +| KEY_SEND | Send key. | +| KEY_REPLY | Reply key. | +| KEY_FORWARDMAIL | Forward Mail key. | +| KEY_SAVE | Save key. | +| KEY_DOCUMENTS | Documents key. | +| KEY_VIDEO_NEXT | Next Video key. | +| KEY_VIDEO_PREV | Previous Video key. | +| KEY_BRIGHTNESS_CYCLE | Brightness Cycle key. | +| KEY_BRIGHTNESS_ZERO | Brightness Zero key. | +| KEY_DISPLAY_OFF | Display Off Key. | +| KEY_BTN_MISC | Misc Button key. | +| KEY_GOTO | Goto key. | +| KEY_INFO | Info key. | +| KEY_PROGRAM | Program key. | +| KEY_PVR | PVR key. | +| KEY_SUBTITLE | Subtitle key. | +| KEY_FULL_SCREEN | Full Screen key. | +| KEY_KEYBOARD | Keyboard. | +| KEY_ASPECT_RATIO | Aspect Ratio key. | +| KEY_PC | Port Control key. | +| KEY_TV | TV key. | +| KEY_TV2 | TV key 2. | +| KEY_VCR | VCR key. | +| KEY_VCR2 | VCR key 2. | +| KEY_SAT | SAT key. | +| KEY_CD | CD key. | +| KEY_TAPE | Tape key. | +| KEY_TUNER | Tuner key. | +| KEY_PLAYER | Player key. | +| KEY_DVD | DVD key. | +| KEY_AUDIO | Audio key. | +| KEY_VIDEO | Video key. | +| KEY_MEMO | Memo key. | +| KEY_CALENDAR | Calendar key. | +| KEY_RED | Red indicator. | +| KEY_GREEN | Green indicator. | +| KEY_YELLOW | Yellow indicator. | +| KEY_BLUE | Blue indicator. | +| KEY_CHANNELUP | Channel Up key. | +| KEY_CHANNELDOWN | Channel Down key. | +| KEY_LAST | Last key. | +| KEY_RESTART | Restart key. | +| KEY_SLOW | Slow key. | +| KEY_SHUFFLE | Shuffle key. | +| KEY_VIDEOPHONE | Videophone key. | +| KEY_GAMES | Games key. | +| KEY_ZOOMIN | Zoom in key. | +| KEY_ZOOMOUT | Zoom out key. | +| KEY_ZOOMRESET | Zoom Reset key. | +| KEY_WORDPROCESSOR | Word Processor key. | +| KEY_EDITOR | Editor key. | +| KEY_SPREADSHEET | Spreadsheet key. | +| KEY_GRAPHICSEDITOR | Graphics Editor key. | +| KEY_PRESENTATION | Presentation key. | +| KEY_DATABASE | Database key. | +| KEY_NEWS | News key. | +| KEY_VOICEMAIL | Voicemail key. | +| KEY_ADDRESSBOOK | Address book key. | +| KEY_MESSENGER | Messenger key. | +| KEY_BRIGHTNESS_TOGGLE | Brightness Toggle key. | +| KEY_SPELLCHECK | Spell Check key. | +| KEY_COFFEE | Coffee key, which is used to launch screen lock or screen saver. | +| KEY_MEDIA_REPEAT | Media Repeat key. | +| KEY_IMAGES | Images key. | +| KEY_BUTTONCONFIG | Button Configuration key. | +| KEY_TASKMANAGER | Task Manager key. | +| KEY_JOURNAL | Log key. | +| KEY_CONTROLPANEL | Control Panel key. | +| KEY_APPSELECT | App Select key. | +| KEY_SCREENSAVER | Screen Saver key. | +| KEY_ASSISTANT | Assistant key. | +| KEY_KBD_LAYOUT_NEXT | Next Keyboard Layout key. | +| KEY_BRIGHTNESS_MIN | Min Brightness key. | +| KEY_BRIGHTNESS_MAX | Max Brightness key. | +| KEY_KBDINPUTASSIST_PREV | Keyboard Input-assisted Previous key. | +| KEY_KBDINPUTASSIST_NEXT | Keyboard Input-assisted Next key. | +| KEY_KBDINPUTASSIST_PREVGROUP | Keyboard Input-assisted Previous key. | +| KEY_KBDINPUTASSIST_NEXTGROUP | Keyboard Input-assisted Next key. | +| KEY_KBDINPUTASSIST_ACCEPT | Keyboard Input-assisted Accept key. | +| KEY_KBDINPUTASSIST_CANCEL | Keyboard Input-assisted Cancel key. | +| KEY_FRONT | Front key, which is used to launch the windshield defogger. | +| KEY_SETUP | Setup key. | +| KEY_WAKEUP | Wakeup key. | +| KEY_SENDFILE | Send File key. | +| KEY_DELETEFILE | Delete File key. | +| KEY_XFER | XFER key, which is used to start file transfer. | +| KEY_PROG1 | Program key 1. | +| KEY_PROG2 | Program key 2. | +| KEY_MSDOS | MS-DOS key. | +| KEY_SCREENLOCK | Screen Lock key. | +| KEY_DIRECTION_ROTATE_DISPLAY | Directional Rotation Display key. | +| KEY_CYCLEWINDOWS | Windows Cycle key. | +| KEY_COMPUTER | Keys. | +| KEY_EJECTCLOSECD | Eject CD key. | +| KEY_ISO | ISO key. | +| KEY_MOVE | Move key. | +| KEY_F13 | F13 key. | +| KEY_F14 | F14 key. | +| KEY_F15 | F15 key. | +| KEY_F16 | F16 key. | +| KEY_F17 | F17 key. | +| KEY_F18 | F18 key. | +| KEY_F19 | F19 key. | +| KEY_F20 | F20 key. | +| KEY_F21 | F21 key. | +| KEY_F22 | F22 key. | +| KEY_F23 | F23 key. | +| KEY_F24 | F24 key. | +| KEY_PROG3 | Program key 3. | +| KEY_PROG4 | Program key 4. | +| KEY_DASHBOARD | Dashboard. | +| KEY_SUSPEND | Suspend key. | +| KEY_HP | HP key. | +| KEY_SOUND | Sound key. | +| KEY_QUESTION | Question key. | +| KEY_CONNECT | Connect key. | +| KEY_SPORT | Sport key. | +| KEY_SHOP | Shop key. | +| KEY_ALTERASE | Alternate key. | +| KEY_SWITCHVIDEOMODE | Switch Video Mode key (monitor, LCD, and TV, etc.).| +| KEY_BATTERY | Battery key. | +| KEY_BLUETOOTH | Bluetooth key. | +| KEY_WLAN | WLAN key. | +| KEY_UWB | Ultra-wideband key. | +| KEY_WWAN_WIMAX | WWAN WiMAX key. | +| KEY_RFKILL | RF Kill key. | +| KEY_CHANNEL | Channel key. | +| KEY_BTN_0 | Button 0. | +| KEY_BTN_1 | Button 1. | +| KEY_BTN_2 | Button 2. | +| KEY_BTN_3 | Button 3. | +| KEY_BTN_4 | Button 4. | +| KEY_BTN_5 | Button 5. | +| KEY_BTN_6 | Button 6. | +| KEY_BTN_7 | Button 7. | +| KEY_BTN_8 | Button 8. | +| KEY_BTN_9 | Button 9. | + +**Since** + +10 + + +### OH_NativeXComponent_MouseEventAction ``` enum OH_NativeXComponent_MouseEventAction @@ -219,21 +614,20 @@ enum OH_NativeXComponent_MouseEventAction Enumerates the mouse event actions. -| Name | Description | -| --------------------------------- | -------------------------------- | -| OH_NATIVEXCOMPONENT_MOUSE_NONE | Invalid mouse event. | -| OH_NATIVEXCOMPONENT_MOUSE_PRESS | The mouse event is triggered when a mouse button is pressed. | -| OH_NATIVEXCOMPONENT_MOUSE_RELEASE | The mouse event is triggered when a mouse button is released. | -| OH_NATIVEXCOMPONENT_MOUSE_MOVE | The mouse event is triggered when the mouse moves on the screen. | +| Value | Description | +| --------------------------------- | ---------------- | +| OH_NATIVEXCOMPONENT_MOUSE_NONE | Invalid mouse event. | +| OH_NATIVEXCOMPONENT_MOUSE_PRESS | Mouse button press. | +| OH_NATIVEXCOMPONENT_MOUSE_RELEASE | Mouse button release. | +| OH_NATIVEXCOMPONENT_MOUSE_MOVE | Mouse movement.| -**Since:** +**Since** 9 ### OH_NativeXComponent_MouseEventButton - ``` enum OH_NativeXComponent_MouseEventButton ``` @@ -242,23 +636,22 @@ enum OH_NativeXComponent_MouseEventButton Enumerates the mouse event buttons. -| Name | Description | -| ---------------------------------- | ---------------------------------- | -| OH_NATIVEXCOMPONENT_NONE_BUTTON | The mouse event is triggered when no mouse button is pressed. | -| OH_NATIVEXCOMPONENT_LEFT_BUTTON | The mouse event is triggered when the left mouse button is pressed. | -| OH_NATIVEXCOMPONENT_RIGHT_BUTTON | The mouse event is triggered when the right mouse button is pressed. | -| OH_NATIVEXCOMPONENT_MIDDLE_BUTTON | The mouse event is triggered when the middle mouse button is pressed. | -| OH_NATIVEXCOMPONENT_BACK_BUTTON | The mouse event is triggered when the back button on the left of the mouse is pressed. | -| OH_NATIVEXCOMPONENT_FORWARD_BUTTON | The mouse event is triggered when the forward button on the left of the mouse is pressed. | +| Value | Description | +| ---------------------------------- | ----------------- | +| OH_NATIVEXCOMPONENT_NONE_BUTTON | No button. | +| OH_NATIVEXCOMPONENT_LEFT_BUTTON | Left mouse button. | +| OH_NATIVEXCOMPONENT_RIGHT_BUTTON | Right mouse button. | +| OH_NATIVEXCOMPONENT_MIDDLE_BUTTON | Middle mouse button. | +| OH_NATIVEXCOMPONENT_BACK_BUTTON | Back button on the left of the mouse.| +| OH_NATIVEXCOMPONENT_FORWARD_BUTTON | Forward key on the left of the mouse.| -**Since:** +**Since** 9 ### OH_NativeXComponent_TouchEventType - ``` enum OH_NativeXComponent_TouchEventType ``` @@ -267,42 +660,42 @@ enum OH_NativeXComponent_TouchEventType Enumerates the touch event types. -| Name | Description | -| --------------------------- | ------------------------------------------ | -| OH_NATIVEXCOMPONENT_DOWN | The touch event is triggered when a finger is pressed. | -| OH_NATIVEXCOMPONENT_UP | The touch event is triggered when a finger is lifted. | -| OH_NATIVEXCOMPONENT_MOVE | The touch event is triggered when a finger is pressed and moves on the screen. | +| Value | Description | +| --------------------------- | --------------------- | +| OH_NATIVEXCOMPONENT_DOWN | The touch event is triggered when a finger is pressed. | +| OH_NATIVEXCOMPONENT_UP | The touch event is triggered when a finger is lifted. | +| OH_NATIVEXCOMPONENT_MOVE | The touch event is triggered when a finger is moved on the screen.| | OH_NATIVEXCOMPONENT_CANCEL | The event is triggered when a touch event is canceled. | -| OH_NATIVEXCOMPONENT_UNKNOWN | Invalid touch type. | +| OH_NATIVEXCOMPONENT_UNKNOWN | Invalid touch type. | -**Since:** +**Since** 8 + ### OH_NativeXComponent_TouchPointToolType - ``` enum OH_NativeXComponent_TouchPointToolType ``` **Description** -Enumerates the contact point tool types. +Enumerates the touch point tool types. -| Name | Description | -| -------- | -------- | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN | Unknown tool type. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_FINGER | Finger. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_PEN | Stylus. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_RUBBER | Eraser. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_BRUSH | Brush. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_PENCIL | Pencil. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_AIRBRUSH | Air brush. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_MOUSE | Mouse. | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_LENS | Lens. | +| Value | Description | +| -------------------------------------- | -------- | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN | Unknown tool type.| +| OH_NATIVEXCOMPONENT_TOOL_TYPE_FINGER | Finger. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_PEN | Stylus. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_RUBBER | Rubber. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_BRUSH | Brush. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_PENCIL | Pencil. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_AIRBRUSH | Air brush. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_MOUSE | Mouse. | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_LENS | Lens. | -**Since:** +**Since** 9 @@ -310,8 +703,163 @@ Enumerates the contact point tool types. ## Function Description -### OH_NativeXComponent_GetMouseEvent() +### OH_NativeXComponent_GetKeyEvent() + +``` +int32_t OH_NativeXComponent_GetKeyEvent (OH_NativeXComponent * component, OH_NativeXComponent_KeyEvent ** keyEvent ) +``` + +**Description** + +Obtains the key event scheduled by ArkUI XComponent. + +**Parameters** + +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| keyEvent | Pointer to the current key event. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 + + +### OH_NativeXComponent_GetKeyEventAction() + +``` +int32_t OH_NativeXComponent_GetKeyEventAction (OH_NativeXComponent_KeyEvent * keyEvent, OH_NativeXComponent_KeyAction * action ) +``` + +**Description** + +Obtains the action of the specified key event. + +**Parameters** + +| Name | Description | +| -------- | -------------------------------------- | +| keyEvent | Pointer to the **OH_NativeXComponent_KeyEvent** instance.| +| action | Pointer to the key event action. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 + + +### OH_NativeXComponent_GetKeyEventCode() + +``` +int32_t OH_NativeXComponent_GetKeyEventCode (OH_NativeXComponent_KeyEvent * keyEvent, OH_NativeXComponent_KeyCode * code ) +``` + +**Description** + +Obtains the key code of the specified key event. + +**Parameters** + +| Name | Description | +| -------- | -------------------------------------- | +| keyEvent | Pointer to the **OH_NativeXComponent_KeyEvent** instance.| +| code | Pointer to the key code of the key event. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 + + +### OH_NativeXComponent_GetKeyEventDeviceId() + +``` +int32_t OH_NativeXComponent_GetKeyEventDeviceId (OH_NativeXComponent_KeyEvent * keyEvent, int64_t * deviceId ) +``` + +**Description** + +Obtains the device ID of the specified key event. + +**Parameters** + +| Name | Description | +| -------- | -------------------------------------- | +| keyEvent | Pointer to the **OH_NativeXComponent_KeyEvent** instance.| +| deviceId | Pointer to the device ID of the key event. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 + + +### OH_NativeXComponent_GetKeyEventSourceType() + +``` +int32_t OH_NativeXComponent_GetKeyEventSourceType (OH_NativeXComponent_KeyEvent * keyEvent, OH_NativeXComponent_EventSourceType * sourceType ) +``` + +**Description** + +Obtains the source type of the specified key event. + +**Parameters** + +| Name | Description | +| ---------- | -------------------------------------- | +| keyEvent | Pointer to the **OH_NativeXComponent_KeyEvent** instance.| +| sourceType | Pointer to the source type of the key event. | + +**Returns** + +Returns the status code of the execution. +**Since** + +10 + + +### OH_NativeXComponent_GetKeyEventTimeStamp() + +``` +int32_t OH_NativeXComponent_GetKeyEventTimeStamp (OH_NativeXComponent_KeyEvent * keyEvent, int64_t * timeStamp ) +``` + +**Description** + +Obtains the timestamp of the specified key event. + +**Parameters** + +| Name | Description | +| --------- | -------------------------------------- | +| keyEvent | Pointer to the **OH_NativeXComponent_KeyEvent** instance.| +| timeStamp | Pointer to the timestamp of the key event. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 + + +### OH_NativeXComponent_GetMouseEvent() ``` int32_t OH_NativeXComponent_GetMouseEvent (OH_NativeXComponent * component, const void * window, OH_NativeXComponent_MouseEvent * mouseEvent ) @@ -323,24 +871,23 @@ Obtains the mouse event scheduled by ArkUI XComponent. **Parameters** -| Name | Description | -| ---------- | --------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| window | Indicates the pointer to a **NativeWindow** handle. | -| mouseEvent | Indicates the pointer to the current mouse event. | +| Name | Description | +| ---------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| window | Handle to the **NativeWindow** instance. | +| mouseEvent | Pointer to the current mouse event. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 9 ### OH_NativeXComponent_GetTouchEvent() - ``` int32_t OH_NativeXComponent_GetTouchEvent (OH_NativeXComponent * component, const void * window, OH_NativeXComponent_TouchEvent * touchEvent ) ``` @@ -351,79 +898,77 @@ Obtains the touch event scheduled by the ArkUI XComponent. **Parameters** -| Name | Description | -| ---------- | --------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| window | Indicates the pointer to a **NativeWindow** handle. | -| touchEvent | Indicates the pointer to the current touch event. | +| Name | Description | +| ---------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| window | Handle to the **NativeWindow** instance. | +| touchEvent | Pointer to the current touch event. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 8 + ### OH_NativeXComponent_GetTouchPointTiltX() - ``` int32_t OH_NativeXComponent_GetTouchPointTiltX (OH_NativeXComponent * component, uint32_t pointIndex, float * tiltX ) ``` **Description** -Obtains the angle between the tilt of the ArkUI XComponent touch point and the x-axis. +Obtains the angle between the Y-Z plane of the ArkUI XComponent touch point and the x-axis. **Parameters** -| Name | Description | -| -------- | -------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| pointIndex | Indicates the index of the pointer to a touch point. | -| tiltX | Indicates the pointer to the tilt along the x-axis. | +| Name | Description | +| ---------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| pointIndex | Pointer to the index of the touch point. | +| tiltX | Pointer to the angle between the Y-Z plane of the touch point and the x-axis. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 9 ### OH_NativeXComponent_GetTouchPointTiltY() - ``` -int32_t OH_NativeXComponent_GetTouchPointTiltX (OH_NativeXComponent * component, uint32_t pointIndex, float * tiltY ) +int32_t OH_NativeXComponent_GetTouchPointTiltY (OH_NativeXComponent * component, uint32_t pointIndex, float * tiltY ) ``` **Description** -Obtains the angle between the tilt of the ArkUI XComponent touch point and the y-axis. +Obtains the angle between the X-Z plane of the ArkUI XComponent touch point and the x-axis. **Parameters** -| Name | Description | -| -------- | -------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| pointIndex | Indicates the index of the pointer to a touch point. | -| tiltY | Indicates the pointer to the tilt along the y-axis. | +| Name | Description | +| ---------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| pointIndex | Pointer to the index of the touch point. | +| tiltY | Pointer to the angle between the X-Z plane of the touch point and the y-axis. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 9 ### OH_NativeXComponent_GetTouchPointToolType() - ``` int32_t OH_NativeXComponent_GetTouchPointToolType (OH_NativeXComponent * component, uint32_t pointIndex, OH_NativeXComponent_TouchPointToolType * toolType ) ``` @@ -434,52 +979,50 @@ Obtains the ArkUI XComponent touch point tool type. **Parameters** -| Name | Description | -| -------- | -------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| pointIndex | Indicates the index of the pointer to a touch point. | -| toolType | Indicates the pointer to the tool type. | +| Name | Description | +| ---------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| pointIndex | Pointer to the index of the touch point. | +| toolType | Pointer to the tool type. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 9 ### OH_NativeXComponent_GetXComponentId() - ``` int32_t OH_NativeXComponent_GetXComponentId (OH_NativeXComponent * component, char * id, uint64_t * size ) ``` **Description** -Obtains the ID of the ArkUI XComponent. +Obtain the ID of ArkUI XComponent. **Parameters** -| Name | Description | -| --------- | ------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| id | Indicates the pointer to the character buffer used to hold the ID of the OH_NativeXComponent instance.
Note that the null terminator is attached to the character buffer, so the size of the character buffer should be at least one unit greater than the length of the real ID.
The recommended size of the character buffer is [OH_XCOMPONENT_ID_LEN_MAX + 1]. | -| size | Indicates the pointer to the length of the ID. | +| Name | Description | +| --------- | ---------------------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance. | +| id | Pointer to the character buffer for storing the ID of the **OH_NativeXComponent** instance. Note that null terminators will be attached to the character buffer, so the size of the character buffer should be at least one unit greater than the length of the real ID. The recommended size is [OH_XCOMPONENT_ID_LEN_MAX + 1].| +| size | Pointer to the length of the ID. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 8 ### OH_NativeXComponent_GetXComponentOffset() - ``` int32_t OH_NativeXComponent_GetXComponentOffset (OH_NativeXComponent * component, const void * window, double * x, double * y ) ``` @@ -490,25 +1033,24 @@ Obtains the offset of the ArkUI XComponent relative to the upper left vertex of **Parameters** -| Name | Description | -| --------- | --------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| window | Indicates the pointer to a **NativeWindow** handle. | -| x | Indicates the pointer to the x coordinate of the current surface. | -| y | Indicates the pointer to the y coordinate of the current surface. | +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| window | Handle to the **NativeWindow** instance. | +| x | Pointer to the x coordinate of the current surface. | +| y | Pointer to the y coordinate of the current surface. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 8 ### OH_NativeXComponent_GetXComponentSize() - ``` int32_t OH_NativeXComponent_GetXComponentSize (OH_NativeXComponent * component, const void * window, uint64_t * width, uint64_t * height ) ``` @@ -519,24 +1061,49 @@ Obtains the size of the surface held by the ArkUI XComponent. **Parameters** -| Name | Description | -| --------- | --------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| window | Indicates the pointer to a **NativeWindow** handle. | -| width | Indicates the pointer to the width of the current surface. | -| height | Indicates the pointer to the height of the current surface. | +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| window | Handle to the **NativeWindow** instance. | +| width | Pointer to the width of the current surface. | +| height | Pointer to the height of the current surface. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 8 -### OH_NativeXComponent_RegisterCallback() +### OH_NativeXComponent_RegisterBlurEventCallback() +``` +int32_t OH_NativeXComponent_RegisterBlurEventCallback (OH_NativeXComponent * component, void(*)(OH_NativeXComponent *component, void *window) callback ) +``` + +**Description** + +Registers the focus loss event callback for this **OH_NativeXComponent** instance. + +**Parameters** + +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| callback | Pointer to the focus loss event callback. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +8 + + +### OH_NativeXComponent_RegisterCallback() ``` int32_t OH_NativeXComponent_RegisterCallback (OH_NativeXComponent * component, OH_NativeXComponent_Callback * callback ) @@ -548,43 +1115,94 @@ Registers a callback for this **OH_NativeXComponent** instance. **Parameters** -| Name | Description | -| --------- | --------------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| callback | Indicates the pointer to the surface lifecycle and touch event callback.| +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| callback | Pointer to the surface lifecycle and touch event callback. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 8 -### OH_NativeXComponent_RegisterMouseEventCallback() +### OH_NativeXComponent_RegisterFocusEventCallback() + +``` +int32_t OH_NativeXComponent_RegisterFocusEventCallback (OH_NativeXComponent * component, void(*)(OH_NativeXComponent *component, void *window) callback ) +``` + +**Description** + +Registers the focus obtaining event callback for this **OH_NativeXComponent** instance. + +**Parameters** + +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| callback | Pointer to the focus obtaining event callback. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 +### OH_NativeXComponent_RegisterKeyEventCallback() + +``` +int32_t OH_NativeXComponent_RegisterKeyEventCallback (OH_NativeXComponent * component, void(*)(OH_NativeXComponent *component, void *window) callback ) +``` + +**Description** + +Registers the key event callback for this **OH_NativeXComponent** instance. + +**Parameters** + +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| callback | Pointer to the key event callback. | + +**Returns** + +Returns the status code of the execution. + +**Since** + +10 + + +### OH_NativeXComponent_RegisterMouseEventCallback() + ``` int32_t OH_NativeXComponent_RegisterMouseEventCallback (OH_NativeXComponent * component, OH_NativeXComponent_MouseEvent_Callback * callback ) ``` **Description** -Registers a mouse event callback for this **OH_NativeXComponent** instance. +Registers the mouse event callback for this **OH_NativeXComponent** instance. **Parameters** -| Name | Description | -| --------- | --------------------------------------- | -| component | Indicates the pointer to an **OH_NativeXComponent** instance. | -| callback | Indicates the pointer to the mouse event callback. | +| Name | Description | +| --------- | ----------------------------- | +| component | Pointer to the **OH_NativeXComponent** instance.| +| callback | Pointer to the mouse event callback. | **Returns** -Returns the status code of the operation. +Returns the status code of the execution. -**Since:** +**Since** 9 @@ -594,23 +1212,25 @@ Returns the status code of the operation. ### OH_XCOMPONENT_ID_LEN_MAX - ``` const uint32_t OH_XCOMPONENT_ID_LEN_MAX = 128 ``` + **Description** -Maximum length of an ArkUI XComponent ID. -**Since:** +Maximum length of the ArkUI XComponent ID. + + +**Since** + 8 ### OH_MAX_TOUCH_POINTS_NUMBER - ``` const uint32_t OH_MAX_TOUCH_POINTS_NUMBER = 10 ``` @@ -619,46 +1239,43 @@ const uint32_t OH_MAX_TOUCH_POINTS_NUMBER = 10 Maximum number of identifiable touch points in a touch event. -**Since:** +**Since** 8 ### action - ``` OH_NativeXComponent_MouseEventAction OH_NativeXComponent_MouseEvent::action ``` **Description** -Current mouse event action. +Action of the mouse event. -**Since:** +**Since** 8 ### button - ``` OH_NativeXComponent_MouseEventButton OH_NativeXComponent_MouseEvent::button ``` **Description** -Mouse event button +Mouse event button. -**Since:** +**Since** 8 ### deviceId - ``` int64_t OH_NativeXComponent_TouchEvent::deviceId = 0 ``` @@ -667,14 +1284,13 @@ int64_t OH_NativeXComponent_TouchEvent::deviceId = 0 ID of the device where the current touch event is triggered. -**Since:** +**Since** 8 ### DispatchHoverEvent - ``` void(* OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent) (OH_NativeXComponent *component, bool isHover) ``` @@ -683,14 +1299,13 @@ void(* OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent) (OH_NativeXC Invoked when a hover event is triggered. -**Since:** +**Since** 8 ### DispatchMouseEvent - ``` void(* OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent) (OH_NativeXComponent *component, void *window) ``` @@ -699,14 +1314,13 @@ void(* OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent) (OH_NativeXC Invoked when a mouse event is triggered. -**Since:** +**Since** 8 ### DispatchTouchEvent - ``` void(* OH_NativeXComponent_Callback::DispatchTouchEvent) (OH_NativeXComponent *component, void *window) ``` @@ -715,46 +1329,43 @@ void(* OH_NativeXComponent_Callback::DispatchTouchEvent) (OH_NativeXComponent *c Invoked when a touch event is triggered. -**Since:** +**Since** 8 ### force [1/2] - ``` float OH_NativeXComponent_TouchPoint::force = 0.0 ``` **Description** -Pressure of the current touch event. +Pressure of the touch event. -**Since:** +**Since** 8 ### force [2/2] - ``` float OH_NativeXComponent_TouchEvent::force = 0.0 ``` **Description** -Pressure of the current touch event. +Pressure of the touch event. -**Since:** +**Since** 8 ### id [1/2] - ``` int32_t OH_NativeXComponent_TouchPoint::id = 0 ``` @@ -763,14 +1374,13 @@ int32_t OH_NativeXComponent_TouchPoint::id = 0 Unique identifier of the finger. -**Since:** +**Since** 8 ### id [2/2] - ``` int32_t OH_NativeXComponent_TouchEvent::id = 0 ``` @@ -779,14 +1389,13 @@ int32_t OH_NativeXComponent_TouchEvent::id = 0 Unique identifier of the finger. -**Since:** +**Since** 8 ### isPressed - ``` bool OH_NativeXComponent_TouchPoint::isPressed = false ``` @@ -795,14 +1404,13 @@ bool OH_NativeXComponent_TouchPoint::isPressed = false Whether the current point is pressed. -**Since:** +**Since** 8 ### numPoints - ``` uint32_t OH_NativeXComponent_TouchEvent::numPoints = 0 ``` @@ -811,14 +1419,13 @@ uint32_t OH_NativeXComponent_TouchEvent::numPoints = 0 Number of current touch points. -**Since:** +**Since** 8 ### OnSurfaceChanged - ``` void(* OH_NativeXComponent_Callback::OnSurfaceChanged) (OH_NativeXComponent *component, void *window) ``` @@ -827,30 +1434,28 @@ void(* OH_NativeXComponent_Callback::OnSurfaceChanged) (OH_NativeXComponent *com Invoked when the surface changes. -**Since:** +**Since** 8 ### OnSurfaceCreated - ``` void(* OH_NativeXComponent_Callback::OnSurfaceCreated) (OH_NativeXComponent *component, void *window) ``` **Description** -Invoked when a surface is created. +Invoked when a surface is created. -**Since:** +**Since** 8 ### OnSurfaceDestroyed - ``` void(* OH_NativeXComponent_Callback::OnSurfaceDestroyed) (OH_NativeXComponent *component, void *window) ``` @@ -859,46 +1464,43 @@ void(* OH_NativeXComponent_Callback::OnSurfaceDestroyed) (OH_NativeXComponent *c Invoked when the surface is destroyed. -**Since:** +**Since** 8 ### screenX [1/3] - ``` float OH_NativeXComponent_TouchPoint::screenX = 0.0 ``` **Description** -X coordinate of the touch point relative to the upper left corner of the application window where the XComponent is located. +X coordinate of the touch point relative to the left edge of the application window where the XComponent is located. -**Since:** +**Since** 8 ### screenX [2/3] - ``` float OH_NativeXComponent_TouchEvent::screenX = 0.0 ``` **Description** -X coordinate of the touch point relative to the upper left corner of the application window where the XComponent is located. +X coordinate of the touch point relative to the left edge of the screen. -**Since:** +**Since** 8 ### screenX [3/3] - ``` float OH_NativeXComponent_MouseEvent::screenX ``` @@ -907,46 +1509,43 @@ float OH_NativeXComponent_MouseEvent::screenX X coordinate of the clicked point relative to the upper left corner of the screen. -**Since:** +**Since** 8 ### screenY [1/3] - ``` float OH_NativeXComponent_TouchPoint::screenY = 0.0 ``` **Description** -Y coordinate of the touch point relative to the upper left corner of the application window where the XComponent is located. +Y coordinate of the touch point relative to the left edge of the application window where the XComponent is located. -**Since:** +**Since** 8 ### screenY [2/3] - ``` float OH_NativeXComponent_TouchEvent::screenY = 0.0 ``` **Description** -Y coordinate of the touch point relative to the upper left corner of the application window where the XComponent is located. +Y coordinate of the touch point relative to the upper edge of the screen. -**Since:** +**Since** 8 ### screenY [3/3] - ``` float OH_NativeXComponent_MouseEvent::screenY ``` @@ -955,14 +1554,13 @@ float OH_NativeXComponent_MouseEvent::screenY Y coordinate of the clicked point relative to the upper left corner of the screen. -**Since:** +**Since** 8 ### size [1/2] - ``` double OH_NativeXComponent_TouchPoint::size = 0.0 ``` @@ -971,14 +1569,13 @@ double OH_NativeXComponent_TouchPoint::size = 0.0 Contact area between the finger pad and the screen. -**Since:** +**Since** 8 ### size [2/2] - ``` double OH_NativeXComponent_TouchEvent::size = 0.0 ``` @@ -987,94 +1584,88 @@ double OH_NativeXComponent_TouchEvent::size = 0.0 Contact area between the finger pad and the screen. -**Since:** +**Since** 8 ### timeStamp [1/2] - ``` long long OH_NativeXComponent_TouchPoint::timeStamp = 0 ``` **Description** -Timestamp of the current touch event. +Timestamp of the touch point. -**Since:** +**Since** 8 ### timeStamp [2/2] - ``` long long OH_NativeXComponent_TouchEvent::timeStamp = 0 ``` **Description** -Timestamp of the current touch event. +Timestamp of the touch event. -**Since:** +**Since** 8 ### timestamp - ``` int64_t OH_NativeXComponent_MouseEvent::timestamp ``` **Description** -Timestamp of the current mouse event. +Timestamp of the mouse event. -**Since:** +**Since** 8 ### touchPoints - ``` OH_NativeXComponent_TouchPoint OH_NativeXComponent_TouchEvent::touchPoints[OH_MAX_TOUCH_POINTS_NUMBER] ``` **Description** -Array of the current touch points. +Array of the touch points. -**Since:** +**Since** 8 ### type [1/2] - ``` OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchPoint::type = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN ``` **Description** -Touch type of the touch event. +Touch type of the touch point. -**Since:** +**Since** 8 ### type [2/2] - ``` OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchEvent::type = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN ``` @@ -1083,14 +1674,13 @@ OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchEvent::type = OH_Nat Touch type of the touch event. -**Since:** +**Since** 8 ### x [1/3] - ``` float OH_NativeXComponent_TouchPoint::x = 0.0 ``` @@ -1099,14 +1689,13 @@ float OH_NativeXComponent_TouchPoint::x = 0.0 X coordinate of the touch point relative to the left edge of the XComponent. -**Since:** +**Since** 8 ### x [2/3] - ``` float OH_NativeXComponent_TouchEvent::x = 0.0 ``` @@ -1115,14 +1704,13 @@ float OH_NativeXComponent_TouchEvent::x = 0.0 X coordinate of the touch point relative to the left edge of the XComponent. -**Since:** +**Since** 8 ### x [3/3] - ``` float OH_NativeXComponent_MouseEvent::x ``` @@ -1131,14 +1719,13 @@ float OH_NativeXComponent_MouseEvent::x X coordinate of the clicked point relative to the upper left corner of the component. -**Since:** +**Since** 8 ### y [1/3] - ``` float OH_NativeXComponent_TouchPoint::y = 0.0 ``` @@ -1147,14 +1734,13 @@ float OH_NativeXComponent_TouchPoint::y = 0.0 Y coordinate of the touch point relative to the upper edge of the XComponent. -**Since:** +**Since** 8 ### y [2/3] - ``` float OH_NativeXComponent_TouchEvent::y = 0.0 ``` @@ -1163,14 +1749,13 @@ float OH_NativeXComponent_TouchEvent::y = 0.0 Y coordinate of the touch point relative to the upper edge of the XComponent. -**Since:** +**Since** 8 ### y [3/3] - ``` float OH_NativeXComponent_MouseEvent::y ``` @@ -1179,6 +1764,6 @@ float OH_NativeXComponent_MouseEvent::y Y coordinate of the clicked point relative to the upper left corner of the component. -**Since:** +**Since** -8 \ No newline at end of file +8 diff --git a/en/application-dev/reference/native-apis/_o_h___native_x_component___callback.md b/en/application-dev/reference/native-apis/_o_h___native_x_component___callback.md index fd2a0ebced876c110742f8fbe75c080f218d5d6a..437c09e54c892d5e8fbe9a95d1a34ee85de2ca7d 100644 --- a/en/application-dev/reference/native-apis/_o_h___native_x_component___callback.md +++ b/en/application-dev/reference/native-apis/_o_h___native_x_component___callback.md @@ -3,7 +3,7 @@ ## Overview -Registers a callback for the surface lifecycle and touch event. +Registers callbacks for the surface lifecycle and touch event. **Since:** 8 @@ -18,9 +18,9 @@ Registers a callback for the surface lifecycle and touch event. ### Member Variables -| Name | Description | +| Name | Description | | -------- | -------- | -| [OnSurfaceCreated](_o_h___native_x_component.md#onsurfacecreated)| Invoked when a surface is created. | -| [OnSurfaceChanged](_o_h___native_x_component.md#onsurfacechanged)| Invoked when the surface changes. | -| [OnSurfaceDestroyed](_o_h___native_x_component.md#onsurfacedestroyed)| Invoked when the surface is destroyed. | -| [DispatchTouchEvent](_o_h___native_x_component.md#dispatchtouchevent)| Invoked when a touch event is triggered. | +| [OnSurfaceCreated](_o_h___native_x_component.md#onsurfacecreated)| Invoked when a surface is created. | +| [OnSurfaceChanged](_o_h___native_x_component.md#onsurfacechanged)| Invoked when the surface changes. | +| [OnSurfaceDestroyed](_o_h___native_x_component.md#onsurfacedestroyed)| Invoked when the surface is destroyed. | +| [DispatchTouchEvent](_o_h___native_x_component.md#dispatchtouchevent)| Invoked when a touch event is triggered. | diff --git a/en/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event___callback.md b/en/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event___callback.md index 531b6b7151febabc65b37dcfe97daa434f676825..e0942f57a86628bd9a8c72c15901e96efefb326d 100644 --- a/en/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event___callback.md +++ b/en/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event___callback.md @@ -3,7 +3,7 @@ ## Overview -Registers a callback for the mouse event. +Registers callbacks for the mouse event. **Since:** 9 @@ -18,7 +18,7 @@ Registers a callback for the mouse event. ### Member Variables -| Name | Description | +| Name | Description | | -------- | -------- | -| [DispatchMouseEvent](_o_h___native_x_component.md#dispatchmouseevent) | Invoked when a mouse event is triggered. | -| [DispatchHoverEvent](_o_h___native_x_component.md#dispatchhoverevent) | Invoked when a hover event is triggered. | +| [DispatchMouseEvent](_o_h___native_x_component.md#dispatchmouseevent) | Invoked when a mouse event is triggered. | +| [DispatchHoverEvent](_o_h___native_x_component.md#dispatchhoverevent) | Invoked when a hover event is triggered. | diff --git a/en/application-dev/reference/native-apis/native__interface__xcomponent_8h.md b/en/application-dev/reference/native-apis/native__interface__xcomponent_8h.md index ddd53144f6359edcebf6e3f89f209c5ec2508bb2..94e975d3f9f14342028b16fb527b4dd09f5ca87e 100644 --- a/en/application-dev/reference/native-apis/native__interface__xcomponent_8h.md +++ b/en/application-dev/reference/native-apis/native__interface__xcomponent_8h.md @@ -3,13 +3,13 @@ ## Overview -Declares the APIs used to access the native XComponent. +Declares the APIs for accessing **NativeXComponent**. -**Since:** +**Since** 8 -**Related Modules:** +**Related Modules** [Native XComponent](_o_h___native_x_component.md) @@ -19,50 +19,65 @@ Declares the APIs used to access the native XComponent. ### Structs -| Name | Description | -| -------- | -------- | -| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | Describes the touch point of the touch event. | -| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | Describes the touch event. | -| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | Describes the mouse event.| -| [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) | Registers a callback for the surface lifecycle and touch event. | -| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | Registers a callback for the mouse event. | +| Name | Description | +| ---------------------------------------- | --------------------- | +| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | Describes the touch point of the touch event. | +| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | Describes the touch event. | +| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | Describes the mouse event. | +| [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) | Registers callbacks for the surface lifecycle and touch event.| +| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | Registers callbacks for the mouse event. | ### Types -| Name | Description | -| -------- | -------- | -| [OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) | Provides an encapsulated OH_NativeXComponent instance. | -| [OH_NativeXComponent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_callback) | Registers a callback for the surface lifecycle and touch event. | -| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_mouseevent_callback) | Registers a callback for the mouse event. | +| Name | Description | +| ---------------------------------------- | ------------------------------------ | +| [OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) | Provides an encapsulated **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_callback) | Registers callbacks for the surface lifecycle and touch event. | +| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_mouseevent_callback) | Registers callbacks for the mouse event. | +| [OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) | Provides an encapsulated **OH_NativeXComponent_KeyEvent** instance.| ### Enums -| Name | Description | -| -------- | -------- | -| { OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0,
OH_NATIVEXCOMPONENT_RESULT_FAILED = -1,
OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2} | [Enumerates](_o_h___native_x_component.md#anonymous-enum) the API access states. | -| [OH_NativeXComponent_TouchEventType](_o_h___native_x_component.md#oh_nativexcomponent_toucheventtype) {
OH_NATIVEXCOMPONENT_DOWN = 0,
OH_NATIVEXCOMPONENT_UP,
OH_NATIVEXCOMPONENT_MOVE,
OH_NATIVEXCOMPONENT_CANCEL,
OH_NATIVEXCOMPONENT_UNKNOWN } | Enumerates the touch event types. | -| [OH_NativeXComponent_MouseEventAction](_o_h___native_x_component.md#oh_nativexcomponent_mouseeventaction) {
OH_NATIVEXCOMPONENT_MOUSE_NONE = 0,
OH_NATIVEXCOMPONENT_MOUSE_PRESS,
OH_NATIVEXCOMPONENT_MOUSE_RELEASE,
OH_NATIVEXCOMPONENT_MOUSE_MOVE } | Enumerates the mouse event actions. | -| [OH_NativeXComponent_MouseEventButton](_o_h___native_x_component.md#oh_nativexcomponent_mouseeventbutton) {
OH_NATIVEXCOMPONENT_NONE_BUTTON = 0,
OH_NATIVEXCOMPONENT_LEFT_BUTTON = 0x01,
OH_NATIVEXCOMPONENT_RIGHT_BUTTON = 0x02,
OH_NATIVEXCOMPONENT_MIDDLE_BUTTON = 0x04,
OH_NATIVEXCOMPONENT_BACK_BUTTON = 0x08,
OH_NATIVEXCOMPONENT_FORWARD_BUTTON = 0x10 } | Enumerates the mouse event buttons. | +| Name | Description | +| ---------------------------------------- | ---------- | +| { OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0, OH_NATIVEXCOMPONENT_RESULT_FAILED = -1, OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2 } | Enumerates the API access states.| +| [OH_NativeXComponent_TouchEventType](_o_h___native_x_component.md#oh_nativexcomponent_toucheventtype) {
OH_NATIVEXCOMPONENT_DOWN = 0, OH_NATIVEXCOMPONENT_UP, OH_NATIVEXCOMPONENT_MOVE, OH_NATIVEXCOMPONENT_CANCEL,
OH_NATIVEXCOMPONENT_UNKNOWN
} | Enumerates the touch event types. | +| [OH_NativeXComponent_TouchPointToolType](_o_h___native_x_component.md#oh_nativexcomponent_touchpointtooltype) {
OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN = 0, OH_NATIVEXCOMPONENT_TOOL_TYPE_FINGER, OH_NATIVEXCOMPONENT_TOOL_TYPE_PEN, OH_NATIVEXCOMPONENT_TOOL_TYPE_RUBBER,
OH_NATIVEXCOMPONENT_TOOL_TYPE_BRUSH, OH_NATIVEXCOMPONENT_TOOL_TYPE_PENCIL, OH_NATIVEXCOMPONENT_TOOL_TYPE_AIRBRUSH, OH_NATIVEXCOMPONENT_TOOL_TYPE_MOUSE,
OH_NATIVEXCOMPONENT_TOOL_TYPE_LENS
} | Enumerates the touch point tool types. | +| [OH_NativeXComponent_EventSourceType](_o_h___native_x_component.md#oh_nativexcomponent_eventsourcetype) {
OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN = 0, OH_NATIVEXCOMPONENT_SOURCE_TYPE_MOUSE, OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHSCREEN, OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHPAD,
OH_NATIVEXCOMPONENT_SOURCE_TYPE_JOYSTICK, OH_NATIVEXCOMPONENT_SOURCE_TYPE_KEYBOARD
} | Enumerates the touch event source types. | +| [OH_NativeXComponent_MouseEventAction](_o_h___native_x_component.md#oh_nativexcomponent_mouseeventaction) { OH_NATIVEXCOMPONENT_MOUSE_NONE = 0, OH_NATIVEXCOMPONENT_MOUSE_PRESS, OH_NATIVEXCOMPONENT_MOUSE_RELEASE, OH_NATIVEXCOMPONENT_MOUSE_MOVE } | Enumerates the mouse event actions. | +| [OH_NativeXComponent_MouseEventButton](_o_h___native_x_component.md#oh_nativexcomponent_mouseeventbutton) {
OH_NATIVEXCOMPONENT_NONE_BUTTON = 0, OH_NATIVEXCOMPONENT_LEFT_BUTTON = 0x01, OH_NATIVEXCOMPONENT_RIGHT_BUTTON = 0x02, OH_NATIVEXCOMPONENT_MIDDLE_BUTTON = 0x04,
OH_NATIVEXCOMPONENT_BACK_BUTTON = 0x08, OH_NATIVEXCOMPONENT_FORWARD_BUTTON = 0x10
} | Enumerates the mouse event buttons. | ### Functions -| Name | Description | -| -------- | -------- | -| [OH_NativeXComponent_GetXComponentId](_o_h___native_x_component.md#oh_nativexcomponent_getxcomponentid) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, char \*id, uint64_t \*size) | Obtains the ID of the ArkUI XComponent. | -| [OH_NativeXComponent_GetXComponentSize](_o_h___native_x_component.md#oh_nativexcomponent_getxcomponentsize) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, uint64_t \*width, uint64_t \*height) | Obtains the size of the surface held by the ArkUI XComponent. | -| [OH_NativeXComponent_GetXComponentOffset](_o_h___native_x_component.md#oh_nativexcomponent_getxcomponentoffset) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, double \*x, double \*y) | Obtains the offset of the ArkUI XComponent relative to the upper left vertex of the screen. | -| [OH_NativeXComponent_GetTouchEvent](_o_h___native_x_component.md#oh_nativexcomponent_gettouchevent) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) \*touchEvent) | Obtains the touch event scheduled by the ArkUI XComponent. | -| [OH_NativeXComponent_GetMouseEvent](_o_h___native_x_component.md#oh_nativexcomponent_getmouseevent) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) \*mouseEvent) | Obtains the mouse event scheduled by ArkUI XComponent. | -| [OH_NativeXComponent_RegisterCallback](_o_h___native_x_component.md#oh_nativexcomponent_registercallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) \*callback) | Registers a callback for this **OH_NativeXComponent** instance. | -| [OH_NativeXComponent_RegisterMouseEventCallback](_o_h___native_x_component.md#oh_nativexcomponent_registermouseeventcallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) \*callback) | Registers a mouse event callback for this **OH_NativeXComponent** instance. | +| Name | Description | +| ---------------------------------------- | -------------------------------------- | +| [OH_NativeXComponent_GetXComponentId](_o_h___native_x_component.md#oh_nativexcomponent_getxcomponentid) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, char \*id, uint64_t \*size) | Obtains the ID of the ArkUI XComponent. | +| [OH_NativeXComponent_GetXComponentSize](_o_h___native_x_component.md#oh_nativexcomponent_getxcomponentsize) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, uint64_t \*width, uint64_t \*height) | Obtains the size of the surface held by the ArkUI XComponent. | +| [OH_NativeXComponent_GetXComponentOffset](_o_h___native_x_component.md#oh_nativexcomponent_getxcomponentoffset) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, double \*x, double \*y) | Obtains the offset of the ArkUI XComponent relative to the upper left vertex of the screen.| +| [OH_NativeXComponent_GetTouchEvent](_o_h___native_x_component.md#oh_nativexcomponent_gettouchevent) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) \*touchEvent) | Obtains the touch event scheduled by the ArkUI XComponent. | +| [OH_NativeXComponent_GetTouchPointToolType](_o_h___native_x_component.md#oh_nativexcomponent_gettouchpointtooltype) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, uint32_t pointIndex, [OH_NativeXComponent_TouchPointToolType](_o_h___native_x_component.md#oh_nativexcomponent_touchpointtooltype) \*toolType) | Obtains the ArkUI XComponent touch point tool type. | +| [OH_NativeXComponent_GetTouchPointTiltX](_o_h___native_x_component.md#oh_nativexcomponent_gettouchpointtiltx) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltX) | Obtains the angle between the Y-Z plane of the ArkUI XComponent touch point and the x-axis. | +| [OH_NativeXComponent_GetTouchPointTiltY](_o_h___native_x_component.md#oh_nativexcomponent_gettouchpointtilty) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltY) | Obtains the angle between the Y-Z plane of the ArkUI XComponent touch point and the y-axis. | +| [OH_NativeXComponent_GetMouseEvent](_o_h___native_x_component.md#oh_nativexcomponent_getmouseevent) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, const void \*window, [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) \*mouseEvent) | Obtains the mouse event scheduled by ArkUI XComponent. | +| [OH_NativeXComponent_RegisterCallback](_o_h___native_x_component.md#oh_nativexcomponent_registercallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) \*callback) | Registers a callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterMouseEventCallback](_o_h___native_x_component.md#oh_nativexcomponent_registermouseeventcallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) \*callback) | Registers the mouse event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterFocusEventCallback](_o_h___native_x_component.md#oh_nativexcomponent_registerfocuseventcallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, void \*window)) | Registers the focus obtaining event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterKeyEventCallback](_o_h___native_x_component.md#oh_nativexcomponent_registerkeyeventcallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, void \*window)) | Registers the key event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_RegisterBlurEventCallback](_o_h___native_x_component.md#oh_nativexcomponent_registerblureventcallback) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, void \*window)) | Registers the focus loss event callback for this **OH_NativeXComponent** instance. | +| [OH_NativeXComponent_GetKeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_getkeyevent) ([OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) \*component, [OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) \*\*keyEvent) | Obtains the key event scheduled by the ArkUI XComponent. | +| [OH_NativeXComponent_GetKeyEventAction](_o_h___native_x_component.md#oh_nativexcomponent_getkeyeventaction) ([OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_KeyAction](_o_h___native_x_component.md#oh_nativexcomponent_keyaction) \*action) | Obtains the action of the specified key event. | +| [OH_NativeXComponent_GetKeyEventCode](_o_h___native_x_component.md#oh_nativexcomponent_getkeyeventcode) ([OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_KeyCode](_o_h___native_x_component.md#oh_nativexcomponent_keycode) \*code) | Obtains the key code of the specified key event. | +| [OH_NativeXComponent_GetKeyEventSourceType](_o_h___native_x_component.md#oh_nativexcomponent_getkeyeventsourcetype) ([OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_EventSourceType](_o_h___native_x_component.md#oh_nativexcomponent_eventsourcetype) \*sourceType) | Obtains the source type of the specified key event. | +| [OH_NativeXComponent_GetKeyEventDeviceId](_o_h___native_x_component.md#oh_nativexcomponent_getkeyeventdeviceid) ([OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) \*keyEvent, int64_t \*deviceId) | Obtains the device ID of the specified key event. | +| [OH_NativeXComponent_GetKeyEventTimeStamp](_o_h___native_x_component.md#oh_nativexcomponent_getkeyeventtimestamp) ([OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) \*keyEvent, int64_t \*timeStamp) | Obtains the timestamp of the specified key event. | ### Variables -| Name | Description | -| -------- | -------- | -| **OH_XCOMPONENT_ID_LEN_MAX** = 128 | Maximum length of an ArkUI XComponent ID. | -| **OH_MAX_TOUCH_POINTS_NUMBER** = 10 | Maximum number of identifiable touch points in a touch event. | +| Name | Description | +| ---------------------------------------- | ------------------------- | +| **OH_XCOMPONENT_ID_LEN_MAX** = 128 | Maximum length of the ArkUI XComponent ID.| +| **OH_MAX_TOUCH_POINTS_NUMBER** = 10 | Maximum number of identifiable touch points in a touch event. | diff --git a/en/application-dev/reference/native-apis/native__xcomponent__key__event_8h.md b/en/application-dev/reference/native-apis/native__xcomponent__key__event_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..6a5e639eae245662815de9cba9a878e2733e0089 --- /dev/null +++ b/en/application-dev/reference/native-apis/native__xcomponent__key__event_8h.md @@ -0,0 +1,25 @@ +# native_xcomponent_key_event.h + + +## Overview + +Declares the enums used for accessing **NativeXComponent** key events. + +**Since** + +10 + +**Related Modules** + +[Native XComponent](_o_h___native_x_component.md) + + +## Summary + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_NativeXComponent_KeyCode](_o_h___native_x_component.md#oh_nativexcomponent_keycode) {
KEY_UNKNOWN = -1, KEY_FN = 0, KEY_HOME = 1, KEY_BACK = 2,KEY_MEDIA_PLAY_PAUSE = 10, KEY_MEDIA_STOP = 11, KEY_MEDIA_NEXT = 12, KEY_MEDIA_PREVIOUS = 13,
KEY_MEDIA_REWIND = 14, KEY_MEDIA_FAST_FORWARD = 15, KEY_VOLUME_UP = 16, KEY_VOLUME_DOWN = 17,
KEY_POWER = 18, KEY_CAMERA = 19, KEY_VOLUME_MUTE = 22, KEY_MUTE = 23,KEY_BRIGHTNESS_UP = 40, KEY_BRIGHTNESS_DOWN = 41, KEY_0 = 2000, KEY_1 = 2001,
KEY_2 = 2002, KEY_3 = 2003, KEY_4 = 2004, KEY_5 = 2005,
KEY_6 = 2006, KEY_7 = 2007, KEY_8 = 2008, KEY_9 = 2009,
KEY_STAR = 2010, KEY_POUND = 2011, KEY_DPAD_UP = 2012, KEY_DPAD_DOWN = 2013,KEY_DPAD_LEFT = 2014, KEY_DPAD_RIGHT = 2015, KEY_DPAD_CENTER = 2016,
KEY_A = 2017,
KEY_B = 2018, KEY_C = 2019, KEY_D = 2020, KEY_E = 2021,
KEY_F = 2022, KEY_G = 2023, KEY_H = 2024, KEY_I = 2025,
KEY_J = 2026, KEY_K = 2027, KEY_L = 2028, KEY_M = 2029,
KEY_N = 2030, KEY_O = 2031, KEY_P = 2032, KEY_Q = 2033,
KEY_R = 2034, KEY_S = 2035, KEY_T = 2036, KEY_U = 2037,
KEY_V = 2038, KEY_W = 2039, KEY_X = 2040, KEY_Y = 2041,
KEY_Z = 2042, KEY_COMMA = 2043, KEY_PERIOD = 2044, KEY_ALT_LEFT = 2045,
KEY_ALT_RIGHT = 2046, KEY_SHIFT_LEFT = 2047, KEY_SHIFT_RIGHT = 2048, KEY_TAB = 2049,
KEY_SPACE = 2050, KEY_SYM = 2051, KEY_EXPLORER = 2052, KEY_ENVELOPE = 2053,
KEY_ENTER = 2054, KEY_DEL = 2055, KEY_GRAVE = 2056, KEY_MINUS = 2057,
KEY_EQUALS = 2058, KEY_LEFT_BRACKET = 2059, KEY_RIGHT_BRACKET = 2060, KEY_BACKSLASH = 2061,
KEY_SEMICOLON = 2062, KEY_APOSTROPHE = 2063, KEY_SLASH = 2064, KEY_AT = 2065,
KEY_PLUS = 2066, KEY_MENU = 2067, KEY_PAGE_UP = 2068, KEY_PAGE_DOWN = 2069,
KEY_ESCAPE = 2070, KEY_FORWARD_DEL = 2071, KEY_CTRL_LEFT = 2072, KEY_CTRL_RIGHT = 2073,
KEY_CAPS_LOCK = 2074, KEY_SCROLL_LOCK = 2075, KEY_META_LEFT = 2076, KEY_META_RIGHT = 2077,
KEY_FUNCTION = 2078, KEY_SYSRQ = 2079, KEY_BREAK = 2080, KEY_MOVE_HOME = 2081,
KEY_MOVE_END = 2082, KEY_INSERT = 2083, KEY_FORWARD = 2084, KEY_MEDIA_PLAY = 2085,
KEY_MEDIA_PAUSE = 2086, KEY_MEDIA_CLOSE = 2087, KEY_MEDIA_EJECT = 2088, KEY_MEDIA_RECORD = 2089,
KEY_F1 = 2090, KEY_F2 = 2091, KEY_F3 = 2092, KEY_F4 = 2093,
KEY_F5 = 2094, KEY_F6 = 2095, KEY_F7 = 2096, KEY_F8 = 2097,
KEY_F9 = 2098, KEY_F10 = 2099, KEY_F11 = 2100, KEY_F12 = 2101,
KEY_NUM_LOCK = 2102, KEY_NUMPAD_0 = 2103, KEY_NUMPAD_1 = 2104, KEY_NUMPAD_2 = 2105,
KEY_NUMPAD_3 = 2106, KEY_NUMPAD_4 = 2107, KEY_NUMPAD_5 = 2108, KEY_NUMPAD_6 = 2109,
KEY_NUMPAD_7 = 2110, KEY_NUMPAD_8 = 2111, KEY_NUMPAD_9 = 2112, KEY_NUMPAD_DIVIDE = 2113,
KEY_NUMPAD_MULTIPLY = 2114, KEY_NUMPAD_SUBTRACT = 2115, KEY_NUMPAD_ADD = 2116, KEY_NUMPAD_DOT = 2117,
KEY_NUMPAD_COMMA = 2118, KEY_NUMPAD_ENTER = 2119, KEY_NUMPAD_EQUALS = 2120, KEY_NUMPAD_LEFT_PAREN = 2121,
KEY_NUMPAD_RIGHT_PAREN = 2122, KEY_VIRTUAL_MULTITASK = 2210, KEY_SLEEP = 2600, KEY_ZENKAKU_HANKAKU = 2601,
KEY_102ND = 2602, KEY_RO = 2603, KEY_KATAKANA = 2604, KEY_HIRAGANA = 2605,
KEY_HENKAN = 2606, KEY_KATAKANA_HIRAGANA = 2607, KEY_MUHENKAN = 2608, KEY_LINEFEED = 2609,
KEY_MACRO = 2610, KEY_NUMPAD_PLUSMINUS = 2611, KEY_SCALE = 2612, KEY_HANGUEL = 2613,
KEY_HANJA = 2614, KEY_YEN = 2615, KEY_STOP = 2616, KEY_AGAIN = 2617,
KEY_PROPS = 2618, KEY_UNDO = 2619, KEY_COPY = 2620, KEY_OPEN = 2621,
KEY_PASTE = 2622, KEY_FIND = 2623, KEY_CUT = 2624, KEY_HELP = 2625,
KEY_CALC = 2626, KEY_FILE = 2627, KEY_BOOKMARKS = 2628, KEY_NEXT = 2629,
KEY_PLAYPAUSE = 2630, KEY_PREVIOUS = 2631, KEY_STOPCD = 2632, KEY_CONFIG = 2634,
KEY_REFRESH = 2635, KEY_EXIT = 2636, KEY_EDIT = 2637, KEY_SCROLLUP = 2638,
KEY_SCROLLDOWN = 2639, KEY_NEW = 2640, KEY_REDO = 2641, KEY_CLOSE = 2642,
KEY_PLAY = 2643, KEY_BASSBOOST = 2644, KEY_PRINT = 2645, KEY_CHAT = 2646,
KEY_FINANCE = 2647, KEY_CANCEL = 2648, KEY_KBDILLUM_TOGGLE = 2649, KEY_KBDILLUM_DOWN = 2650,
KEY_KBDILLUM_UP = 2651, KEY_SEND = 2652, KEY_REPLY = 2653, KEY_FORWARDMAIL = 2654,
KEY_SAVE = 2655, KEY_DOCUMENTS = 2656, KEY_VIDEO_NEXT = 2657, KEY_VIDEO_PREV = 2658,
KEY_BRIGHTNESS_CYCLE = 2659, KEY_BRIGHTNESS_ZERO = 2660, KEY_DISPLAY_OFF = 2661, KEY_BTN_MISC = 2662,
KEY_GOTO = 2663, KEY_INFO = 2664, KEY_PROGRAM = 2665, KEY_PVR = 2666,
KEY_SUBTITLE = 2667, KEY_FULL_SCREEN = 2668, KEY_KEYBOARD = 2669, KEY_ASPECT_RATIO = 2670,
KEY_PC = 2671, KEY_TV = 2672, KEY_TV2 = 2673, KEY_VCR = 2674,
KEY_VCR2 = 2675, KEY_SAT = 2676, KEY_CD = 2677, KEY_TAPE = 2678,
KEY_TUNER = 2679, KEY_PLAYER = 2680, KEY_DVD = 2681, KEY_AUDIO = 2682,
KEY_VIDEO = 2683, KEY_MEMO = 2684, KEY_CALENDAR = 2685, KEY_RED = 2686,
KEY_GREEN = 2687, KEY_YELLOW = 2688, KEY_BLUE = 2689, KEY_CHANNELUP = 2690,
KEY_CHANNELDOWN = 2691, KEY_LAST = 2692, KEY_RESTART = 2693, KEY_SLOW = 2694,
KEY_SHUFFLE = 2695, KEY_VIDEOPHONE = 2696, KEY_GAMES = 2697, KEY_ZOOMIN = 2698,
KEY_ZOOMOUT = 2699, KEY_ZOOMRESET = 2700, KEY_WORDPROCESSOR = 2701, KEY_EDITOR = 2702,
KEY_SPREADSHEET = 2703, KEY_GRAPHICSEDITOR = 2704, KEY_PRESENTATION = 2705, KEY_DATABASE = 2706,
KEY_NEWS = 2707, KEY_VOICEMAIL = 2708, KEY_ADDRESSBOOK = 2709, KEY_MESSENGER = 2710,
KEY_BRIGHTNESS_TOGGLE = 2711, KEY_SPELLCHECK = 2712, KEY_COFFEE = 2713, KEY_MEDIA_REPEAT = 2714,
KEY_IMAGES = 2715, KEY_BUTTONCONFIG = 2716, KEY_TASKMANAGER = 2717, KEY_JOURNAL = 2718,
KEY_CONTROLPANEL = 2719, KEY_APPSELECT = 2720, KEY_SCREENSAVER = 2721, KEY_ASSISTANT = 2722,
KEY_KBD_LAYOUT_NEXT = 2723, KEY_BRIGHTNESS_MIN = 2724, KEY_BRIGHTNESS_MAX = 2725, KEY_KBDINPUTASSIST_PREV = 2726,
KEY_KBDINPUTASSIST_NEXT = 2727, KEY_KBDINPUTASSIST_PREVGROUP = 2728, KEY_KBDINPUTASSIST_NEXTGROUP = 2729, KEY_KBDINPUTASSIST_ACCEPT = 2730,
KEY_KBDINPUTASSIST_CANCEL = 2731, KEY_FRONT = 2800, KEY_SETUP = 2801, KEY_WAKEUP = 2802,
KEY_SENDFILE = 2803, KEY_DELETEFILE = 2804, KEY_XFER = 2805, KEY_PROG1 = 2806,
KEY_PROG2 = 2807, KEY_MSDOS = 2808, KEY_SCREENLOCK = 2809, KEY_DIRECTION_ROTATE_DISPLAY = 2810,
KEY_CYCLEWINDOWS = 2811, KEY_COMPUTER = 2812, KEY_EJECTCLOSECD = 2813, KEY_ISO = 2814,
KEY_MOVE = 2815, KEY_F13 = 2816, KEY_F14 = 2817, KEY_F15 = 2818,
KEY_F16 = 2819, KEY_F17 = 2820, KEY_F18 = 2821, KEY_F19 = 2822,
KEY_F20 = 2823, KEY_F21 = 2824, KEY_F22 = 2825, KEY_F23 = 2826,
KEY_F24 = 2827, KEY_PROG3 = 2828, KEY_PROG4 = 2829, KEY_DASHBOARD = 2830,
KEY_SUSPEND = 2831, KEY_HP = 2832, KEY_SOUND = 2833, KEY_QUESTION = 2834,
KEY_CONNECT = 2836, KEY_SPORT = 2837, KEY_SHOP = 2838, KEY_ALTERASE = 2839,
KEY_SWITCHVIDEOMODE = 2841, KEY_BATTERY = 2842, KEY_BLUETOOTH = 2843, KEY_WLAN = 2844,
KEY_UWB = 2845, KEY_WWAN_WIMAX = 2846, KEY_RFKILL = 2847, KEY_CHANNEL = 3001,
KEY_BTN_0 = 3100, KEY_BTN_1 = 3101, KEY_BTN_2 = 3102, KEY_BTN_3 = 3103,
KEY_BTN_4 = 3104, KEY_BTN_5 = 3105, KEY_BTN_6 = 3106, KEY_BTN_7 = 3107,
KEY_BTN_8 = 3108, KEY_BTN_9 = 3109
} | Enumerates the mouse event key codes.| +| [OH_NativeXComponent_KeyAction](_o_h___native_x_component.md#oh_nativexcomponent_keyaction) { OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN = -1, OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN = 0, OH_NATIVEXCOMPONENT_KEY_ACTION_UP } | Enumerates the key event actions.| diff --git a/en/application-dev/security/huks-overview.md b/en/application-dev/security/huks-overview.md index 18a1a076bf7d33aa9f5178b9f9edded37cfc862b..b51c57abae53c09f8b4cf61b536d6b6f97bda45d 100644 --- a/en/application-dev/security/huks-overview.md +++ b/en/application-dev/security/huks-overview.md @@ -23,29 +23,29 @@ Before using the HUKS for development, you are advised to understand the followi - HUKS Core - HUKS Core is a core component that implements functions, including cryptographic calculation of keys, encryption and decryption of plaintext keys, and key access control. Generally, it runs in a secure environment (such as the TEE or security chip) of the device to ensure that the keys in plaintext are always in the HUKS Core. + HUKS Core is a core component that implements functions, including cryptographic calculation of keys, encryption and decryption of plaintext keys, and key access control. Generally, it runs in a secure environment such as a Trusted Execution Environment (TEE) or a secure chipset of the device to ensure that the keys in plaintext are always in the HUKS Core. - Key session - A key session holds information about the key operation date, key information, and access control attributes when a key is used. You need to pass in a key alias to create a session for the key. The HUKS generates a globally unique handle for each session. A general key operation involves creating a session, passing in data and parameters, and finalizing the session (or aborting the session). + A key session holds the key information, including the key operation data, key properties, and access control attributes, when a key is used. You need to pass in a key alias to create a session for the key. The HUKS generates a globally unique handle for each session. A general key operation involves creating a session, passing in data and parameters, and finishing the session (or aborting the session). ## Working Principles The security design of the HUKS includes the following: -- Always keep keys in a secure environment. +- Keys in a secure environment in lifecycle In the lifecycle of a key, the plaintext will never be exposed outside the HUKS Core. For the devices with a Trusted Execution Environment (TEE) or secure chipset, the HUKS Core runs in the TEE or secure chipset. This prevents the key plaintext from being disclosed even if the Rich Execution Environment (REE) is cracked. -- Encrypt keys for storage. +- Encrypted keys for storage The service keys are encrypted based on the device root key. Some keys can be protected by passwords if the devices support this feature. -- Apply strict access control over keys. +- Strict access control over keys Only authorized services can access keys. For security-sensitive services, user identity authentication can be enabled for key access. -- Provide key attestation. +- Key attestation - The HUKS provides attestation for hardware-backed key storage. It proves that the key has not been tampered with, is stored in the hardware-backed HUKS Core, and has correct key attributes. + The HUKS provides attestation for hardware-backed key storage. It proves that the key has not been tampered with, is stored in the hardware-backed HUKS Core, and has correct key properties. A key session is the basis for key operations in the HUKS. It initializes key information and caches the service data. Cryptographic operations on data and encryption and decryption are performed in the HUKS Core for security purposes. diff --git a/en/application-dev/ui/arkts-common-components-xcomponent.md b/en/application-dev/ui/arkts-common-components-xcomponent.md index b6bdb5633f2275fda550f7ae2c6c7f75ed420d0f..95d8f30eb1802159a76389f56519d44ef75b5261 100644 --- a/en/application-dev/ui/arkts-common-components-xcomponent.md +++ b/en/application-dev/ui/arkts-common-components-xcomponent.md @@ -205,15 +205,15 @@ XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' } > While this mode also uses the NAPI mechanism as the **import** mode, it enables you to use the NDK APIs of the **\**, by having the **NativeXComponent** instance of the **\** exposed to the native layer of the application when the dynamic library is loaded. - **onLoad** event - - Trigger time: when the surface of the **\** is prepared. + - Trigger time: when the surface of the **\** is ready. - **context** parameter: where the native API exposed on the module is mounted. Its usage is similar to the usage of the **context2** instance obtained after the module is directly loaded using **import context2 from "libnativerender.so"**. - - Time sequence: When the **onLoad** event is subject to the surface. The following figure shows the time sequence of the **onLoad** event and the **OnSurfaceCreated** event on the native side. + - Time sequence: subject to the surface. The figure below shows the time sequence of the **onLoad** event and the **OnSurfaceCreated** event at the native layer. ![onLoad](figures/onLoad.png) - **onDestroy** event - Trigger time: when the **\** is destroyed, in the same manner as that when an ArkUI component is destroyed. The following figure shows the time sequence of the **onDestroy** event and the **OnSurfaceDestroyed** event on the native side. + Trigger time: when the **\** is destroyed, in the same manner as that when an ArkUI component is destroyed. The figure below shows the time sequence of the **onDestroy** event and the **OnSurfaceDestroyed** event at the native layer. ![onDestroy](figures/onDestroy.png) @@ -222,7 +222,7 @@ XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' } The surface held by the **\** complies with the producer-consumer model. -In OpenHarmony, components that comply with the producer design, such as the camera and video player, can write data to the surface held by the **\** and display the data through the **\**. +In OpenHarmony, components that comply with the producer design, such as the Camera and AVPlayer components, can write data to the surface held by the **\** and display the data through the **\**. ![picture-1](figures/picture-1.png) diff --git a/en/application-dev/ui/arkts-drawing-customization-on-canvas.md b/en/application-dev/ui/arkts-drawing-customization-on-canvas.md index c98fa5c4886de3d32b6346c21b85b3a2ab4d4921..e0db4fefccd08eebf02f08bfaa8d839f0cc77daa 100644 --- a/en/application-dev/ui/arkts-drawing-customization-on-canvas.md +++ b/en/application-dev/ui/arkts-drawing-customization-on-canvas.md @@ -53,8 +53,8 @@ You can draw custom graphics on the canvas in any of the following ways: // Configure the parameters of the CanvasRenderingContext2D and OffscreenCanvasRenderingContext2D objects, including whether to enable anti-aliasing. The value true indicates that anti-aliasing is enabled. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - // Create an OffscreenCanvasRenderingContext2D object. width indicates the width of the offscreen canvas, and height indicates the height of the offscreen canvas. - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + // Create an OffscreenCanvas object. width indicates the width of the offscreen canvas, and height indicates the height of the offscreen canvas. + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -63,10 +63,11 @@ You can draw custom graphics on the canvas in any of the following ways: .height('100%') .backgroundColor('#F5DC62') .onReady(() =>{ + var offContext = this.offCanvas.getContext("2d", this.settings) // You can draw content here. - this.offContext.strokeRect(50, 50, 200, 150); + offContext.strokeRect(50, 50, 200, 150); // Display the image rendered by the offscreen drawing value on the common canvas. - let image = this.offContext.transferToImageBitmap(); + let image = this.offCanvas.transferToImageBitmap(); this.context.transferFromImageBitmap(image); }) } @@ -113,7 +114,7 @@ Canvas(this.context) ## Canvas Component Drawing Modes -Two modes are available for drawing with the **Canvas** component: +Two modes are available for drawing with the **Canvas** component: - After the **onReady()** callback of the **Canvas** component is invoked, use the **CanvasRenderingContext2D** and **OffscreenCanvasRenderingContext2D** objects to call related APIs for drawing. @@ -154,9 +155,8 @@ Two modes are available for drawing with the **Canvas** component: **OffscreenCanvasRenderingContext2D** and **CanvasRenderingContext2D** provide a large number of attributes and methods, which can be used to draw text and graphics and process pixels. They are the core of the **Canvas** component. Common APIs include [fill](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#fill), [clip](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#clip), and [stroke](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#stroke). In addition, [fillStyle](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#fillstyle), [globalAlpha](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#globalalpha), [strokeStyle](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#strokestyle), and more attributes are provided to spruce up the graphics. This topic describes typical usage of the canvas. - Draw a basic shape. - You can draw a basic shape by calling APIs such as [arc](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#arc), [ellipse](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse), and [rect](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#rect). - + ```ts Canvas(this.context) .width('100%') @@ -175,12 +175,12 @@ Two modes are available for drawing with the **Canvas** component: this.context.beginPath(); this.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2); this.context.stroke(); - }) - + }) + ``` - -![2023022794521(1)](figures/2023022794521(1).jpg) - + + ![2023022794521(1)](figures/2023022794521(1).jpg) + - Draw text. You can use APIs such as [fillText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#filltext) and [strokeText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext) to draw text. @@ -212,7 +212,7 @@ Two modes are available for drawing with the **Canvas** component: struct GetImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600) private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") build() { @@ -222,14 +222,15 @@ Two modes are available for drawing with the **Canvas** component: .height('100%') .backgroundColor('#F5DC62') .onReady(() =>{ + var offContext = this.offCanvas.getContext("2d", this.settings) // Use the drawImage API to draw an image in the area with the width and height of 130 starting from (0, 0). - this.offContext.drawImage(this.img,0,0,130,130); + offContext.drawImage(this.img,0,0,130,130); // Use the getImageData API to obtain the image data with the width and height of 130 starting from (50, 50). - let imagedata = this.offContext.getImageData(50,50,130,130); + let imagedata = offContext.getImageData(50,50,130,130); // Use the putImageData API to draw the obtained image data in the area starting from (150, 150). - this.offContext.putImageData(imagedata,150,150); + offContext.putImageData(imagedata,150,150); // Draw the offscreen drawing content to the canvas. - let image = this.offContext.transferToImageBitmap(); + let image = this.offCanvas.transferToImageBitmap(); this.context.transferFromImageBitmap(image); }) } diff --git a/en/application-dev/ui/figures/picture-1.png b/en/application-dev/ui/figures/picture-1.png index 85e91bba345c1b0012d0c6f031baa7ee43ef867a..427fcdf017b7eaa1e8db8edaa4554f7b796cccf2 100644 Binary files a/en/application-dev/ui/figures/picture-1.png and b/en/application-dev/ui/figures/picture-1.png differ diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 9605cdbe5ca3c083d5ac8887d45fa469943ee861..6280743a71a852222dc3b277a17b483c24b14111 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -1836,7 +1836,7 @@ - FAQs - [Full SDK Compilation Guide](faqs/full-sdk-compile-guide.md) - [Guide to Switching to Full SDK](faqs/full-sdk-switch-guide.md) - - [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](faqs/howto-migrate-cmake-with-ohosndk.md) + - [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](faqs/cmake-with-ndk.md) - [Application Model Development](faqs/faqs-ability.md) - ArkUI Framework Development (ArkTS) - [ArkTS Syntax Usage](faqs/faqs-arkui-arkts.md) diff --git a/en/device-dev/Readme-EN.md b/en/device-dev/Readme-EN.md index 34f88884dbf49b2738e335a250b9c5bc4cc0ed92..f259aa35bc14089cdb69439971c55a3278942634 100644 --- a/en/device-dev/Readme-EN.md +++ b/en/device-dev/Readme-EN.md @@ -34,7 +34,7 @@ - [Kernel for the Standard System](kernel/kernel-standard-overview.md) - [Driver](driver/Readme-EN.md) - [Compilation and Building](subsystems/subsys-build-all.md) - - [Distributed Remote Startup](subsystems/subsys-remote-start.md) + - [ArkUI](subsystems/subsys-arkui-customize_titlebar.md) - [Graphics](subsystems/subsys-graphics-overview.md) - [Multimedia](subsystems/subsys-multimedia-camera-overview.md) - [Utils](subsystems/subsys-utils-guide.md) @@ -52,10 +52,8 @@ - [Mini- and Small-System Devices](guide/device-wlan-led-control.md) - [Standard-System Devices](guide/device-clock-guide.md) - Debugging - - [Test Case Development](device-test/developer_test.md) + - [Device Test](device-test/Readme-EN.md) - [R&D Tools](subsystems/subsys-toolchain-hdc-guide.md) -- XTS Certification - - [XTS Test Case Development](device-test/xts.md) - Tools - [Docker Environment](get-code/gettools-acquire.md) - [IDE](get-code/gettools-ide.md) diff --git a/en/device-dev/device-test/developer_test.md b/en/device-dev/device-test/developer_test.md index d9e0550b975785a9946c057980c608054e6fdda3..a3d699e62c32a222ab10d8a8c24cf0babd48267d 100644 --- a/en/device-dev/device-test/developer_test.md +++ b/en/device-dev/device-test/developer_test.md @@ -8,7 +8,7 @@ OpenHarmony provides you with a comprehensive development self-test framework ** This document describes how to use the development self-test framework of OpenHarmony. -### Introduction +### Overview After adding or modifying code, OpenHarmony developers want to quickly verify whether the modified code functions properly, and the system already has a large number of automated test cases of existing functions, such as TDD cases and XTS cases. The development self-test framework aims to help you improve your self-test efficiency so that you can quickly execute the specified automated test cases and conducting development tests at the development phase. @@ -18,7 +18,7 @@ After adding or modifying code, OpenHarmony developers want to quickly verify wh When executing test cases using the framework, you must connect to the OpenHarmony device in advance. -## Environment Preparations +## Environment Setup The development self-test framework depends on the Python environment. It is required that the Python version be 3.7.5 or later. Before using the framework, you can refer to the following document for configuration. @@ -28,16 +28,20 @@ Click [here](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-co | Environment Dependency | Version | Description | | ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Operating system | Ubuntu 18.04 or later | Code compilation environment. | +| Operating system | Ubuntu 20.04 or later | Code compilation environment. | | Linux extension component| libreadline-dev | Plugin used to read commands. | | python | 3.7.5 or later | Language used by the test framework. | | Python plugins | pyserial 3.3 or later, paramiko 2.7.1 or later, setuptools 40.8.0 or later, and rsa4.0 or later| - **pserial**: supports Python serial port communication.
- **paramiko**: allows Python to use SSH.
- **setuptools**: allows Python packages to be created and distributed easily.
- **rsa**: implements RSA encryption in Python.| | NFS Server | haneWIN NFS Server 1.2.50 or later or NFS v4 or later | Devices can be connected using serial ports. Mini- and small-system devices are used. | -| HDC | 1.1.0 | A tool that enables devices to be connected through the HarmonyOS Device Connector (HDC). | +| HDC | 1.2.0a | A tool that enables devices to be connected through the OpenHarmony Device Connector (HDC). | -1. Run the following command to install the Linux extended component readline: +1. Install Ubuntu. + + As Ubuntu 20 has built-in Python 3.8.5, you do not need to install Python separately. + +2. Run the following command to install the Linux extended component readline: ```bash sudo apt-get install libreadline-dev @@ -91,7 +95,9 @@ Click [here](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-co 6. Install the NFS server if the device outputs results only through the serial port. - > This step is applicable to small-system or mini-system devices. + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > This operation applies to small-system or mini-system devices, not standard-system devices. - Windows OS: Install the **haneWIN NFS Server1.2.50** package. - Linux OS: Run the following command to install the NFS server: @@ -107,299 +113,34 @@ Click [here](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-co 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. ``` -7. If the device supports HDC connection, install the HDC tool. For details about the installation process, see [HDC-OpenHarmony device connector](https://gitee.com/openharmony/developtools_hdc/blob/master/README.md). +7. If the device supports HDC connection, install the HDC tool. For details about the installation process, see [HDC-OpenHarmony Device Connector](https://gitee.com/openharmony/developtools_hdc/blob/master/README.md). ### Environment Dependency Check -| Check Item | Operation | Requirement | +| Check Item | Action | Requirement | | -------------------------------------------------- | --------------------------------------------------- | ------------------------- | | Check whether Python is installed successfully. | Run the **python --version** command. | The Python version is 3.7.5 or later. | | Check whether Python plugins are successfully installed. | Go to the **test/developertest** directory and run **start.bat** or **start.sh**.| The **>>>** prompt is displayed.| | Check the NFS server status (for the devices that support only serial port output).| Log in to the development board through the serial port and run the **mount** command to mount the NFS. | The file directory can be mounted. | -| Check whether the HDC is successfully installed. | Run the **hdc_std -v** command. | The HDC version is 1.1.0 or later. | +| Check whether the HDC is successfully installed. | Run the **hdc -v** command. | The HDC version is 1.2.0a or later. | ## Test Case Preparation -The test framework supports multiple types of tests and provides different test case templates for them._ +The test framework supports multiple types of tests and provides different test case templates for them. **TDD Test (C++)** -Naming rules for source files - -The source file name of test cases must be the same as that of the test suite. The file names must use lowercase letters and in the *Function*_*Sub-function*_**test** format. More specific sub-functions can be added as required. -Example: -``` -calculator_sub_test.cpp -``` - -Test case example -```c++ -/* - * Copyright (c) 2021 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "calculator.h" -#include - -using namespace testing::ext; - -class CalculatorSubTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void CalculatorSubTest::SetUpTestCase(void) -{ - // Set a setup function, which will be called before all test cases. -} - -void CalculatorSubTest::TearDownTestCase(void) -{ - // Set a teardown function, which will be called after all test cases. -} - -void CalculatorSubTest::SetUp(void) -{ - // Set a setup function, which will be called before all test cases. -} - -void CalculatorSubTest::TearDown(void) -{ - // Set a teardown function, which will be called after all test cases. -} - -/** - * @tc.name: integer_sub_001 - * @tc.desc: Verify the sub function. - * @tc.type: FUNC - * @tc.require: issueNumber - */ -HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) -{ - // Step 1 Call the function to obtain the test result. - int actual = Sub(4, 0); - - // Step 2 Use an assertion to compare the obtained result with the expected result. - EXPECT_EQ(4, actual); -} -``` -The procedure is as follows: - -1. Add comment information to the test case file header. - -``` -/* - * Copyright (c) 2021 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -``` - -2. Add the test framework header file and namespace. - -```c++ -#include - -using namespace testing::ext; -``` - -3. Add the header file of the test class. - -```c++ -#include "calculator.h" -``` - -4. Define the test suite (test class). - -```c++ -class CalculatorSubTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void CalculatorSubTest::SetUpTestCase(void) -{ - // Set a setup function, which will be called before all test cases. -} - -void CalculatorSubTest::TearDownTestCase(void) -{ - // Set a teardown function, which will be called after all test cases. -} - -void CalculatorSubTest::SetUp(void) -{ - // Set a setup function, which will be called before all test cases. -} - -void CalculatorSubTest::TearDown(void) -{ - // Set a teardown function, which will be called after all test cases. -}== -``` -> **NOTE** -> -> When defining a test suite, ensure that the test suite name is the same as the target to build and uses the upper camel case style. - -5. Add implementation of the test cases, including test case comments and logic. - -```c++ -/** - * @tc.name: integer_sub_001 - * @tc.desc: Verify the sub function. - * @tc.type: FUNC - * @tc.require: issueNumber - */ -HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) -{ - // Step 1 Call the function to obtain the test result. - int actual = Sub(4, 0); - - // Step 2 Use an assertion to compare the obtained result with the expected result. - EXPECT_EQ(4, actual); -} -``` -> **NOTE** -> -> @tc.require: The format must be started with **AR/SR** or **issue**, for example, **issueI56WJ7**. - -The following test case templates are provided for your reference. - -| Type | Description | -| --------------- | ------------------------------------------------ | -| HWTEST(A,B,C) | Use this template if the test case execution does not depend on setup or teardown. | -| HWTEST_F(A,B,C) | Use this template if the test case execution (excluding parameters) depends on setup or teardown.| -| HWTEST_P(A,B,C) | Use this template if the test case execution (including parameters) depends on setup or teardown. | - -In the template names: - -- **A** indicates the test suite name. - -- **B** indicates the test case name, which is in the *Function*_*No.* format. The *No.* is a three-digit number starting from **001**. - -- *C* indicates the test case level. There are five test case levels: guard-control level 0 and non-guard-control level 1 to level 4. Of levels 1 to 4, a smaller value indicates a more important function verified by the test case. - - -**NOTE** - -- The expected result of each test case must have an assertion. - -- The test case level must be specified. - -- It is recommended that the test be implemented step by step according to the template. - -- The comment must contain the test case name, description, type, and requirement number, which are in the @tc.*xxx*: *value* format. The test case type @**tc.type** can be any of the following: - - -| Test Case Type| Code| -| ------------ | -------- | -| Function test | FUNC | -| Performance test | PERF | -| Reliability test | RELI | -| Security test | SECU | -| Fuzzing test | FUZZ | - -**TDD Test (JS)** - - Naming rules for source files + The source file name of test cases must be the same as that of the test suite. The file names must use lowercase letters and in the [Function]\_[Sub-function]\_**test** format. More specific sub-functions can be added as required. -The source file name of a test case must be in the *Function**Sub-function***Test** format, and each part must use the upper camel case style. More specific sub-functions can be added as required. -Example: -``` -AppInfoTest.js -``` - -- Test case example -```js -/* - * Copyright (C) 2021 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import app from '@system.app' - -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - -describe("AppInfoTest", function () { - beforeAll(function() { - // Set a setup function, which will be called before all test cases. - console.info('beforeAll caled') - }) - - afterAll(function() { - // Set a teardown function, which will be called after all test cases. - console.info('afterAll caled') - }) - - beforeEach(function() { - // Set a setup function, which will be called before all test cases. - console.info('beforeEach caled') - }) - - afterEach(function() { - // Set a teardown function, which will be called after all test cases. - console.info('afterEach caled') - }) - - /* - * @tc.name:appInfoTest001 - * @tc.desc:verify app info is not null - * @tc.type: FUNC - * @tc.require: issueNumber - */ - it("appInfoTest001", 0, function () { - // Step 1 Call the function to obtain the test result. - var info = app.getInfo() - - // Step 2 Use an assertion to compare the obtained result with the expected result. - expect(info != null).assertEqual(true) - }) -}) -``` -The procedure is as follows: -1. Add comment information to the test case file header. +- The following uses **calculator_sub_test.cpp** as an example to describe how to compile a single-thread test case: ``` /* - * Copyright (C) 2021 XXXX Device Co., Ltd. + * Copyright (c) 2023 XXXX Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -412,55 +153,446 @@ The procedure is as follows: * See the License for the specific language governing permissions and * limitations under the License. */ - ``` -2. Import the APIs and JSUnit test library to test. - ```js - import app from '@system.app' - import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - ``` -3. Define the test suite (test class). - ```js - describe("AppInfoTest", function () { - beforeAll(function() { - // Set a setup function, which will be called before all test cases. - console.info('beforeAll caled') - }) - - afterAll(function() { - // Set a teardown function, which will be called after all test cases. - console.info('afterAll caled') - }) - - beforeEach(function() { - // Set a setup function, which will be called before all test cases. - console.info('beforeEach caled') - }) - - afterEach(function() { - // Set a teardown function, which will be called after all test cases. - console.info('afterEach caled') - }) - ``` -4. Add implementation of the test cases. - ```JS - /* - * @tc.name:appInfoTest001 - * @tc.desc:verify app info is not null + #include "calculator.h" + #include + + using namespace testing::ext; + + class CalculatorSubTest : public testing::Test { + public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + }; + + void CalculatorSubTest::SetUpTestCase(void) + { + // Set a setup function, which will be called before all test cases. + } + + void CalculatorSubTest::TearDownTestCase(void) + { + // Set a teardown function, which will be called after all test cases. + } + + void CalculatorSubTest::SetUp(void) + { + // Set a setup function, which will be called before all test cases. + } + + void CalculatorSubTest::TearDown(void) + { + // Set a teardown function, which will be called after all test cases. + } + + /** + * @tc.name: integer_sub_001 + * @tc.desc: Verify the sub function. * @tc.type: FUNC * @tc.require: issueNumber */ - it("appInfoTest001", 0, function () { + HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) + { // Step 1 Call the function to obtain the test result. - var info = app.getInfo() + int actual = Sub(4, 0); // Step 2 Use an assertion to compare the obtained result with the expected result. - expect(info != null).assertEqual(true) - }) + EXPECT_EQ(4, actual); + } ``` - > **NOTE** - > - > @tc.require: The format must be started with **issue**, for example, **issueI56WJ7**. + The procedure is as follows: + 1. Add comment information to the test case file header. + ``` + /* + * Copyright (c) 2023 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + ``` + 2. Add the test framework header file and namespace. + ``` + #include + + using namespace testing::ext; + ``` + 3. Add the header file of the test class. + ``` + #include "calculator.h" + ``` + 4. Define the test suite (test class). + > When defining a test suite, ensure that the test suite name is the same as the target to build and uses the upper camel case style. + ``` + class CalculatorSubTest : public testing::Test { + public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + }; + + void CalculatorSubTest::SetUpTestCase(void) + { + // Set a setup function, which will be called before all test cases. + } + + void CalculatorSubTest::TearDownTestCase(void) + { + // Set a teardown function, which will be called after all test cases. + } + + void CalculatorSubTest::SetUp(void) + { + // Set a setup function, which will be called before all test cases. + } + + void CalculatorSubTest::TearDown(void) + { + // Set a teardown function, which will be called after all test cases. + } + ``` + + 5. Add implementation of the test cases, including test case comments and logic. + ``` + /** + * @tc.name: integer_sub_001 + * @tc.desc: Verify the sub function. + * @tc.type: FUNC + * @tc.require: issueNumber + */ + HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) + { + // Step 1 Call the function to obtain the test result. + int actual = Sub(4, 0); + + // Step 2 Use an assertion to compare the obtained result with the expected result. + EXPECT_EQ(4, actual); + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > The value of **@tc.require** must start with AR/SR or issue, for example, **issueI56WJ7**. + +- The following uses base_object_test.cpp as an example to describe how to compile a multi-thread test case: + ``` + // The test case file header comment and test case comment are the same as those in the single-thread test case example. + + #include "base_object.h" + #include + #include + #include + + using namespace testing::ext; + using namespace testing::mt; + + namespace OHOS { + namespace AAFwk { + class AAFwkBaseObjectTest : public testing::Test {......} + + // Step 1 Set the function to be tested to return the factorial result. + int factorial(int n) + { + int result = 1; + for (int i = 1; i <= n; i++) { + result *= i; + } + printf("Factorial Function Result : %d! = %d\n", n, result); + return result; + } + + // Step 2 Use an assertion to compare the obtained result with the expected result. + void factorial_test() + { + int ret = factorial(3); // Call the function to obtain the result. + std::thread::id this_id = std::this_thread::get_id(); + std::ostringstream oss; + oss << this_id; + std::string this_id_str = oss.str(); + long int thread_id = atol(this_id_str.c_str()); + printf("running thread...: %ld\n", thread_id); // Output the ID of the running thread. + EXPECT_EQ(ret, 6); + } + + HWTEST_F(AAFwkBaseObjectTest, Factorial_test_001, TestSize.Level1) + { + SET_THREAD_NUM(4); + printf("Factorial_test_001 BEGIN\n"); + GTEST_RUN_TASK(factorial_test); + printf("Factorial_test_001 END\n"); + } + + HWMTEST_F(AAFwkBaseObjectTest, Factorial_test_002, TestSize.Level1, 6) + { + printf("Factorial_test_002 BEGIN\n"); + factorial_test(); + printf("Factorial_test_002 END\n"); + } + + } // namespace AAFwk + } // namespace OHOS + + ``` + The procedure is as follows: + 1. Add comment information to the test case file header. + + > **NOTE**
The standard is the same as that of the single-thread test case. + + 2. Add the test framework header file and namespace. + ``` + #include + #include + #include + using namespace testing::ext; + using namespace testing::mt; + ``` + 3. Add the header file of the test class. + ``` + #include "base_object.h" + ``` + 4. Define the test suite (test class). + ``` + class AAFwkBaseObjectTest : public testing::Test {......} + + ``` + > **NOTE**
The standard is the same as that of the single-thread test case. + + 5. Add implementation of the test cases, including test case comments and logic. + + ``` + // Step 1 Set the function to be tested to return the factorial result. + int factorial(int n) + { + int result = 1; + for (int i = 1; i <= n; i++) { + result *= i; + } + printf("Factorial Function Result : %d! = %d\n", n, result); + return result; + } + + // Step 2 Use an assertion to compare the obtained result with the expected result. + void factorial_test() + { + int ret = factorial(3); // Call the function to obtain the result. + std::thread::id this_id = std::this_thread::get_id(); + std::ostringstream oss; + oss << this_id; + std::string this_id_str = oss.str(); + long int thread_id = atol(this_id_str.c_str()); + printf("running thread...: %ld\n", thread_id); // Output the ID of the running thread. + EXPECT_EQ(ret, 6); + } + + // GTEST_RUN_TASK(TestFunction) is a multi-thread startup function. The parameter is a custom function. + // If SET_THREAD_NUM() is not called, the default value 10 will be used. + HWTEST_F(AAFwkBaseObjectTest, Factorial_test_001, TestSize.Level1) + { + SET_THREAD_NUM(4); // Set the number of threads. It can be dynamically set in the same test suite. + printf("Factorial_test_001 BEGIN\n"); + GTEST_RUN_TASK(factorial_test); // Start the multi-thread execution of the factorial_test task. + printf("Factorial_test_001 END\n"); + } + + // HWMTEST_F(TEST_SUITE, TEST_TC, TEST_LEVEL, THREAD_NUM) + // THREAD_NUM can be used to set the number of threads for executing a test case. + // HWMTEST_F creates a specified number of threads and executes the tested function. + HWMTEST_F(AAFwkBaseObjectTest, Factorial_test_002, TestSize.Level1, 6) + { + printf("Factorial_test_002 BEGIN\n"); + factorial_test(); + printf("Factorial_test_002 END\n"); + } + // Add the multi-thread API MTEST_ADD_TASK(THREAD_ID,ThreadTestFunc). Multiple threads are registered but are not executed in this test case. Instead, they are executed later in a unified manner. This API is applicable to the multi-thread test in the scenario where multiple test cases are combined. + // THREAD_ID is used to distinguish threads and starts from 0. You can also use a random thread ID by passing in RANDOM_THREAD_ID. In this scenario, each thread ID is unique. + // Add the multi-thread API MTEST_POST_RUN() to execute the previously registered threads in a unified manner. + ``` + > **NOTE**
The comments for multi-thread test cases are the same as those of single-thread test cases. + +- About C++ test case templates: + + The following test case templates are provided for your reference. + + | Type| Description| + | ------------| ------------| + | HWTEST(A,B,C)| Use this template if the test case execution does not depend on setup or teardown.| + | HWTEST_F(A,B,C)| Use this template if the test case execution (excluding parameters) depends on setup and teardown.| + | HWMTEST_F(A,B,C,D)| Use this template if the multi-thread test case execution depends on setup and teardown.| + | HWTEST_P(A,B,C)| Use this template if the test case execution (including parameters) depends on setup and teardown.| + + + In the template names: + + - **A** indicates the test suite name. + + - **B** indicates the test case name, which is in the *Function*_*No.* format. The *No.* is a three-digit number starting from **001**. + + - **C** indicates the test case level. There are five test case levels: guard-control level 0 and non-guard-control level 1 to level 4. Of levels 1 to 4, a smaller value indicates a more important function verified by the test case. + + - **D** indicates the number of threads for executing the multi-thread test case. + + **Note**: + + - The expected result of each test case must have an assertion. + + - The test case level must be specified. + + - It is recommended that the test be implemented step by step according to the template. + + - The test case description is in the standard @tc.*xxx* *value* format. The comment must contain the test case name, description, type, and requirement number. The test case type @tc.type can be any of the following: + + + | Test Case Type | Code | + | ------------ | -------- | + | Function test | FUNC | + | Performance Test | PERF | + | Reliability test | RELI | + | Security Test | SECU | + | Fuzz test | FUZZ | + +**TDD Test (JavaScript)** + +- Naming rules for source files + + + The source file name of a test case must be in the [Function][Sub-function]**Test** format, and each part must use the upper camel case style. More specific sub-functions can be added as required. + Example: + ``` + AppInfoTest.js + ``` + +- Test case example + + ```js + /* + * Copyright (C) 2023 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import app from '@system.app' + + import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + + describe("AppInfoTest", function () { + beforeAll(function() { + // Set a setup function, which will be called before all test cases. + console.info('beforeAll caled') + }) + + afterAll(function() { + // Set a teardown function, which will be called after all test cases. + console.info('afterAll caled') + }) + + beforeEach(function() { + // Set a setup function, which will be called before all test cases. + console.info('beforeEach caled') + }) + + afterEach(function() { + // Set a teardown function, which will be called after all test cases. + console.info('afterEach caled') + }) + + /* + * @tc.name:appInfoTest001 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: issueNumber + */ + it("appInfoTest001", 0, function () { + // Step 1 Call the function to obtain the test result. + var info = app.getInfo() + + // Step 2 Use an assertion to compare the obtained result with the expected result. + expect(info != null).assertEqual(true) + }) + }) + ``` + The procedure is as follows: + 1. Add comment information to the test case file header. + ``` + /* + * Copyright (C) 2023 XXXX Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + ``` + 2. Import the APIs and JSUnit test library to test. + ```js + import app from '@system.app' + + import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + ``` + 3. Define the test suite (test class). + ```js + describe("AppInfoTest", function () { + beforeAll(function() { + // Set a setup function, which will be called before all test cases. + console.info('beforeAll caled') + }) + + afterAll(function() { + // Set a teardown function, which will be called after all test cases. + console.info('afterAll caled') + }) + + beforeEach(function() { + // Set a setup function, which will be called before all test cases. + console.info('beforeEach caled') + }) + + afterEach(function() { + // Set a teardown function, which will be called after all test cases. + console.info('afterEach caled') + }) + ``` + 4. Write test cases + ```JS + /* + * @tc.name:appInfoTest001 + * @tc.desc:verify app info is not null + * @tc.type: FUNC + * @tc.require: issueNumber + */ + it("appInfoTest001", 0, function () { + // Step 1 Call the function to obtain the test result. + var info = app.getInfo() + + // Step 2 Use an assertion to compare the obtained result with the expected result. + expect(info != null).assertEqual(true) + }) + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > The value of **@tc.require** must start with AR/SR or issue, for example, **issueI56WJ7**. **Fuzzing Test** @@ -481,325 +613,447 @@ The following provides templates for different languages for your reference. - **Test case build file example (C++)** -``` -# Copyright (c) 2021 XXXX Device Co., Ltd. - -import("//build/test.gni") + ``` + # Copyright (c) 2023 XXXX Device Co., Ltd. -module_output_path = "developertest/calculator" + import("//build/test.gni") -config("module_private_config") { - visibility = [ ":*" ] + module_output_path = "developertest/calculator" - include_dirs = [ "../../../include" ] -} + config("module_private_config") { + visibility = [ ":*" ] -ohos_unittest("CalculatorSubTest") { - module_out_path = module_output_path + include_dirs = [ "../../../include" ] + } - sources = [ - "../../../include/calculator.h", - "../../../src/calculator.cpp", - ] + ohos_unittest("CalculatorSubTest") { + module_out_path = module_output_path - sources += [ "calculator_sub_test.cpp" ] + sources = [ + "../../../include/calculator.h", + "../../../src/calculator.cpp", + ] - configs = [ ":module_private_config" ] + sources += [ "calculator_sub_test.cpp" ] - deps = [ "//third_party/googletest:gtest_main" ] -} + configs = [ ":module_private_config" ] -group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] -} -``` -The procedure is as follows: + deps = [ "//third_party/googletest:gtest_main" ] + } -1. Add comment information for the file header. - ``` - # Copyright (c) 2021 XXXX Device Co., Ltd. - ``` -2. Import the build template. - ``` - import("//build/test.gni") - ``` -3. Specify the file output path. - ``` - module_output_path = "developertest/calculator" - ``` - > **NOTE**
The output path is ***Part name*/*Module name***. - -4. Configure the directories for dependencies. - - ``` - config("module_private_config") { - visibility = [ ":*" ] - - include_dirs = [ "../../../include" ] - } - ``` - > **NOTE** - > - > Generally, the dependency directories are configured here and directly referenced in the build script of the test case. - -5. Set the output build file for the test cases. - - ``` - ohos_unittest("CalculatorSubTest") { - } - ``` -6. Write the build script (add the source file, configuration, and dependencies) for the test cases. - ``` - ohos_unittest("CalculatorSubTest") { - module_out_path = module_output_path - sources = [ - "../../../include/calculator.h", - "../../../src/calculator.cpp", - "../../../test/calculator_sub_test.cpp" - ] - sources += [ "calculator_sub_test.cpp" ] - configs = [ ":module_private_config" ] - deps = [ "//third_party/googletest:gtest_main" ] - } - ``` - - > **NOTE** - > - > Set the test type based on actual requirements. The following test types are available: - > - > - **ohos_unittest**: unit test - > - **ohos_moduletest**: module test - > - **ohos_systemtest**: system test - > - **ohos_performancetest**: performance test - > - **ohos_securitytest**: security test - > - **ohos_reliabilitytest**: reliability test - > - **ohos_distributedtest**: distributed test - -7. Group the test case files by test type. - - ``` - group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] - } - ``` - > **NOTE** - > - > Grouping test cases by test type allows you to execute a specific type of test cases when required. + group("unittest") { + testonly = true + deps = [":CalculatorSubTest"] + } + ``` + The procedure is as follows: + + 1. Add comment information for the file header. + ``` + # Copyright (c) 2023 XXXX Device Co., Ltd. + ``` + 2. Import the build template. + ``` + import("//build/test.gni") + ``` + 3. Specify the file output path. + ``` + module_output_path = "developertest/calculator" + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > The output path is the *Part name*/*Module name*. + + 4. Configure the directories for dependencies. + + ``` + config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ "../../../include" ] + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Generally, the dependency directories are configured here and directly referenced in the build script of the test case. + + 5. Set the output build file for the test cases. + + ``` + ohos_unittest("CalculatorSubTest") { + } + ``` + 6. Write the build script (add the source file, configuration, and dependencies) for the test cases. + ``` + ohos_unittest("CalculatorSubTest") { + module_out_path = module_output_path + sources = [ + "../../../include/calculator.h", + "../../../src/calculator.cpp", + "../../../test/calculator_sub_test.cpp" + ] + sources += [ "calculator_sub_test.cpp" ] + configs = [ ":module_private_config" ] + deps = [ "//third_party/googletest:gtest_main" ] + } + ``` + + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Set the test type based on actual requirements. The following test types are available: + > - **ohos_unittest**: unit test + > - **ohos_js_unittest**: FA model JS unit test + > - **ohos_js_stage_unittest**: stage model ArkTS unit test + > - **ohos_moduletest**: module test + > - **ohos_systemtest**: system test + > - **ohos_performancetest**: performance test + > - **ohos_securitytest**: security test + > - **ohos_reliabilitytest**: reliability test + > - **ohos_distributedtest**: distributed test + + 7. Group the test case files by test type. + + ``` + group("unittest") { + testonly = true + deps = [":CalculatorSubTest"] + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Grouping test cases by test type allows you to execute a specific type of test cases when required. - **Test case build file example (JavaScript)** -``` -# Copyright (C) 2021 XXXX Device Co., Ltd. - -import("//build/test.gni") - -module_output_path = "developertest/app_info" - -ohos_js_unittest("GetAppInfoJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" -} - -group("unittest") { - testonly = true - deps = [ ":GetAppInfoJsTest" ] -} -``` - -The procedure is as follows: - -1. Add comment information for the file header. - -``` -# Copyright (C) 2021 XXXX Device Co., Ltd. -``` + ``` + # Copyright (C) 2023 XXXX Device Co., Ltd. -2. Import the build template. + import("//build/test.gni") -``` -import("//build/test.gni") -``` + module_output_path = "developertest/app_info" -3. Specify the file output path. + ohos_js_unittest("GetAppInfoJsTest") { + module_out_path = module_output_path -``` -module_output_path = "developertest/app_info" -``` -> **NOTE** -> -> The output path is ***Part name*/*Module name***. + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" + } -4. Set the output build file for the test cases. + group("unittest") { + testonly = true + deps = [ ":GetAppInfoJsTest" ] + } + ``` -``` -ohos_js_unittest("GetAppInfoJsTest") { -} -``` -> **NOTE** -> - Use the **ohos_js_unittest** template to define the JavaScript test suite. Pay attention to the difference between JavaScript and C++. -> - The file generated for the JavaScript test suite must be in .hap format and named after the test suite name defined here. The test suite name must end with **JsTest**. + The procedure is as follows: + + 1. Add comment information for the file header. + + ``` + # Copyright (C) 2023 XXXX Device Co., Ltd. + ``` + + 2. Import the build template. + + ``` + import("//build/test.gni") + ``` + + 3. Specify the file output path. + + ``` + module_output_path = "developertest/app_info" + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > The output path is the *Part name*/*Module name*. + + 4. Set the output build file for the test cases. + + ``` + ohos_js_unittest("GetAppInfoJsTest") { + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > - Use the **ohos_js_unittest** template to define the JavaScript test suite. Pay attention to the difference between JavaScript and C++. + > - The file generated for the JavaScript test suite must be in .hap format and named after the test suite name defined here. The test suite name must end with **JsTest**. + + 5. Configure the **config.json** file and signature file, which are mandatory. + + ``` + ohos_js_unittest("GetAppInfoJsTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" + } + ``` + **config.json** is the configuration file required for HAP build. You need to set **target** based on the tested SDK version. Default values can be retained for other items. The following is an example: + + ```json + { + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5 // Set it based on the tested SDK version. In this example, SDK5 is used. + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } + } + ``` + + 6. Group the test case files by test type. + + ``` + group("unittest") { + testonly = true + deps = [ ":GetAppInfoJsTest" ] + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Grouping test cases by test type allows you to execute a specific type of test cases when required. + +- **Example of ArkTS case compilation configuration for the stage model** -5. Configure the **config.json** file and signature file, which are mandatory. + ``` + # Copyright (C) 2023 XXXX Device Co., Ltd. + + import("//build/test.gni") -``` -ohos_js_unittest("GetAppInfoJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" -} -``` -**config.json** is the configuration file required for HAP build. You need to set **target** based on the tested SDK version. Default values can be retained for other items. The following is an example: - -```json -{ - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 // Set it based on the tested SDK version. In this example, SDK5 is used. + want_output_path = "developertest/stage_test" + + ohos_js_stage_unittest("ActsBundleMgrStageEtsTest") { + hap_profile = "entry/src/main/module.json" + deps = [ + ":actbmsstageetstest_js_assets", + ":actbmsstageetstest_resources", + ] + ets2abc = true + certificate_profile = "signature/openharmony_sx.p7b" + hap_name = "ActsBundleMgrStageEtsTest" + subsystem_name = "developertest" + part_name = "stage_test" + module_out_path = want_output_path } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication", - "name": ".MyApplication", - "deviceType": [ - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "MyApplication", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] + ohos_app_scope("actbmsstageetstest_app_profile") { + app_profile = "AppScope/app.json" + sources = [ "AppScope/resources" ] } - } -``` - -6. Group the test case files by test type. - -``` -group("unittest") { - testonly = true - deps = [ ":GetAppInfoJsTest" ] -} -``` -> **NOTE** -> -> Grouping test cases by test type allows you to execute a specific type of test cases when required. - -**Fuzzing Test** - -[Fuzzing case specifications](https://gitee.com/openharmony/test_developertest/blob/master/libs/fuzzlib/README_zh.md) - -**Benchmark Test** - -[Benchmark case specifications](https://gitee.com/openharmony/test_developertest/blob/master/libs/benchmark/README_zh.md) - - -**Configuring ohos.build** + ohos_js_assets("actbmsstageetstest_js_assets") { + source_dir = "entry/src/main/ets" + } + ohos_resources("actbmsstageetstest_resources") { + sources = [ "entry/src/main/resources" ] + deps = [ ":actbmsstageetstest_app_profile" ] + hap_profile = "entry/src/main/module.json" + } + group("unittest") { + testonly = true + deps = [] + deps += [ ":ActsBundleMgrStageEtsTest" ] + } + ``` + The procedure is as follows: + + 1. Add comment information for the file header. + + ``` + # Copyright (C) 2023 XXXX Device Co., Ltd. + ``` + + 2. Import the build template. + + ``` + import("//build/test.gni") + ``` + + 3. Specify the file output path. + + ``` + want_output_path = "developertest/stage_test" + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > The output path is the *Part name*/*Module name*. + + 4. Set the output build file for the test cases. + + ``` + ohos_js_stage_unittest("ActsBundleMgrStageEtsTest") { + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Use the **ohos_js_stage_unittest** template to define the ArkTS test suite for the stage model. + + 5. Specify the configuration file **module.json**, signature file, part name, and compilation output path, which are all mandatory. + + ``` + ohos_js_stage_unittest("ActsBundleMgrStageEtsTest") { + hap_profile = "entry/src/main/module.json" + certificate_profile = "signature/openharmony_sx.p7b" + subsystem_name = "developertest" + part_name = "stage_test" // Part name + } + ``` + + 6. Specify the configuration resource file (add the source files, configurations, and dependencies). + ``` + # Declare an AppScope module for the HAP. Those specified by app_profile and sources will be combined to a specific entry file for compilation. + ohos_app_scope("actbmsstageetstest_app_profile") { + app_profile = "AppScope/app.json" + sources = [ "AppScope/resources" ] + } + + # Place the test case code for the stage model in the ets directory. + ohos_js_assets("actbmsstageetstest_js_assets") { + source_dir = "entry/src/main/ets" + } + + # Source files are stored in the resources directory after compilation in the stage model. + ohos_resources("actbmsstageetstest_resources") { + sources = [ "entry/src/main/resources" ] + deps = [ ":actbmsstageetstest_app_profile" ] + hap_profile = "entry/src/main/module.json" + } + + ``` + + 7. Group the test case files by test type. + + ``` + group("unittest") { + testonly = true + deps = [ ":GetAppInfoJsTest" ] + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Grouping test cases by test type allows you to execute a specific type of test cases when required. + +**Configuring bundle.json** Configure the part build file to associate with specific test cases. ``` -"partA": { - "module_list": [ - +"build": { + "sub_component": [ + "//test/testfwk/developer_test/examples/app_info:app_info", + "//test/testfwk/developer_test/examples/detector:detector", + "//test/testfwk/developer_test/examples/calculator:calculator" ], "inner_list": [ - - ], - "system_kits": [ - + { + "header": { + "header_base": "////test/testfwk/developer_test/examples/detector/include", + "header_files": [ + "detector.h" + ] + }, + "name": "//test/testfwk/developer_test/examples/detector:detector" + } ], - "test_list": [ // Test under configuration module calculator. - "//system/subsystem/partA/calculator/test:unittest", - "//system/subsystem/partA/calculator/test:fuzztest", - "//system/subsystem/partA/calculator/test:benchmarktest" + "test": [ // Test under configuration module calculator. + "//test/testfwk/developer_test/examples/app_info/test:unittest", + "//test/testfwk/developer_test/examples/calculator/test:unittest", + "//test/testfwk/developer_test/examples/calculator/test:fuzztest" } ``` -> **NOTE**
**test_list** contains the test cases of the corresponding module. +> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> +> **test_list** contains the test cases of the corresponding module. ## Configuring Test Resources -Test resources include external file resources, such as image files, video files, and third-party libraries, required for test case execution. +The test resources mainly include external file resources such as image files, video files, and third-party libraries required during test case execution. Currently, only static resources can be configured. Perform the following steps: -1. Create a **resource** directory under the **test** directory of the part, create a corresponding module directory under the **resource** directory, and store the resource files required in this module directory. +1. Create the **resource** directory in the **test** directory of the part, and create a directory for the module in the **resource** directory to store resource files of the module. 2. In the module directory under **resource**, create the **ohos_test.xml** file in the following format: -```xml - - - - - - - -``` + ```xml + + + + + + + + ``` -3. In the build file of the test cases, configure **resource_config_file** to point to the resource file **ohos_test.xml**. + 3. In the build file of the test cases, configure **resource_config_file** to point to the resource file **ohos_test.xml**. -``` -ohos_unittest("CalculatorSubTest") { - resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" -} -``` ->**NOTE** ->- **target_name** indicates the test suite name defined in the **BUILD.gn** file in the **test** directory. **preparer** indicates the action to perform before the test suite is executed. ->- **src="res"** indicates that the test resources are in the **resource** directory under the **test** directory. **src="out"** indicates that the test resources are in the **out/release/$(*part*)** directory. + ``` + ohos_unittest("CalculatorSubTest") { + resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" + } + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + >- **target_name** indicates the test suite name defined in the **BUILD.gn** file in the **test** directory. **preparer** indicates the action to perform before the test suite is executed. + >- **src="res"** indicates that the test resources are in the **resource** directory under the **test** directory. **src="out"** indicates that the test resources are in the **out/release/$(*part*)** directory. ## Test Case Execution -### Configuration File +### Configuration File user_config.xml -Before executing test cases, you need to modify the configuration based on the device used. +Before executing test cases, you need to modify the configuration in **developer_test\config\user_config.xml** based on the device used. -#### Modifying user_config.xml ```xml @@ -849,11 +1103,50 @@ Before executing test cases, you need to modify the configuration based on the d ``` ->**NOTE** -> ->If HDC is connected to the device before the test cases are executed, you only need to configure the device IP address and port number, and retain the default settings for other parameters. +> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> +> If HDC is connected to the device before the test cases are executed, you only need to configure the device IP address and port number, and retain the default settings for other parameters. -### Command Description +### Executing Test Cases on Windows +#### **Test Case Building** + +Test cases cannot be built on Windows. You need to run the following command to build test cases on Linux: +``` +./build.sh --product-name {product_name} --build-target make_test +``` + +> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> +>- **product-name**: specifies the name of the product to be compiled. +>- **build-target**: specifies the test case to build. **make_test** indicates all test cases. You can specify the test cases based on requirements. + +When the build is complete, the test cases are automatically saved in **out/ohos-arm-release/packages/phone/tests**. + +#### Setting Up the Execution Environment +1. On Windows, create the **Test** directory in the test framework and then create the **testcase** directory in the **Test** directory. + +2. Copy **developertest** and **xdevice** from the Linux environment to the **Test** directory on Windows, and copy the test cases to the **testcase** directory. + + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Port the test framework and test cases from the Linux environment to the Windows environment for subsequent execution. + +3. Modify the **user_config.xml** file. + ```xml + + + false + + + + D:\Test\testcase\tests + + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > **\** indicates whether to build test cases. **\** indicates the path for searching for test cases. + +#### Executing Test Cases 1. Start the test framework. ``` @@ -865,96 +1158,198 @@ Before executing test cases, you need to modify the configuration based on the d If you need to manually add a product, add it within the **\** tag to **config/framework_config.xml**. -3. Execute test cases. +3. Execute the test cases. - Run the following command to execute test cases: - ``` - run -t UT -ts CalculatorSubTest -tc interger_sub_00l - ``` - In the command: - ``` - -**t [TESTTYPE]**: specifies the test type, which can be **UT**, **MST**, **ST**, **PERF**, **FUZZ**, or **BENCHMARK**. This parameter is mandatory. - -**tp [TESTPART]**: specifies the part to test. This parameter can be used independently. - -**tm [TESTMODULE]**: specifies the module to test. This parameter must be specified together with **-tp**. - -**ts [TESTSUITE]**: specifies a test suite. This parameter can be used independently. - -**tc [TESTCASE]**: specifies a test case. This parameter must be specified together with **-ts**. - -**h**: displays help information. - ``` + Run the following commands to execute test cases: + ``` + run -t UT + run -t UT -tp PartName + run -t UT -tp PartName -tm TestModuleName + run -t UT -tp ability_base -ts base_object_test + run -t UT -tp PartName -tm TestModuleName -ts CalculatorSubTest + run -t UT -ts base_object_test + run -t UT -ts base_object_test -tc AAFwkBaseObjectTest.BaseObject_test_001 + run -t UT -ts CalculatorSubTest -tc CalculatorSubTest.interger_sub_00l + run -t UT -cov coverage + run -t UT -ra random + run -t UT -ts base_object_test --repeat 5 + run -hl + run -rh 3 + run --retry + ``` -#### Executing Test Cases on Windows + + In the command: + ``` + -**t [TESTTYPE]**: specifies the test type, which can be **UT**, **MST**, **ST**, **PERF**, **FUZZ**, **BENCHMARK**, **ACTS**, **HATS**, and more. This parameter is mandatory. + -**tp [TESTPART]**: specifies the part to test. This parameter can be used independently. + -**tm [TESTMODULE]**: specifies the module to test. This parameter must be specified together with **-tp**. + -**ts [TESTSUITE]**: specifies the test suite. This parameter can be used independently. + -**tc [TESTCASE]**: specifies the test case. This parameter must be specified together with **-ts** to indicate the test suite. + -**cov [COVERAGE]**: specifies the coverage. + -**h**: displays help information. + -**ra [random]**: specifies the out-of-order execution for C++ cases. + --**repeat**: specifies the number of case execution times. + -**hl [HISTORYLIST]**: enables the display of the latest 10 test cases. If there are more than 10 test cases, only the latest 10 test cases are displayed. + -**rh [RUNHISTORY]**: specifies the sequence number of the historical record to execute. + --**retry**: checks the last execution result and re-runs the failed test cases, if any. + ``` -Test cases cannot be built on Windows. You need to run the following command to build test cases on Linux: -``` -./build.sh --product-name {product_name} --build-target make_test -``` + +### Executing Test Cases on Linux ->**NOTE** ->- **product-name**: specifies the name of the product to be compiled. ->- **build-target**: specifies the test case to build. **make_test** indicates all test cases. You can specify the test cases based on requirements. -After the build is complete, the test cases are automatically saved in **out/ohos-arm-release/packages/phone/tests**. +#### Configuring Remote Port Mapping and Modifying Configuration File +To enable test cases to be executed on a remote Linux server or a Linux VM, map the port to enable communication between the device and the remote server or VM. Configure port mapping as follows: +1. On the HDC server, run the following commands: + ``` + hdc_std kill + hdc_std -m -s 0.0.0.0:8710 + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > The IP address and port number are default values. -##### Setting Up the Execution Environment -1. On Windows, create the **Test** directory in the test framework and then create the **testcase** directory in the **Test** directory. +2. On the HDC client, run the following command: + ``` + hdc_std -s xx.xx.xx.xx:8710 list targets + ``` + > ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** + > + > Enter the IP address of the device to test. -2. Copy **developertest** and **xdevice** from the Linux environment to the **Test** directory on Windows, and copy the test cases to the **testcase** directory. +3. Modify the **user_config.xml** file. + ```xml + + + true + + + + + + + + + + ``` - >**NOTE** - > - >Port the test framework and test cases from the Linux environment to the Windows environment for subsequent execution. -3. Modify the **user_config.xml** file. - ```xml - - - false - - - - D:\Test\testcase\tests - - ``` - >**NOTE** - > - >**\** indicates whether to build test cases. **\** indicates the path for searching for test cases. +#### Executing Test Cases +1. Start the test framework. + ``` + ./start.sh + ``` +2. Select the product. -#### Executing Test Cases on Linux + After the test framework starts, you are asked to select a product. Select the development board to test. -If you directly connect to a Linux host, you can directly run commands to execute test cases. + If the displayed product list does not contain the target one, you can add it in the **\** tag in **config/framework_config.xml**. -##### Mapping the Remote Port -To enable test cases to be executed on a remote Linux server or a Linux VM, map the port to enable communication between the device and the remote server or VM. Configure port mapping as follows: -1. On the HDC server, run the following commands: - ``` - hdc_std kill - hdc_std -m -s 0.0.0.0:8710 - ``` - >**NOTE** - > - >The IP address and port number are default values. + ``` + + + + -2. On the HDC client, run the following command: - ``` - hdc_std -s xx.xx.xx.xx:8710 list targets - ``` - >**NOTE** - > - >Enter the IP address of the device to test. + ``` + +3. Execute the test cases. + + 1. TDD commands + + The test framework locates the test cases based on the command, and automatically builds and executes the test cases. + ``` + run -t UT + run -t UT -tp PartName + run -t UT -tp PartName -tm TestModuleName + run -t UT -tp ability_base -ts base_object_test + run -t UT -tp PartName -tm TestModuleName -ts CalculatorSubTest + run -t UT -ts base_object_test + run -t UT -ts base_object_test -tc AAFwkBaseObjectTest.BaseObject_test_001 + run -t UT -ts CalculatorSubTest -tc CalculatorSubTest.interger_sub_00l + run -t -cov coverage + run -t UT -ra random + run -t UT -tp PartName -pd partdeps + run -t UT -ts base_object_test --repeat 5 + run -hl + run -rh 3 + run --retry + ``` + In the command: + ``` + -**t [TESTTYPE]**: specifies the test type, which can be **UT**, **MST**, **ST**, **PERF**, **FUZZ**, and **BENCHMARK**. This parameter is mandatory. + -**tp [TESTPART]**: specifies the part to test. This parameter can be used independently. + -**tm [TESTMODULE]**: specifies the module to test. This parameter must be specified together with **-tp**. + -**ts [TESTSUITE]**: specifies the test suite. This parameter can be used independently. + -**tc [TESTCASE]**: specifies the test case. This parameter must be specified together with **-ts** to indicate the test suite. + -**cov [COVERAGE]**: specifies the coverage. + -**h**: displays help information. + -**ra [random]**: specifies the out-of-order execution for C++ cases. + -**pd [partdeps]**: specifies execution parameter of the level-2 part dependencies. + --**repeat**: specifies the number of case execution times. + -**hl [HISTORYLIST]**: enables the display of the latest 10 test cases. If there are more than 10 test cases, only the latest 10 test cases are displayed. + -**rh [RUNHISTORY]**: specifies the sequence number of the historical record to execute. + --**retry**: checks the last execution result and re-runs the failed test cases, if any. + ``` + + In Linux, you can run the following commands to view the supported product forms, test types, subsystems, and parts. + ``` + To view the help information, run **help**. + To view the **show** command, run **help show**. + To view the supported product forms, run **show productlist**. + To view the supported test types, run **show typelist**. + To view the supported test subsystems, run **show subsystemlist** . + To view the supported test parts, run **show partlist**. + ``` + 2. ACTS/HATS commands + + After selecting the product, you can refer to the following to execute the ACTS or HATS test cases. + ``` + run -t ACTS + run -t HATS + run -t ACTS -ss arkui + run -t ACTS -ss arkui, modulemanager + run -t ACTS -ss arkui -ts ActsAceEtsTest + run -t HATS -ss telephony -ts HatsHdfV1RilServiceTest + run -t ACTS -ss arkui -tp ActsPartName + run -t ACTS -ss arkui -ts ActsAceEtsTest,ActsAceEtsResultTest + run -t HATS -ss powermgr -ts HatsPowermgrBatteryTest,HatsPowermgrThermalTest + run -t ACTS -ss arkui -ts ActsAceEtsTest -ta class:alphabetIndexerTest#alphabetIndexerTest001 + run -t ACTS -ss arkui -ts ActsAceEtsTest -ta class:alphabetIndexerTest#alphabetIndexerTest001 --repeat 2 + run -hl + run -rh 1 + run --retry + ``` + The parameters in the ACTS and HATS commands are the same, but are different from those in TDD commands. + ``` + -**t [TESTTYPE]**: specifies the test case type, which can be **ACTS** or **HATS**. This parameter is mandatory. + -**ss [SUBSYSTEM]**: specifies the subsystem to test. This parameter can be used independently. To specify multiple subsystems, separate them with commas (,). + -**tp [TESTPART]**: specifies the part to test. This parameter can be used independently. + -**ts [TESTSUITE]**: specifies the test suite. This parameter can be used independently. To specify multiple test suites, separate them with commas (,). + -**ta [TESTARGS]**: specifies the test method. This parameter must be used together with **-ts**. + --**repeat**: specifies the number of case execution times. + -**hl [HISTORYLIST]**: enables the display of the latest 10 test cases. If there are more than 10 test cases, only the latest 10 test cases are displayed. + -**rh [RUNHISTORY]**: specifies the sequence number of the historical record to execute. + --**retry**: checks the last execution result and re-runs the failed test cases, if any. + ``` ## Viewing the Test Result -### Test Report Logs -After the test cases are executed, the test result will be automatically generated. You can view the detailed test result in the related directory. +After the test is executed, the console automatically generates the test result. -### Test Result You can obtain the test result in the following directory: ``` test/developertest/reports/xxxx_xx_xx_xx_xx_xx ``` ->**NOTE** -> ->The folder for test reports is automatically generated. +> ![icon-note.gif](/en/device-dev/driver/public_sys-resources/icon-note.gif) **NOTE** +> +> The test report folder is automatically generated. The folder contains the following files: | Type | Description | @@ -964,12 +1359,54 @@ The folder contains the following files: | summary_report.html | Test report summary. | | details_report.html | Detailed test report. | -### Test Framework Logs -``` -reports/platform_log_xxxx_xx_xx_xx_xx_xx.log -``` -### Latest Test Report -``` -reports/latest -``` + +## Executing Coverage Cases +When GCDA data is available, you can execute the test cases as follows for subsystems to generate a coverage report: + +1. (Optional) To block redundant branch data generated by non-core code, run the following command in the **/test/testfwk/developer_test/localCoverage/restore_comment** directory before source code compilation: + + python3 build_before_generate.py + + Run the following command to select the parts to be blocked during compilation: + + run -tp partname + run -tp partname1 partname2 +2. Before compiling the version, modify the compilation options. Add **-- coverage** to the **cflags**, **cflags_cc**, and **ldflags** options in the **build.gn** file of the involved subsystem. + + ldflags = [ "--coverage" ] + C: cflags = [ "--coverage" ] + C++: cflags_cc = [ "--coverage" ] + + **Recommended**: You can also refer to the mode for the window subsystem. For details, see the files in this [pull request](https://gitee.com/openharmony/window_window_manager/pulls/1274/files). +3. To execute coverage test cases, perform the following to install the dependencies: + + 1. Run the **sudo apt install lcov** command to install lcov. + 2. Run the **apt install dos2unix** command to install dos2unix. + 3. Run the **pip install lxml** command to install lxml. + 4. Run the **pip install selectolax** command to install selectolax. + 5. Run the **pip install CppHeaderParser** command to install CppHeaderParser. + +4. To map a remote device, set its IP address in the **usr_config.xml** file. For details about device mapping, see [Configuring Remote Port Mapping and Modifying Configuration File](#configuring-remote-port-mapping-and-modifying-configuration-file). + + + + + + + + +5. Run the **./start.sh** command. Below are examples: + + run -t UT -tp *Part name* -cov coverage + run -t UT -ss *Subsystem name* -cov coverage + run -t UT -ss *Subsystem name* -tp **Part name** -cov coverage + run -t UT MST ST -tp *Part name* -cov coverage + + Note: The **-cov coverage** parameter must be added to the preceding commands. + +6. Obtain the coverage report from the following paths: + + Code coverage report: **/test/testfwk/developer_test/localCoverage/codeCoverage/results/coverage/reports/cxx/html** + + API coverage report: **/test/testfwk/developer_test/localCoverage/interfaceCoverage/results/coverage/interface_kits/html** diff --git a/en/device-dev/device-test/smartperf-host.md b/en/device-dev/device-test/smartperf-host.md index ec92a1ba4c2c5ca57957702de1e9fe9c8cb54c9c..6f8451539b9e7bde43dbe79029138508f520d809 100644 --- a/en/device-dev/device-test/smartperf-host.md +++ b/en/device-dev/device-test/smartperf-host.md @@ -1,4 +1,4 @@ -# Smartperf-Host +# Smartperf-Host User Guide ## Overview Smartperf-Host is an intuitive performance and power optimization tool that offers in-depth data mining and fine-grained data visualization. In this tool, you can gain visibility into a multitude of metrics in terms of CPU scheduling, frequency, process and thread time slices, heap memory, frame rate, and more, in swimlanes. Better yet, you can analyze the collected data intuitively on the GUI. ## Architecture diff --git a/en/device-dev/driver/driver-peripherals-audio-des.md b/en/device-dev/driver/driver-peripherals-audio-des.md index 150f968593e7e5bc2a3c713e66c5e71a967077a0..c9aea7010c127594d9151a48c1ed69b9b312da08 100644 --- a/en/device-dev/driver/driver-peripherals-audio-des.md +++ b/en/device-dev/driver/driver-peripherals-audio-des.md @@ -192,8 +192,8 @@ struct AudioDaiOps g_codecDaiDeviceOps = { }; struct DaiData g_codecDaiData = { - .DaiInit = CodecDaiDeviceInit, // Initialize the codec DAI device (need to be implemented for a new platform). - .ops = &g_codecDaiDeviceOps, // Codec DAI device operation function set. + .DaiInit = CodecDaiDeviceInit,// Initialize the codec DAI device (need to be implemented for a new platform). + .ops = &g_codecDaiDeviceOps, // Codec DAI device operation function set. }; ``` @@ -378,13 +378,13 @@ The code snippet is as follows: audio :: host { device_codec :: device { device0 :: deviceNode { - policy = 1; // The codec module provides services only for the kernel. - priority = 50; // The codec module must be loaded before the load of the HDF_AUDIO module. + policy = 1; // The codec module provides services only for the kernel. + priority = 50; // The codec module must be loaded before the load of the HDF_AUDIO module. preload = 0; permission = 0666; - moduleName = "CODEC_HI3516"; // The value must be the same as moduleName in HdfDriverEntry. - serviceName = "codec_service_0"; // Name of the service provided externally. - deviceMatchAttr = "hdf_codec_driver"; // Name of the private attribute, which is used to match the corresponding private data (including the register configuration). + moduleName = "CODEC_HI3516"; // The value must be the same as moduleName in HdfDriverEntry. + serviceName = "codec_service_0"; // Name of the service provided externally. + deviceMatchAttr = "hdf_codec_driver"; // Name of the private attribute, which is used to match the corresponding private data (including the register configuration). } } ``` @@ -403,12 +403,12 @@ root { // Set the private data attribute name, which must be the same as the deviceMatchAttr in device_info.hcs. match_attr = "hdf_audio_driver_1"; serviceName = "hdf_audio_codec_primary_dev11"; // Name of the service provided externally. - codecName = "codec_service_1"; // Codec service name. - platformName = "dma_service_0"; // DMA service. - cpuDaiName = "dai_service"; // CPU DAI service. - codecDaiName = "tfa9879_codec_dai"; // Codec DAI service. - dspName = "dsp_service_0"; // DSP service name. - dspDaiName = "dsp_dai"; // DSP DAI. + codecName = "codec_service_1"; // Codec service name. + platformName = "dma_service_0"; // DMA service. + cpuDaiName = "dai_service"; // CPU DAI service. + codecDaiName = "tfa9879_codec_dai"; // Codec DAI service. + dspName = "dsp_service_0"; // DSP service name. + dspDaiName = "dsp_dai"; // DSP DAI. } } } diff --git a/en/device-dev/driver/driver-peripherals-touch-des.md b/en/device-dev/driver/driver-peripherals-touch-des.md index 0f7d0f7cf40b9ff5694dca61d28117ca5a4b886d..ffbd0ad728e2838926d73abc37d535459233eeb7 100644 --- a/en/device-dev/driver/driver-peripherals-touch-des.md +++ b/en/device-dev/driver/driver-peripherals-touch-des.md @@ -3,11 +3,11 @@ ## Overview -### Function Introduction +### Functions The touchscreen driver powers on its integrated circuit (IC), initializes hardware pins, registers interrupts, configures the communication (I2C or SPI) interface, sets input configurations, and downloads and updates firmware. -The touchscreen driver is developed based on the OpenHarmony input driver model, which applies basic APIs of the operating system abstraction layer (OSAL) and platform interface layer on the OpenHarmony Hardware Driver Foundation [(HDF)](../driver/driver-hdf-development.md). Common APIs include the bus communication APIs and OS native APIs (such as memory, lock, thread, and timer APIs). The OSAL and platform APIs shield the differences of underlying hardware. This allows the use of the touchscreen driver across platforms and OSs. In this regard, you can develop the touchscreen driver only once and deploy it on multiple devices. +The touchscreen driver is developed based on the OpenHarmony input driver model, which applies basic APIs of the operating system abstraction layer (OSAL) and platform interface layer on the OpenHarmony Hardware Driver Foundation [(HDF)](driver-overview-foundation.md). Common APIs include the bus communication APIs and OS native APIs (such as memory, lock, thread, and timer APIs). The OSAL and platform APIs shield the differences of underlying hardware. This allows the use of the touchscreen driver across platforms and OSs. In this regard, you can develop the touchscreen driver only once and deploy it on multiple devices. ### Working Principles @@ -123,7 +123,7 @@ The load process of the input driver model (for the touchscreen driver) is as fo The development process of the touchscreen driver is as follows: -1. Configure device information.
The input driver is developed based on the HDF. The HDF loads and starts the driver in a unified manner. You need to configure the driver information, such as whether to load the driver and the loading priority, in the configuration file. Then, the HDF starts the registered driver modules one by one. For details about how to configure the driver, see [Driver Development](../driver/driver-hdf-development.md#how-to-develop). +1. Configure device information.
The input driver is developed based on the HDF. The HDF loads and starts the driver in a unified manner. You need to configure the driver information, such as whether to load the driver and the loading priority, in the configuration file. Then, the HDF starts the registered driver modules one by one. For details about the driver configuration, see [HDF Driver Development Process](driver-hdf-manage.md). 2. Configure board-specific information and touchscreen private information.
Configure the I/O pin functions. For example, set registers for the I2C pins on the board for the touchscreen to enable I2C communication. @@ -136,7 +136,7 @@ The following example describes how to develop the touchscreen driver for an RK3 1. Configure device information. - Configure the modules of the input driver model in **vendor/hihope/rk3568/hdf_config/khdf/device_info/device_info.hcs**. For details, see [Driver Development](../driver/driver-hdf-development.md). Then, the HDF loads the modules of the input model in sequence based on the configuration information. + Configure the modules of the input driver model in **vendor/hihope/rk3568/hdf_config/khdf/device_info/device_info.hcs**. For details, see [HDF Driver Development Process](driver-hdf-manage.md). The HDF loads modules of the input model in sequence based on the configuration information. ```c input :: host { @@ -280,7 +280,7 @@ The following example describes how to develop the touchscreen driver for an RK3 { int32_t resX = device->driver->boardCfg->attr.resolutionX; int32_t resY = device->driver->boardCfg->attr.resolutionY; - + for (int32_t i = 0; i < pointNum; i++) { frame->fingers[i].y = (buf[GT_POINT_SIZE * i + GT_X_LOW] & ONE_BYTE_MASK) | ((buf[GT_POINT_SIZE * i + GT_X_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET); @@ -334,7 +334,7 @@ The following example describes how to develop the touchscreen driver for an RK3 } return HDF_SUCCESS; } - + static struct TouchChipOps g_sampleChipOps = { .Init = ChipInit, .Detect = ChipDetect, @@ -342,7 +342,7 @@ The following example describes how to develop the touchscreen driver for an RK3 .Suspend = ChipSuspend, .DataHandle = ChipDataHandle, }; - + static TouchChipCfg *ChipConfigInstance(struct HdfDeviceObject *device) { TouchChipCfg *chipCfg = (TouchChipCfg *)OsalMemAlloc(sizeof(TouchChipCfg)); @@ -359,7 +359,7 @@ The following example describes how to develop the touchscreen driver for an RK3 } return chipCfg; } - + static ChipDevice *ChipDeviceInstance(void) { ChipDevice *chipDev = (ChipDevice *)OsalMemAlloc(sizeof(ChipDevice)); @@ -370,7 +370,7 @@ The following example describes how to develop the touchscreen driver for an RK3 (void)memset_s(chipDev, sizeof(ChipDevice), 0, sizeof(ChipDevice)); return chipDev; } - + static void FreeChipConfig(TouchChipCfg *config) { if (config->pwrSeq.pwrOn.buf != NULL) { @@ -381,7 +381,7 @@ The following example describes how to develop the touchscreen driver for an RK3 } OsalMemFree(config); } - + static int32_t HdfSampleChipInit(struct HdfDeviceObject *device) { TouchChipCfg *chipCfg = NULL; @@ -404,27 +404,27 @@ The following example describes how to develop the touchscreen driver for an RK3 chipDev->ops = &g_sampleChipOps; chipDev->chipName = chipCfg->chipName; chipDev->vendorName = chipCfg->vendorName; - + /* Register the touchscreen device with the platform driver. */ if (RegisterChipDevice(chipDev) != HDF_SUCCESS) { goto freeDev; } HDF_LOGI("%s: exit succ, chipName = %s", __func__, chipCfg->chipName); return HDF_SUCCESS; - + freeDev: OsalMemFree(chipDev); freeCfg: FreeChipConfig(chipCfg); return HDF_FAILURE; } - + struct HdfDriverEntry g_touchSampleChipEntry = { .moduleVersion = 1, .moduleName = "HDF_TOUCH_SAMPLE", .Init = HdfSampleChipInit, }; - + HDF_INIT(g_touchSampleChipEntry); ``` @@ -506,4 +506,3 @@ The following example describes how to develop the touchscreen driver for an RK3 return 0; } ``` - \ No newline at end of file diff --git a/en/device-dev/kernel/Readme-EN.md b/en/device-dev/kernel/Readme-EN.md index 3e041a3f024fee6bdd88fe84f012d39e07ec8d27..d78692102287b1458f57c68fb78c380f21ae0fb3 100644 --- a/en/device-dev/kernel/Readme-EN.md +++ b/en/device-dev/kernel/Readme-EN.md @@ -1,6 +1,5 @@ # Kernel -- Kernel - [Kernel Overview](kernel-overview.md) - Mini-System Kernel (LiteOS-M) - [LiteOS-M Overview](kernel-mini-overview.md) diff --git a/en/device-dev/kernel/kernel-mini-memory-exception.md b/en/device-dev/kernel/kernel-mini-memory-exception.md index 599623cbb364b7fc93cd1b6a9cd6d11cc338053d..8d1b4b271d20779f08bfdc9d9c1a51a927ba7e61 100644 --- a/en/device-dev/kernel/kernel-mini-memory-exception.md +++ b/en/device-dev/kernel/kernel-mini-memory-exception.md @@ -25,11 +25,12 @@ In the figure, the registers in different colors indicate different functions. T The following table describes APIs available for the OpenHarmony LiteOS-M stack trace module. For more details about the APIs, see the API reference. - **Table 1** APIs of the stack trace module +**Table 1** APIs of the stack trace module -| Category| API| +| API| Description| | -------- | -------- | -| Stack tracing| **LOS_BackTrace**: prints the call stack relationship at the calling point.
**LOS_RecordLR**: obtains the call stack relationship at the calling point when print is unavailable.| +| LOS_BackTrace | Prints the call stack relationship at the calling point.| +| LOS_RecordLR | Obtains the call stack relationship at the calling point when print is unavailable.| ## Development Guidelines @@ -39,17 +40,18 @@ The following table describes APIs available for the OpenHarmony LiteOS-M stack The typical process for enabling exception debugging is as follows: -1. Configure the macros related to exception handling - in the **target_config.h** file. - | Configuration Item| Description| Value| +1. Configure the macros related to exception handling in the **target_config.h** file. + + | Configuration Item| Description| Value| | -------- | -------- | -------- | | LOSCFG_BACKTRACE_DEPTH | Depth of the function call stack. The default value is **15**.| 15 | | LOSCFG_BACKTRACE_TYPE | Type of the stack tracing.
**0**: The stack tracing is disabled.
**1**: supports call stack analysis of the Cortex-M series hardware.
**2**: supports call stack analysis of the RISC-V series hardware.| Set this parameter to **1** or **2** based on the toolchain type.| - -1. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions. - The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows: - - The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleExcEntry** function is called in **TestTaskEntry**. + +2. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions. + + The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows: + + The sample code is built and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleExcEntry** in **TestTaskEntry**. ``` #include @@ -210,10 +212,10 @@ The typical process for enabling exception debugging is as follows: The procedure for locating the exception is as follows: -1. Ensure that the compiler optimization is disabled. Otherwise, the following problems may be optimized during the compilation process. +1. Check that the compiler optimization is disabled. Otherwise, the following problems may be optimized during the compilation process. 2. Open the image disassembly file (.asm) generated. If the file is not generated, use the objdump tool to generate it. The command is as follows: - + ``` arm-none-eabi-objdump -S -l XXX.elf ``` @@ -221,7 +223,7 @@ The procedure for locating the exception is as follows: 3. Search for the PC (pointing to the instruction being executed) in the .asm file to locate the abnormal function. The PC address directs to the instruction being executed when the exception occurs. In the .asm file corresponding to the currently executed binary file, search for the PC value **0x2101c61a** and locate the instruction being executed by the CPU. Disassemble the code as follows: - + ``` 2101c60c : 2101c60c: b580 push {r7, lr} @@ -242,13 +244,13 @@ The procedure for locating the exception is as follows: 2101c62e: bd80 pop {r7, pc} 2101c630: 21025f90 .word 0x21025f90 ``` - + As indicated by the information displayed: - - - The CPU is executing **ldr r3, [r3, #0]** when an exception occurs. The value of **r3** is **0xffffffff**, which causes an invalid address. + - When the exception occurs, the CPU is executing the **ldr r3, [r3, #0]** instruction. The value of **r3** is **0xffffffff**, which causes an invalid address. - The exception occurs in the **GetResultException0** function. - -4. Search for the parent function of the abnormal function based on the LR value. + +5. Search for the parent function of the abnormal function based on the LR value. + The code disassembly of the LR value **0x2101c64d** is as follows: ``` @@ -271,7 +273,7 @@ The procedure for locating the exception is as follows: 2101c656: bf00 nop 2101c658: 21025fb0 .word 0x21025fb0 ``` - - The previous line of LR **2101c648** is **bl2101c60c **, which calls the abnormal function. The parent function is **GetResultException1**. - -5. Parse the LR value between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship where the exception occurs and find the cause of the exception. \ No newline at end of file + + The previous line of LR **2101c648** is **bl 2101c60c \**, which calls the abnormal function. The parent function is **GetResultException1**. + +7. Repeat step 3 to parse the LR value between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship where the exception occurs and find the cause of the exception. diff --git a/en/device-dev/kernel/kernel-overview.md b/en/device-dev/kernel/kernel-overview.md index 873d8b0a6c09eabbaaee70005e8eda10793045dd..a1a303edf777899df32fb6d6eac402ec8c5c042a 100644 --- a/en/device-dev/kernel/kernel-overview.md +++ b/en/device-dev/kernel/kernel-overview.md @@ -10,9 +10,9 @@ The interface through which you interact with an operating system (OS) is the ou An OS is a system software located between applications and hardware. It provides program interfaces and running environments for upper-layer applications and manages underlying hardware resources. Located at a lower layer of the OS, the kernel provides concurrent management of hardware resources for the upper-layer program framework. - **Figure 1** OS architecture +**Figure 1** OS architecture - ![](figures/OS_architecture.png) +![](figures/OS_architecture.png) ### Multi-Kernel Architecture @@ -31,10 +31,10 @@ OpenHarmony supports Linux and LiteOS. You can select OpenHarmony based on produ The kernel subsystem is located at the lower layer of OpenHarmony. Since OpenHarmony is oriented to devices with different CPUs and storage space, the kernel subsystem supports use of the optimal OS kernel for devices of different resource levels. The KAL shields differences between kernels and provides basic kernel capabilities for the upper layer. - **Figure 2** OpenHarmony architecture +**Figure 2** OpenHarmony architecture - ![](figures/openharmony_architecture.png) +![](figures/openharmony_architecture.png) ### OpenHarmony Types @@ -43,19 +43,17 @@ OpenHarmony can be classified into the following types based on the supported de - Mini system -The mini system fits into the devices that come with MCU processors, such as Arm Cortex-M and 32-bit RISC-V, and memory greater than or equal to 128 KiB. This system provides a variety of lightweight network protocols, a lightweight graphics framework, and a wide range of read/write components with the Internet of Things (IoT) bus. The mini system applies to smart home products such as LinkIoT module devices and sensors. - + The mini system fits into the devices that come with MCU processors, such as Arm Cortex-M and 32-bit RISC-V, and memory greater than or equal to 128 KiB. This system provides a variety of lightweight network protocols, a lightweight graphics framework, and a wide range of read/write components with the Internet of Things (IoT) bus. The mini system applies to smart home products such as LinkIoT module devices and sensors. - Small system -The small system fits into the devices that come with application processors, such as Arm Cortex-A, and memory greater than or equal to 1 MiB. This system provides higher security capabilities, a standard graphics framework, and video encoding and decoding capabilities. The small system applies to smart home products such as IP cameras, peephole cameras, and routers as well as smart travel products such as event data recorders (EDRs). - + The small system fits into the devices that come with application processors, such as Arm Cortex-A, and memory greater than or equal to 1 MiB. This system provides higher security capabilities, a standard graphics framework, and video encoding and decoding capabilities. The small system applies to smart home products such as IP cameras, peephole cameras, and routers as well as smart travel products such as event data recorders (EDRs). - Standard system The standard system fits into the devices that come with application processors, such as Arm Cortex-A, and memory greater than or equal to 128 MiB. This system provides a complete application framework supporting enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. The standard system applies to high-end refrigerator displays. Different OpenHarmony systems use kernels of different forms. LiteOS applies to mini and small systems. Linux applies to small and standard systems. The table below lists the kernels and applicable systems. - **Table 1** Kernels and applicable systems +**Table 1** Kernels and applicable systems | Level| Mini System| Small System| Standard System| | -------- | -------- | -------- | -------- | @@ -69,11 +67,13 @@ Different OpenHarmony systems use kernels of different forms. LiteOS applies to ### Kernel Architecture -OpenHarmony LiteOS-M is a lightweight OS kernel designed for the IoT field. It features small footprint, low power consumption, and high performance. It has a simple code structure, including the minimum kernel function set, kernel abstraction layer, optional components, and project directory. The LiteOS-M kernel is divided into the hardware layer and hardware-irrelevant layers. The hardware layer provides a unified HAL interface for easier hardware adaptation. A range of compilation toolchains can be used with different chip architectures to meet the expansion of diversified hardware and compilation toolchains in the Artificial Intelligence of Things (AIoT) field. +OpenHarmony LiteOS-M is a lightweight OS kernel designed for the IoT field. It features small footprint, low power consumption, and high performance. It has a simple code structure, including the minimum kernel function set, kernel abstraction layer, optional components, and project directory. + +The LiteOS-M kernel is divided into the hardware layer and hardware-irrelevant layers. The hardware layer provides a unified HAL interface for easier hardware adaptation. A range of compilation toolchains can be used with different chip architectures to meet the expansion of diversified hardware and compilation toolchains in the Artificial Intelligence of Things (AIoT) field. - **Figure 3** LiteOS-M architecture +**Figure 3** LiteOS-M architecture - ![](figures/Liteos-m-architecture.png "kernel-architecture") +![](figures/Liteos-m-architecture.png "kernel-architecture") ### How to Use @@ -86,7 +86,7 @@ For details about how to use LiteOS-M, see "Usage" in LiteOS-M [Kernel Overview] ### Kernel Architecture -The LiteOS-A kernel mainly applies to small-sized systems. It is oriented to devices with M-level memory and supports memory management unit (MMU) isolation. Similar kernels in the industry include Zircon and Darwin. +The LiteOS-A kernel applies to the small system. It fits into devices with memory greater than or equal to 1 MiB and supporting memory management unit (MMU) isolation. Similar kernels in the industry include Zircon and Darwin. To keep pace with the rapid development of the IoT industry, the OpenHarmony lightweight kernel is continuously optimized and expanded to provide application developers with friendly development experience and unified and open ecosystem capabilities. LiteOS-A has the following new features: @@ -134,7 +134,7 @@ During the build process, you can merge the driver code based on the chip platfo OpenHarmony provides the enhanced swap (ESwap), related thread group (RTG), and lightweight CPU isolation features for the Linux kernel. -ESwap +**ESwap** Enhanced Swap (ESwap) allows a custom partition to serve as a swap partition and uses a resident process zswapd to encrypt and swap the anonymous pages compressed by [zram](https://gitee.com/link?target=https%3A%2F%2Fwww.kernel.org%2Fdoc%2Fhtml%2Flatest%2Fadmin-guide%2Fblockdev%2Fzram.html) to the ESwap partition. In this way, a block of memory can be completely released to ensure the available memory (Memavailable) waterline. In addition to this reclaiming mechanism, the entire memory framework is enhanced to improve the reclaiming efficiency of anonymous pages and file pages and streamline the reclaiming ratio of these two types of pages to prevent refaults caused by excessive reclamation. @@ -150,16 +150,18 @@ Lightweight CPU isolation enables dynamic CPU isolation based on the system load ### How to Use 1. Apply HDF patches. + Apply the HDF kernel patches matching your kernel version. For details, see the method in **kernel.mk** in the **kernel/linux/build** repository. - + ``` $(OHOS_BUILD_HOME)/drivers/hdf_core/adapter/khdf/linux/patch_hdf.sh $(OHOS_BUILD_HOME) $(KERNEL_SRC_TMP_PATH) $(KERNEL_PATCH_PATH) $(DEVICE_NAME) ``` 2. Apply the chip driver patches. + The following uses Hi3516D V300 as an example. - Place the patches for the chip component in the corresponding path based on the path and naming rules for the patches of the chip component in **kernel.mk** in the **kernel/linux/build** repository. + Place the patches for the chip component in the corresponding directory based on the path and naming rules for the patches of the chip component in **kernel.mk** in the **kernel/linux/build** repository. ``` DEVICE_PATCH_DIR := $(OHOS_BUILD_HOME)/kernel/linux/patches/${KERNEL_VERSION}/$(DEVICE_NAME)_patch @@ -167,13 +169,16 @@ Lightweight CPU isolation enables dynamic CPU isolation based on the system load ``` 3. Modify the **config** file to build. - Place the **config** file for the chip component in the corresponding path based on the path and naming rules of the chip component in **kernel.mk** in the **kernel/linux/build** repository. - + + Place the **config** file for the chip component in the corresponding directory based on the path and naming rules of the chip component in **kernel.mk** in the **kernel/linux/build** repository. + ``` KERNEL_CONFIG_PATH := $(OHOS_BUILD_HOME)/kernel/linux/config/${KERNEL_VERSION}DEFCONFIG_FILE := $(DEVICE_NAME)_$(BUILD_TYPE)_defconfig ``` + + - > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
+ > **NOTICE**
> In the OpenHarmony project build process, patches are installed after "kernel/linux/linux-\*.\*" is copied. Before using the version-level build command of OpenHarmony, ensure that the "kernel/linux/linux-\*.\*" source code is available. > > After the build is complete, the kernel is generated in the kernel directory in the **out** directory. Modify the **config** file based on the kernel generated, and copy the generated **.config** file to the corresponding path in the **config** repository. Then, the configuration takes effect. diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index fda961faa27a1c9f8e34b96a7e26cbbe927c60d2..996d167977dbd065df2c730b565bcfa7790cb3ba 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -24,9 +24,12 @@ - [Using Cargo2gn](subsys-build-cargo2gn-guide.md) - [FAQs](subsys-build-FAQ.md) - [ArkCompiler Development](subsys-arkcompiler-guide.md) -- [Distributed Remote Startup](subsys-remote-start.md) - Graphics - [Graphics Overview](subsys-graphics-overview.md) +- ArkUI + - [Custom Window Title Bar Development](subsys-arkui-customize_titlebar.md) +- Small-System Graphics + - [Overview of Small-System Graphics](subsys-graphics-overview.md) - [Common Component Development](subsys-graphics-common-guide.md) - [Container Component Development](subsys-graphics-container-guide.md) - [Development of Layout Container Components](subsys-graphics-layout-guide.md) diff --git a/en/device-dev/subsystems/figures/HUKS-architecture.png b/en/device-dev/subsystems/figures/HUKS-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..3cb0916925b1737af0c69cb082ec91ad20fb66c1 Binary files /dev/null and b/en/device-dev/subsystems/figures/HUKS-architecture.png differ diff --git a/en/device-dev/subsystems/subsys-arkui-customize_titlebar.md b/en/device-dev/subsystems/subsys-arkui-customize_titlebar.md new file mode 100644 index 0000000000000000000000000000000000000000..42e962744c4354cffc27ce0b2556a285c5a305d1 --- /dev/null +++ b/en/device-dev/subsystems/subsys-arkui-customize_titlebar.md @@ -0,0 +1,145 @@ +# Custom Window Title Bar Development +## Overview +While OpenHarmony provides default UX styles for window title bars, it allows device vendors to develop custom window title bars to meet specific needs. +## Development Guidelines + +### How to Develop +Perform the following steps: +1. In **MaximizeMode** (in **frameworks/core/components/common/layout/constants.h**), define the enums, for example, **MODE_AVOID_SYSTEM_BAR** and **MODE_FULL_FILL**. + ```cpp + enum class MaximizeMode : uint32_t { + MODE_AVOID_SYSTEM_BAR, + MODE_FULL_FILL, + MODE_RECOVER, + }; + ``` +2. In **ContainerModalViewFactory::GetView** (in **foundation/arkui/ace_engine/frameworks/core/components_ng/pattern/container_modal/container_modal_view_factory.h**), add the creation of the custom window title bar based on the current value of **MaximizeMode**. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > The **ContainerModalViewFactory::GetView** method is a factory method. Below shows the method expanded: + + ```cpp + class ACE_EXPORT ContainerModalViewFactory { + public: + static RefPtr GetView(RefPtr& content, MaximizeMode mode) { + if (mode == MaximizeMode::MODE_AVOID_SYSTEM_BAR || + mode == MaximizeMode::MODE_FULL_FILL) { + return ContainerModalViewEnhance::Create(content); + } else { + return ContainerModalView::Create(content); + } + } + }; + ``` +In the preceding example, vendor enhance creates a custom title bar branch based on the value of **MaximizeMode** (**MaximizeMode::MODE_AVOID_SYSTEM_BAR** or **MaximizeMode::MODE_FULL_FILL**). + +3. Create a folder in the **foundation/arkui/ace_engine/frameworks/core/components_ng/pattern/container_modal** directory to store your custom title bar code. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > The structure of the **container_modal** folder is as follows: + ```shell + ├── container_modal_accessibility_property.cpp + ├── container_modal_accessibility_property.h + ├── container_modal_pattern.cpp + ├── container_modal_pattern.h + ├── container_modal_view.cpp + ├── container_modal_view_factory.h + ├── container_modal_view.h + └── enhance + ├── container_modal_pattern_enhance.cpp + ├── container_modal_pattern_enhance.h + ├── container_modal_view_enhance.cpp + └── container_modal_view_enhance.h + ``` + The **container_modal_\*** files in the **container_modal** folder contain the code related to the default title bar view. You can add your custom code files in the created folder, **enhance** in this example. + +4. Complete build configuration for the new .cpp files in **foundation/arkui/ace_engine/frameworks/core/components_ng/pattern/BUILD.gn**. + +When your development of the custom title bar is complete, debug and verify the title bar. +### Debugging and Verification +Before the verification, prepare the following files (which must be stored in the same path): +- **open_maximize.bat** + + Below shows the content of this file: + + ```shell + hdc shell mount -o rw,remount /sys_prod + hdc file send window_manager_config_open.xml sys_prod/etc/window/resources/window_manager_config.xml + hdc shell reboot + ``` + +- **window_manager_config_open.xml** + + Below shows the content of this file: + + ```html + + + + 50 50 50 + 1706 + 1000 + 398 + 528 + 0 + 82 121 1068 706 + 102 + 0 + 5 + 10 + 2880 + 0.5 0.33 0.67 + + + 500 + 150 + 0.2 0.0 0.2 1.0 + + + + + 200 + 0.0 0.0 0.2 1.0 + + 0.9 0.9 + 0 0 1 0 + 0 0 + 0 + + + + + off + off + defaultCornerRadiusL + + + + 0 + #000000 + 0 + 15 + 0.4 + 34 + + + 0 + #000000 + 0 + 15 + 0.2 + 17 + + + + + + ``` + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > The **window_manager_config_open.xml** file contains various configuration items. Before the verification, you must change the default value of **MaximizeMode** to the one you have defined, that is, the value obtained by **MaximizeMode maximizeMode = GetWindowManager()->GetWindowMaximizeMode()**. The system loads the corresponding title bar according to the value. + +Then, debug the custom title bar as follows: +1. Burn the image that contains the custom title bar code to the device. +2. Run the **open_maximize.bat** script. +3. Run the demo to check whether the title bar works properly. diff --git a/en/device-dev/subsystems/subsys-build-FAQ.md b/en/device-dev/subsystems/subsys-build-FAQ.md index 3922581ea092b7225683c1bfdc8016de249526cb..f6df39da206a6243b65d5bac7266ed374f3b232e 100644 --- a/en/device-dev/subsystems/subsys-build-FAQ.md +++ b/en/device-dev/subsystems/subsys-build-FAQ.md @@ -4,29 +4,19 @@ ### "usr/sbin/ninja: invalid option -- w" -- **Symptom** +- **Symptom**
The build fails, and "usr/sbin/ninja: invalid option -- w" is displayed. - The build fails, and **usr/sbin/ninja: invalid option -- w** is displayed. +- **Possible Causes**
The Ninja version in use does not support the **--w** option. -- **Possible Causes** - - The Ninja version in use does not support the **--w** option. - -- **Solution** - - Uninstall Ninja and GN, and [install Ninja and GN of the required version](../../device-dev/get-code/gettools-ide.md). +- **Solution**
Uninstall Ninja and GN, and [install Ninja and GN of the required version](../../device-dev/get-code/gettools-ide.md). ### "/usr/bin/ld: cannot find -lncurses" -- **Symptom** +- **Symptom**
The build fails, and "/usr/bin/ld: cannot find -lncurses" is displayed. - The build fails, and **/usr/bin/ld: cannot find -lncurses** is displayed. +- **Possible Causes**
The ncurses library is not available. -- **Possible Causes** - - The ncurses library is not installed. - -- **Solution** +- **Solution**
```shell sudo apt-get install lib32ncurses5-dev @@ -34,15 +24,11 @@ ### "line 77: mcopy: command not found" -- **Symptom** - - The build fails, and **line 77: mcopy: command not found** is displayed. +- **Symptom**
The build fails, and "line 77: mcopy: command not found" is displayed. -- **Possible Causes** +- **Possible Causes**
mcopy is not available. - mcopy is not installed. - -- **Solution** +- **Solution**
```shell sudo apt-get install dosfstools mtools @@ -50,39 +36,25 @@ ### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" -- **Symptom** - - The build fails, and the following information is displayed:
**riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory** - -- **Possible Causes** +- **Symptom**
The build fails, and "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" is displayed. - You do not have the permission to access files in the RISC-V compiler directory. +- **Possible Causes**
You do not have the permission to access files in the RISC-V compiler directory. -- **Solution** +- **Solution**
1. Run the following command to locate **gcc_riscv32**. - 1. Run the following command to locate **gcc_riscv32**: - - ```shell - which riscv32-unknown-elf-gcc - ``` + ```shell + which riscv32-unknown-elf-gcc + ``` - - - 2. Run the **chmod** command to change the directory permission to **755**. - - + 2. Run the **chmod** command to change the permission for the directory to **755**. ### "No module named 'Crypto'" -- **Symptom** - - The build fails, and **No module named 'Crypto'** is displayed. +- **Symptom**
The build fails, and "No module named'Crypto'" is displayed. -- **Possible Causes** +- **Possible Causes**
Crypto is not installed in Python3. - Crypto is not installed in Python3. - -- **Solution** +- **Solution**
1. Run the following command to query the Python version: @@ -96,17 +68,13 @@ sudo pip3 install pycryptodome ``` -### "xx.sh : xx unexpected operator" - -- **Symptom** - - The build fails, and **xx.sh [: xx unexpected operator** is displayed. +### "xx.sh: xx unexpected operator" -- **Possible Causes** +- **Symptom**
The build fails, and " xx.sh [: xx unexpected operator" is displayed. - The build environment shell is not bash. +- **Possible Causes**
The build environment shell is not bash. -- **Solution** +- **Solution**
```shell sudo rm -rf /bin/sh @@ -114,20 +82,31 @@ ``` -### "some services are not authenticated. Listed as follows" +### "some services are not authenticated. Listed as follow" + +- **Symptom**
The build fails, and " some services are not authenticated. Listed as follow" is displayed. + +- **Possible Causes**
In the .cfg file of the processes listed in the error message, **uid** is set to **root** or **system**. However, these processes are not high-privilege processes defined by the product. + +- **Solution**
+ + Modify the process .cfg file to reduce the privilege level. Do not set **uid** to **root** or **system** unless necessary. + + If a process must have the **root** or **system** privilege due to service requirements, modify the **high_privilege_process_list.json** file with the approval of the security experts. The **high_privilege_process_list.json** file is located in **vendor/***{company_name}/{product_name }***/security_config**. -- **Symptom** + For example, the file for rk3586 is **//vendor/hihope/rk3568/security_config/high_privilege_process_list.json**. - The build fails, and "some services are not authenticated. Listed as follows" is displayed. -- **Possible Causes** +### "Error: some services do not match with critical whitelist" - For the processes listed in the error information, the UID is set to **root** or **system** in the process configuration files. However, these processes are not high-privilege processes defined by the product. +- **Symptom**
The build fails, and "Error: some services do not match with critical whitelist" is displayed. -- **Solution** +- **Possible Causes**
In the .cfg file of the processes listed in the error message, the **critical** field is defined and enabled. However, the **critical** field is not allowed for the processes, or the **critical** setting does not match the settings in the whitelist. - Modify the process configuration file to reduce the privilege level. Do not set **UID** to **root** or **system** unless necessary. +- **Solution**
- If a process must have the **root** or **system** privilege due to service requirements, modify the **high_privilege_process_list.json** file with the approval of security experts. The **high_privilege_process_list.json** file is located in **vendor/**{*company_name*}/{*product_name*}**/security_config**. For example, the file for rk3586 is **//vendor/hihope/rk3568/security_config/high_privilege_process_list.json**. + Remove the **critical** field or set the first bit of the **critical** field to **0** in the .cfg file of the processes. Do not enable the **critical** field unless necessary. + For details about how to use the **critical** field, see [Service Management](subsys-boot-init-service.md). If **critical** needs to be enabled for a process due to service requirements, modify the **//vendor/{company_name}/{product_name}/security_config/critical_reboot_process_list.json** file with the approval of the security experts. + For example, the critical_reboot process control whitelist of rk3586 is **//vendor/hihope/rk3568/security_config/critical_reboot_process_list.json**. diff --git a/en/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md b/en/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md index 1826640aa51bd09a66a8f72c5d5a0bacdbca76ea..20e4556164d6b9955c5eef54b2f2a696e4546cad 100644 --- a/en/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md +++ b/en/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @@ -17,7 +17,7 @@ The HAP provides HAP build functions and supports FA and stage models. ## How to Develop -### Templates +### OpenHarmony Templates #### ohos_hap This template declares a HAP target, which generates a HAP that will be packaged into the system image. @@ -27,8 +27,8 @@ This template declares a HAP target, which generates a HAP that will be packaged | hap_profile | Configuration file of the HAP. It is **config.json** for the FA model and **module.json** for the stage model.| | raw_assets | Raw assets, which are directly copied to the **assets** directory of the HAP.| | resources | Resource files, which are stored in the **assets/entry/resources** directory after build.| -| js_assets | JS resources, which are stored in the **assets/js/default** directory after built with Ace.| -| ets_assets | eTS resources, which are stored in the **assets/js/default** directory after built with Ace.| +| js_assets | JS resources, which are stored in the **assets/js/default** directory after built.| +| ets_assets | eTS resources, which are stored in the **assets/js/default** directory after built.| | deps | Dependencies of the target.| | shared_libraries | Native libraries on which the target depends.| | hap_name | HAP name, which is optional. By default, it is the target name.| @@ -55,7 +55,7 @@ Declares the AppScope module of the HAP. The **app_profile** and **sources** var | sources | Resources in the AppScope module of the HAP. This variable is used only in the stage model.| #### ohos_js_assets -Provides JS or eTS code, which is stored in the **assets/js/default** directory after built with Ace. In the stage model, this template is stored in the **assets/js** or **assets/ets** directory, depending on the programming language. +Provides JS or eTS code, which is stored in the **assets/js/default** directory after built. In the stage model, this template is stored in the **assets/js** or **assets/ets** directory, depending on the programming language. | Variable| Description| | --------- | ---- | @@ -84,7 +84,7 @@ Resource files, which are stored in the **assets/entry/resources** directory for 1. Save the developed application example to the **applications/standard/** directory. -2. Configure the GN script **applications/standard/example/BUILD.gn**.
The following is an example of the FA model. For details about more **BUILD.gn** configurations, see [GN Script Configuration Example](#gn-script-configuration-example). +2. Configure the GN script **applications/standard/example/BUILD.gn**.
The following is an example of the FA model. For details about more **BUILD.gn** configurations, see [GN Script Configuration Example](#gn-script-configuration-example). ``` import("//build/ohos.gni") # Import ohos.gni. @@ -103,7 +103,7 @@ Resource files, which are stored in the **assets/entry/resources** directory for } ``` -3. Modify the **applications/standard/hap/ohos.build** file.
The following is an example: +3. Modify the **applications/standard/hap/ohos.build** file.
The following is an example: ``` { "subsystem": "applications", diff --git a/en/device-dev/subsystems/subsys-remote-start.md b/en/device-dev/subsystems/subsys-remote-start.md deleted file mode 100644 index 2c3b0e4d5866b238e62f7c488d1033d0f0565027..0000000000000000000000000000000000000000 --- a/en/device-dev/subsystems/subsys-remote-start.md +++ /dev/null @@ -1,107 +0,0 @@ -# Distributed Remote Startup - -## Overview - -The Distributed Manager Service sets up a distributed service platform in OpenHarmony by using a proxy between the primary and secondary devices. With the Distributed Manager Service, the primary device \(OpenHarmony-powered smart TV\) can start a Feature Ability \(FA\) deployed on the secondary device \(a memory-constrained OpenHarmony device such as an IP camera or a lite wearable\). - -For example, if a user presses the **Remind Me** button for a TV program on the smart TV, the smart TV will start the corresponding reminder FA on the lite wearable to remind the user when the particular TV program is available. - -## Basic Concepts - -- FA - - Feature Ability, representing an ability with a UI for interacting with users - - -- Remote startup - - Cross-device FA startup, which is the counterpart of local FA startup - - -## Available APIs - -The following table describes the API that can be used by smart TVs to remotely start an FA. This API is provided in the **AbilitySlice** class. For details, see the Java API reference for OpenHarmony application development. - -**Table 1** API for remotely starting an FA on the distributed network - - - - - - - - - - -

Method

-

Description

-

void startAbility(Want want)

-

Remotely starts an FA based on the specified Want information. If the name and type of the want parameter are different from those used in the integrated development environment (IDE), use the parameter name and type in the IDE.

-
- -**Table 2** Description of the want parameter - - - - - - - - - - - - -

Parameter

-

Type

-

Description

-

want

-

ohos.aafwk.content.Want

-

When you use startAbility(Want want) to remotely start an FA, you must first specify the deviceId, bundleName, and abilityName attributes of the target FA in the Want object.

-
- -## Limitations and Constraints - -- The primary device can remotely start an FA of the secondary device, but the secondary device cannot remotely start an FA of the primary device. -- Before the remote startup, ensure that the two OpenHarmony devices are on the same network segment and can ping each other on the distributed network. Otherwise, the remote startup fails. -- Currently, only the FAs that have the same public key \(that is, the same Huawei certificate\) can be started between the primary and secondary devices. - -## How to Develop - -To enable the primary device \(smart TV\) to start an FA of the secondary device \(assuming that the target FA has been developed\), perform the following steps: - -1. Complete FA development for the smart TV on DevEco Studio. -2. Obtain the IDs of online secondary devices. - - ``` - // Import the header files required for device selection. - import ohos.distributedschedule.interwork.DeviceInfo; - import ohos.distributedschedule.interwork.DeviceManager; - - // Obtain the online device list. - List deviceInfoListOnline = DeviceManager.getDmsDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE); - String remote_device_id; - if (deviceInfoListOnline.size() > 0) - { - remote_device_id = deviceInfoListOnline[0].GetDeviceId(); // Obtain the ID of the first device in the online device list. - } - ``` - -3. Create a **Want** instance. You should first create an **ElementName** object with **deviceId**, **bundleName**, **abilityName** specified and add this object to the **Want** instance. Then, set the multi-device startup flag **Want.FLAG\_ABILITYSLICE\_MULTI\_DEVICE** to the **Want** instance to enable remote FA startup. - - ``` - // Import related header files. - import ohos.aafwk.ability.Ability; - import ohos.aafwk.content.Want; - import ohos.bundle.ElementName; - - // Start the remote FA on the secondary device. - Want want = new Want(); // Create a Want instance that encapsulates information about the remote FA to start. - // Use the device ID obtained in step 2 and specify the FA information. - ElementName name = new ElementName(remote_device_id, "com.huawei.remote_package_name", "remote_class_name"); - want.setElement(name); // Add information about the target FA for startup to the Want instance. - want.setFlags(Want.FLAG_ABILITYSLICE_MULTI_DEVICE); // Set the multi-device startup flag. If this flag is not set, remote FA startup will be unavailable. - startAbility(want); // Start the specified FA based on the want parameter. If the name and type of the want parameter are different from those used in the IDE, use the parameter name and type in the IDE. - ``` - - diff --git a/en/device-dev/subsystems/subsys-security-huks-guide.md b/en/device-dev/subsystems/subsys-security-huks-guide.md index 3f315b54ce4e2b57b03b89c1a4b9828ba2b0932a..d9cd48403f47fda888f4c27ab43cc96a36ad87e6 100644 --- a/en/device-dev/subsystems/subsys-security-huks-guide.md +++ b/en/device-dev/subsystems/subsys-security-huks-guide.md @@ -1,159 +1,213 @@ -# Development on HUKS +# HUKS Development ## Overview -### Introduction +### HUKS -OpenHarmony Universal KeyStore (HUKS) provides system-level key management capabilities, ensuring secure management and use of keys throughout their lifecycle (generation, storage, use, and destruction). The environment where a key is stored and used is of the most importance to key security. For example, the key in plaintext must be used in a secure environment, such as a Trusted Execution Environment (TEE) or security chip. This document describes how to configure a secure environment based on the HUKS architecture and how to verify the configuration. +OpenHarmony Universal KeyStore (HUKS) provides lifecycle key management from key generation, storage, use to destruction and attestation for the keys stored in the HUKS. In the HUKS hierarchical architecture, the HUKS core layer (HUKS Core) at the bottom implements key management functions and runs in a secure hardware environment, such as a Trusted Execution Environment (TEE) or secure chipset. The implementation of the HUKS core layer varies depending on the secure hardware environment of the vendor. To ensure consistency of the architecture and interfaces between the service layer and application layer, the HUKS core layer defines a set of Hardware Device Interface (HDI) APIs. -HUKS supports key lifecycle management, which covers the following: +This document describes how to develop the HUKS core layer functions using the HUKS HDI APIs. -- Key generation and import +The HUKS core layer is supposed to support the following functions: -- Key storage +- Generation of keys. -- Key use (including encryption and decryption, signing and verification, key derivation and agreement, hash, and key access control) +- Import of keys. -- Key destruction +- Key operations, including encryption and decryption, signing and signature verification, key derivation, key agreement, and generation of message authentication codes (MACs). -### Basic Concepts +- Key access control. + +- Key attestation. -- HUKS Service +- Export of the public key from a chipset. - An independent OpenHarmony service that supports key management. It belongs to the huks_service process. Instead of handling key calculation, the HUKS Service depends on the HUKS Core to provide services for the upper layer. +### Basic Concepts - HUKS Core + + HUKS Core is a core component that implements functions, including cryptographic calculation of keys, encryption and decryption, and key access control. Generally, it runs in a secure environment (such as a TEE or secure chipset) of a device to ensure that the keys in plaintext are never exposed outside the HUKS Core. + +- Key session + + A key session holds the key information, including the key operation data, key properties, and access control attributes, when a key is used. You need to pass in a key alias to create a session for the key. The HUKS generates a globally unique handle for each session. A general key operation involves creating a session, passing in data and parameters, and finishing the session (or aborting the session). - A functional module that provides the key management service. This module must run in a secure environment, and the keys in plaintext must be kept inside the HUKS Core module throughout the lifecycle. - TEE - A secure area created by isolating software and hardware resources to protect the applications and data in the secure area from unauthorized access. This isolation mechanism yields two execution environments: TEE and Rich Execution Environment (REE). Each execution environment has independent internal data path and memory, protecting the data inside the TEEs from being disclosed. The applications in an REE cannot access resources in a TEE. The applications in a TEE cannot access resources in another TEE without authorization. + A TEE is a secure area created by isolating software and hardware resources to protect the applications and data in the secure area from unauthorized access. This isolation mechanism yields two execution environments: TEE and Rich Execution Environment (REE). Each execution environment has independent internal data path and memory, protecting the data inside the TEE from being disclosed. The applications in an REE cannot access resources in a TEE. The applications in a TEE cannot access resources in another TEE without authorization. + + +## Working Principles + +The HUKS is divided into the following layers: + +- Application layer: provides APIs for applications. +- Service layer: processes key management requests from applications and performs key ciphertext management, identity verification, and key session management. +- Core layer: implements core functions, such as key generation, key operations, key access control, and key attestation. + +**Figure 1** HUKS architecture -- Init-Update-Finish +![huks_architect](./figures/HUKS-architecture.png) - **Init**: initializes data for a key operation. +## Constraints - **Update**: operates data by segment and returns the result, or appends data. + - Keys in a secure environment in lifecycle - **Finish**: finalizes the **Update** operation, and returns the result. + In the lifecycle of a key, the plaintext will never be exposed outside the HUKS Core. For the devices with a TEE or secure chipset, the HUKS Core runs in the TEE or secure chipset. This prevents the key plaintext from being disclosed even if the REE is cracked. That is why the key materials used in all HUKS passthrough HDI APIs are in ciphertext. -### Working Principles +- Encrypted keys for storage -The following uses the key generation process as an example to describe the communication between the HUKS Service and HUKS Core. Other key operations are similar. -The upper-layer application invokes the HUKS Service through the key management SDK. The HUKS Service invokes the HUKS Core, which invokes the key management module to generate a key. The HUKS Core uses a work key derived from the root key to encrypt the generated key and sends the encrypted key to the HUKS Service. The HUKS Service stores the encrypted key in a file. + The service keys are encrypted based on the device root key. If supported by the device, certain keys can be further protected by a password. -![](figures/HUKS-GenerateKey1.png) +- Strict access control over keys -### Constraints + Only authorized services can access keys. For security-critical services, user identity authentication can be enabled for key access. + +- Key attestation -* HUKS must be implemented in a TEE for security purposes. + The HUKS provides attestation for hardware-backed key storage. It proves that the key has not been tampered with, is stored in the hardware-backed HUKS Core, and has correct key properties. -* The certificate chain returned by **HuksHdiAttestKey** must be in the sequence of the application certificate, device certificate, CA certificate, and root certificate, with the certificate length added before each certificate. The certificate chain and its length are assembled in the binary large object (BLOB) format. If you want to define the certificate format, the format must be the same as that parsed by the server. +- Key material format + + When a key (key pair, public key, or private key) is imported or exported, the key material format must meet HUKS requirements. For details, see [Key Material Formats](../../application-dev/security/huks-appendix.md#key-material-formats). -![CertChain format](figures/HUKS-CertChain.png) +- Certificate chain format -* The key returned by the API must be assembled into a **KeyBlob** based on the key storage status. For details about the APIs that must comply with this constraint, see [Available APIs](#available-apis). + The certificate chain returned by **AttestKey()** must be assembled in the sequence of the application certificate, device certificate, CA certificate, and root certificate, with the certificate length added before each certificate. The certificate chain and its length are in the binary large object (BLOB) format. If you want to define the certificate format, the format must be the same as that parsed by the server. - The **KeyBlob** stores both the key and its attributes. The figure below shows the **KeyBlob** structure. For details about how to construct a **KeyBlob**, see [hks_keyblob.c/HksBuildKeyBlob](https://gitee.com/openharmony/security_huks/blob/master/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c). + ![CertChain format](figures/HUKS-CertChain.png) -![KeyBlob format](figures/HUKS-KeyBlob.png) +- KeyBlob + -## Development Guidelines +The key returned by the APIs must be assembled into a **KeyBlob** based on the key storage status. For details about the APIs that must comply with this constraint, see [Available APIs](#available-apis). + + ![KeyBlob format](figures/HUKS-KeyBlob.png) + +## How to Develop ### When to Use -The HUKS Core provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. If you want to replace the HUKS Core with your own implementation, you need to implement the following APIs: +The HUKS Core provides KeyStore capabilities for applications, including key management and cryptographic operations. If you want to replace the HUKS Core with your own implementation, you need to implement the following APIs. ### Available APIs **Table 1** Available APIs -| API | Description | Constraints | Corresponding JS API | +| API | Description | Constraints | JS API | | ------------------------------------------------------------ | ---------------------------------------- | ----------------------------- | ------------------------------------------------------------ | -| [HuksHdiModuleInit()](#hukshdimoduleinit) | Initializes the HUKS Core. | – | –| -| [HuksHdiRefresh()](#hukshdirefresh) | Refreshes the root key. | – | –| -| [HuksHdiGenerateKey()](#hukshdigeneratekey) | Generates a key. | The key generated must be in the **KeyBlob** format. |generateKey(keyAlias: string, options: HuksOptions)| -| [HuksHdiImportKey()](#hukshdiimportkey) | Imports a key in plaintext. | The output parameter must be in the **KeyBlob** format. | importKey(keyAlias: string, options: HuksOptions)| -| [HuksHdiImportWrappedKey()](#hukshdiimportwrappedkey) |Imports an encrypted key. | The output parameter must be in the **KeyBlob** format. | importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions)| -| [HuksHdiExportPublicKey()](#hukshdiexportpublickey) | Exports a public key. |– | exportKey(keyAlias: string, options: HuksOptions) | -| [HuksHdiInit()](#hukshdiinit) | Initializes data for a key operation. This API is of the Init-Update-Final model. |– | init(keyAlias: string, options: HuksOptions) | -| [HuksHdiUpdate()](#hukshdiupdate) | Operates data by segment or appends data for the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the raw data. | update(handle: number, token?: Uint8Array, options: HuksOptions) | -| [HuksHdiFinish()](#hukshdifinish) | Finalizes the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the signed data. | finish(handle: number, options: HuksOptions) | -| [HuksHdiAbort()](#hukshdiabort) | Aborts Init-Update-Finish. |– | abort(handle: number, options: HuksOptions) | -| [HuksHdiGetKeyProperties()](#hukshdigetkeyproperties) | Obtains key properties. |– | getKeyProperties(keyAlias: string, options: HuksOptions)| -| [HuksHdiAttestKey()](#hukshdiattestkey) | Obtains the key certificate. |The output parameter must be in the **certChain** format. | attestKey(keyAlias: string, options: HuksOptions)| -| [HuksHdiExportChipsetPlatformPublicKey()](#hukshdiexportchipsetplatformpublickey) | Exports the public key of a chipset key pair. | The output parameters are the raw data of ECC P-256 x-axis and y-axis values, each of which are of 32 bytes. | –| -| [HuksHdiUpgradeKey()](#hukshdiupgradekey) | Updates the key file. | – | –| +| [ModuleInit()](#moduleinit) | Initializes the HUKS Core. | N/A | N/A| +| [ModuleDestroy()](#moduledestroy) | Destroys the HUKS Core. | N/A | N/A| +| [GenerateKey()](#generatekey) | Generates a key based on the cryptographic algorithm parameters. | The key output must be in the **KeyBlob** format. |generateKey(keyAlias: string, options: HuksOptions)| +| [ImportKey()](#importkey) | Imports a key in plaintext. | The key output must be in the **KeyBlob** format. | importKey(keyAlias: string, options: HuksOptions)| +| [ImportWrappedKey()](#importwrappedkey) |Imports a wrapped (encrypted) key. | The key output must be in the **KeyBlob** format. | importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions)| +| [ExportPublicKey()](#exportpublickey) | Exports the public key of a key pair. |N/A | exportKey(keyAlias: string, options: HuksOptions) | +| [Init()](#init) | Initializes a key session. This API returns a key session handle and an authentication token (optional). |N/A | init(keyAlias: string, options: HuksOptions) | +| [Update()](#update) | Updates key operation data. |The input parameters for signature verification must be the raw data. | update(handle: number, token?: Uint8Array, options: HuksOptions) | +| [Finish()](#finish) | Finishes a key session. |The input parameter for signature verification must be the signed data. | finish(handle: number, options: HuksOptions) | +| [Abort()](#abort) | Aborts a key session. |N/A | abort(handle: number, options: HuksOptions) | +| [CheckKeyValidity()](#checkkeyvalidity) | Checks the key material (ciphertext) validity. |N/A | N/A| +| [AttestKey()](#attestkey) | Attests a key. |The output parameter must be in the certificate chain format. | attestKey(keyAlias: string, options: HuksOptions)| +| [ExportChipsetPlatformPublicKey()](#exportchipsetplatformpublickey) | Exports the public key of a chipset key pair. | The output parameters are the raw data of ECC P-256 x-axis and y-axis values, each of which are of 32 bytes. | N/A| +| [UpgradeKey()](#upgradekey) | Updates the key file. | N/A | N/A| +| [GenerateRandom()](#generaterandom) | Generates a random number. | N/A | N/A| +| [Encrypt()](#encrypt) | Encrypts data. | N/A | N/A| +| [Decrypt()](#decrypt) | Decrypts data. | N/A | N/A| +| [Sign()](#sign) | Signs data. | N/A | N/A| +| [Verify()](#verify) | Verifies a signature. | N/A | N/A| +| [AgreeKey()](#agreekey) | Performs key agreement. | N/A | N/A| +| [DeriveKey()](#derivekey) | Derives a key. | N/A | N/A| +| [Mac()](#mac) | Generates a MAC. | N/A | N/A| - - - -#### HuksHdiModuleInit +#### ModuleInit **API Description** -Initializes the HUKS Core, including the lock, encryption algorithm library, authtoken key, and root key. +Initializes the HUKS Core. You can use this API to initialize global variables, such as the global thread locks, algorithm library, and the AuthToken key and root key used for access control. **Prototype** -
int32_t HuksHdiModuleInit();
+
int32_t ModuleInit(struct IHuks *self);
+
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  
+
Return Value - - **HKS_SUCCESS**: The operation is successful. + - **HKS_SUCCESS** (the value is **0**): The operation is successful. - - Other value: The operation failed. + - Other values (negative number): The operation fails. For details, see HksErrorCode.
- - - -#### HuksHdiRefresh + +#### ModuleDestroy **API Description** -Refreshes the root key. +Destroys the HUKS Core. You can use this API to release global variables including the locks and destroy the AuthToken key and root key in the memory. **Prototype** -
int32_t HuksHdiRefresh();
+
int32_t ModuleDestroy(struct IHuks *self);
+
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  
+
Return Value - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails.
- - - -#### HuksHdiGenerateKey +#### GenerateKey **API Description** -Generates a key based on **paramSet**. +Generate a key based on the **paramSet**. **Prototype** -
int32_t HuksHdiGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, const struct HksBlob *keyIn, struct HksBlob *keyOut);
+
int32_t GenerateKey(struct IHuks *self, const struct HuksBlob *keyAlias, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *keyIn, struct HuksBlob *encKeyOut);
Parameters
-  const struct HksBlob *keyAlias
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *keyAlias Pointer to the alias of the key to generate. The value must meet the following requirements: 1. keyAlias != null 2. keyAlias -> data != null - 3. keyAlias -> size != 0 + 3. keyAlias -> dataLen != 0

- const struct HksParamSet *paramSet + const struct HuksParamSet *paramSet Pointer to the parameters for generating the key.

- const struct HksBlob *keyIn - This parameter is used in key agreement. + const struct HuksBlob *keyIn + Pointer to the original key material to be passed in if the key is generated through key agreement or key derivation. This parameter is optional.

- struct HksBlob *keyOut - Pointer to the output parameter, which holds **paramSet** and the key generated. + struct HuksBlob *encKeyOut + Pointer to the key generated in ciphertext. It holds the **paramSet** and the key ciphertext in the KeyBlob format.
+

@@ -171,41 +225,44 @@ Generates a key based on **paramSet**. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails.
- - - -#### HuksHdiImportKey +#### ImportKey **API Description** Imports a key in plaintext. **Prototype** -
int32_t HuksHdiImportKey(const struct HksBlob *keyAlias, const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut);
+
int32_t ImportKey(struct IHuks *self, const struct HuksBlob *keyAlias, const struct HuksBlob *key,
+    const struct HuksParamSet *paramSet, struct HuksBlob *encKeyOut);
Parameters
-  const struct HksBlob *msg
-  Pointer to the alias of the key to import. The value must meet the following requirements:
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *keyAlias + Pointer to the alias of the key to import. The alias must meet the following requirements: 1. keyAlias != null 2. keyAlias -> data != null - 3. keyAlias -> size != 0 + 3. keyAlias -> dataLen != 0

- const struct HksBlob *key - Pointer to the key to import. The value must meet the following requirements: + const struct HuksBlob *key + Pointer to the plaintext key material to import. For details about the key material format, see Key Material Formats. The value must meet the following requirements: 1. key != null 2. key -> data != null - 3. key -> size != 0 -

- const struct HksParamSet *paramSet - Pointer to the parameters for importing the key. + 3. key -> dataLen != 0

- struct HksBlob *keyOut - Pointer to the output parameter, which holds **paramSet** and the key imported. + const struct HuksParamSet *paramSet + Pointer to the parameters of the key to import.

+ struct HuksBlob *encKeyOut + Pointer to the imported key in ciphertext. It holds the **paramSet** and the imported key ciphertext in the KeyBlob format.


@@ -215,7 +272,7 @@ Imports a key in plaintext. 1. Check parameters in the API. For example, check for null pointers and whether the key algorithm is supported. - 2. **keyOut** must be in the **KeyBlob** format. + 2. Check that **encKeyOut** is in the KeyBlob format.

@@ -225,48 +282,54 @@ Imports a key in plaintext. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiImportWrappedKey +#### ImportWrappedKey **API Description** -Imports an encrypted key. +Imports a wrapped key. **Prototype** -
int32_t HuksHdiImportWrappedKey(const struct HksBlob *keyAlias, const struct HksBlob *wrappingUsedkey, const struct HksBlob *wrappedKeyData, const struct HksParamSet *paramSet, struct HksBlob *keyOut);
+
int32_t ImportWrappedKey(struct IHuks *self, const struct HuksBlob *wrappingKeyAlias,
+    const struct HuksBlob *wrappingEncKey, const struct HuksBlob *wrappedKeyData, const struct HuksParamSet *paramSet,
+    struct HuksBlob *encKeyOut);
Parameters
-  const struct HksBlob *KeyAlias
-  Pointer to the alias of the key to import. The value must meet the following requirements:
-  1. keyAlias != null
-  2. keyAlias -> data != null
-  3. keyAlias -> size != 0
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *wrappingKeyAlias + Pointer to the alias of the key used to encrypt the key to import (it is not the alias of the key to import). The value must meet the following requirements: + 1. wrappingKeyAlias != null + 2. wrappingKeyAlias -> data != null + 3. wrappingKeyAlias -> dataLen != 0

- const struct HksBlob *key + const struct HuksBlob *wrappingEncKey Pointer to the key used to encrypt the key to import. The value must meet the following requirements: - 1. wrappingUsedkey != null - 2. wrappingUsedkey -> data != null - 3. wrappingUsedkey -> size != 0 + 1. wrappingEncKey != null + 2. wrappingEncKey -> data != null + 3. wrappingEncKey -> dataLen != 0

- const struct HksBlob *wrappedKeyData - Pointer to the encrypted data of the key to import. The value must meet the following requirements: + const struct HuksBlob *wrappedKeyData + Pointer to the key material of the key to import. For details abut the key material format, see Importing a Key Securely. The value must meet the following requirements: 1. wrappedKeyData != null 2. wrappedKeyData -> data != null - 3. wrappedKeyData -> size != 0 + 3. wrappedKeyData -> dataLen != 0

- const struct HksParamSet *paramSet - Pointer to the parameters for importing the key. + const struct HuksParamSet *paramSet + Pointer to the properties of the key to import.

- struct HksBlob *keyOut - Pointer to the output parameter, which holds **paramSet** and the key imported. + struct HuksBlob *encKeyOut + Pointer to the imported key material (ciphertext) in the KeyBlob format.
+

@@ -274,7 +337,7 @@ Imports an encrypted key. 1. Check parameters in the API. For example, check for null pointers and whether the key algorithm is supported. - 2. **keyOut** must be in the **KeyBlob** format. + 2. Check that **encKeyOut** is in the KeyBlob format.


@@ -284,34 +347,38 @@ Imports an encrypted key. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiExportPublicKey +#### ExportPublicKey **API Description** -Exports a public key. +Exports the public key of a key pair. **Prototype** -
int32_t HuksHdiExportPublicKey(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut);
+
int32_t ExportPublicKey(struct IHuks *self, const struct HuksBlob *encKey,
+    const struct HuksParamSet *paramSet, struct HuksBlob *keyOut);
Parameters
-  const struct HksBlob *key
-  Pointer to the private key corresponding to the public key to export. The value must meet the following requirements:
-  1. key != null
-  2. key -> data != null
-  3. key -> size != 0
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *encKey + Pointer to the key pair material. The value must meet the following requirements: + 1. encKey != null + 2. encKey -> data != null + 3. encKey -> dataLen != 0

- const struct HksParamSet *paramSet - Pointer to the parameter set, which is empty. + const struct HuksParamSet *paramSet + Pointer to the parameters for exporting the public key. By default, this parameter is left blank.

- struct HksBlob *keyOut - Pointer to the output parameter, which holds the public key exported. + struct HuksBlob *keyOut + Pointer to the public key exported.


@@ -321,39 +388,51 @@ Exports a public key. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiInit +#### Init **API Description** -Initializes data for a key operation. This API is of the Init-Update-Final model. +Initializes a key session. You need to pass in the key material in ciphertext. The HUKS Core decrypts the ciphertext and generates a key session handle and an authentication token (if required). **Prototype** -
int32_t HuksHdiInit(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *handle, struct HksBlob *token);
+
int32_t Init(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+    struct HuksBlob *handle, struct HuksBlob *token);
Parameters
-  const struct HksBlob *key
-  Pointer to the key, on which the **Init** operation is to perform. The value must meet the following requirements:
-  1. key != null
-  2. key -> data != null
-  3. key -> size != 0
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- const struct HksParamSet *paramSet - Pointer to the parameters of the **Init** operation. + const struct HuksBlob *encKey + Pointer to the ciphertext material of the key to be operated. The value must meet the following requirements: + 1. encKey != null + 2. encKey -> data != null + 3. encKey -> dataLen != 0

- struct HksBlob *handle - Pointer to the handle of Init-Update-Finish. + const struct HuksParamSet *paramSet + Pointer to the parameters for initializing the key session.

- struct HksBlob *token - Pointer to the challenge used for secure access control. + struct HuksBlob *handle + Pointer to the key session handle generated, which identifies the key session in Update(), Finish(), and Abort(). +

+ struct HuksBlob *token + Pointer to the authentication token generated for key access control (if required).
+ +

+ +
+ Constraints +This API must be used with **Update()**, **Finish()**, and **Abort()** together. + +


@@ -361,34 +440,38 @@ Initializes data for a key operation. This API is of the Init-Update-Final model - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails.
- - - -#### HuksHdiUpdate +#### Update **API Description** -Operates data by segment or appends data for the key operation. This API is of the Init-Update-Final model. +Updates data for the key operation by segment according to the cryptographic algorithm requirements. **Prototype** -
int32_t HuksHdiUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);
+
int32_t Update(struct IHuks *self, const struct HuksBlob *handle, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *inData, struct HuksBlob *outData);
Parameters
-  const struct HksBlob *handle
-  Pointer to the handle of Init-Update-Finish.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- const struct HksParamSet *paramSet - Pointer to the parameters of the **Update** operation. + const struct HuksBlob *handle + Pointer to the handle of the key session.

- const struct HksBlob *inData - Pointer to the input of the **Update** operation. + const struct HuksParamSet *paramSet + Pointer to the parameters for the update operation.

- struct HksBlob *outData - Pointer to the result of the **Update** operation. + const struct HuksBlob *inData + Pointer to the data to be passed in. +

+ struct HuksBlob *outData + Pointer to the result of the update operation.


@@ -396,7 +479,9 @@ Operates data by segment or appends data for the key operation. This API is of t
Constraints - 1. **inData** must pass in the raw data when signing and signature verification are performed. + 1. This API must be used with **Init()**, **Finish()**, and **Abort()** together. + + 2. **inData** must pass in the raw data when signature verification is performed.


@@ -406,34 +491,38 @@ Operates data by segment or appends data for the key operation. This API is of t - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiFinish +#### Finish **API Description** -Finalizes the key operation. This API is of the Init-Update-Final model. +Finishes the key session. **Prototype** -
int32_t HuksHdiFinish(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);
+
int32_t Finish(struct IHuks *self, const struct HuksBlob *handle, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *inData, struct HuksBlob *outData);
Parameters
-  const struct HksBlob *handle
-  Pointer to the handle of Init-Update-Finish.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- const struct HksParamSet *paramSet - Pointer to the parameters of the **Finish** operation. + const struct HuksBlob *handle + Pointer to the handle of the key session.

- const struct HksBlob *inData - Pointer to the input of the **Finish** operation. + const struct HuksParamSet *paramSet + Pointer to the parameters for the last operation.

- struct HksBlob *outData - Pointer to the result of the **Finish** operation. + const struct HuksBlob *inData + Pointer to the last data to be passed in. +

+ struct HuksBlob *outData + Pointer to the result of the key operation.


@@ -441,7 +530,9 @@ Finalizes the key operation. This API is of the Init-Update-Final model.
Constraints - 1. In signing and signature verification, **inData** must pass in the signature data to be verified. The return value indicates whether the operation is successful. + 1. This API must be used with **Init()**, **Update()**, and **Abort()** together. + + 2. In signature verification, **inData** must pass in the signature data to be verified. The return value indicates whether the signature has passed the verification.


@@ -451,30 +542,40 @@ Finalizes the key operation. This API is of the Init-Update-Final model. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiAbort +#### Abort **API Description** -Aborts Init-Update-Finish. When an error occurs in any of the **Init**, **Update**, and **Finish** operations, call this API to terminate the use of the key. +Aborts the key session. When an error occurs in any of the **Init**, **Update**, and **Finish** operations, call this API to terminate the key session. **Prototype** -
int32_t HuksHdiAbort(const struct HksBlob *handle, const struct HksParamSet *paramSet);
- +
int32_t Abort(struct IHuks *self, const struct HuksBlob *handle, const struct HuksParamSet *paramSet);
Parameters
-  const struct HksBlob *handle
-  Pointer to the handle of Init-Update-Finish.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- const struct HksParamSet *paramSet - Pointer to the parameters of the **Abort** operation. + const struct HuksBlob *handle + Pointer to the handle of the key session. +

+ const struct HuksParamSet *paramSet + Pointer to the parameters of the Abort() operation.
+ +

+ +
+ Constraints +This API must be used with **Init()**, **Update()**, and **Finish()** together. + +


@@ -482,28 +583,32 @@ Aborts Init-Update-Finish. When an error occurs in any of the **Init**, **Update - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails.
- - - -#### HuksHdiGetKeyProperties +#### CheckKeyValidity **API Description** -Obtains key properties. +Checks key validity. **Prototype** -
int32_t HuksHdiGetKeyProperties(const struct HksParamSet *paramSet, const struct HksBlob *key);
+
int32_t CheckKeyValidity(struct IHuks *self, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *encKey);
Parameters
-  const struct HksParamSet *paramSet
-  Pointer to the parameter set, which is empty.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksParamSet *paramSet + Pointer to the parameters for checking the key integrity. By default, this parameter is left empty.

- const struct HksBlob *key - Pointer to the target key. + const struct HuksBlob *encKey + Pointer to the key material (ciphertext) to be checked.


@@ -513,39 +618,42 @@ Obtains key properties. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiAttestKey +#### AttestKey **API Description** -Obtains the key certificate. +Attests a key. **Prototype** -
int32_t (*HuksHdiAttestKey)(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *certChain);
+
int32_t AttestKey(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+    struct HuksBlob *certChain);
Parameters
-  const struct HksBlob *key
-  Pointer to the target key.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- const struct HksParamSet *paramSet - Pointer to the parameters for the operation. + const struct HuksBlob *encKey + Pointer to the key pair material in ciphertext.

- struct HksBlob *certChain - Pointer to the output parameter, which holds the certificate obtained. + const struct HuksParamSet *paramSet + Pointer to the parameters (such as the challenge) for obtaining the key certificate chain. +

+ struct HuksBlob *certChain + Pointer to the certificate chain obtained.


Constraints - - 1. **certChain** must comply with the certificate chain described in [Constraints](#constraints). +**certChain** must comply with the certificate chain described in [Constraints](#constraints).


@@ -555,40 +663,44 @@ Obtains the key certificate. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiExportChipsetPlatformPublicKey +#### ExportChipsetPlatformPublicKey **API Description** Exports the public key of a chipset key pair. **Prototype** -
int32_t (*HuksHdiExportChipsetPlatformPublicKey)(const struct HksBlob *salt, enum HksChipsetPlatformDecryptScene scene, struct HksBlob *publicKey);
+
int32_t ExportChipsetPlatformPublicKey(struct IHuks *self, const struct HuksBlob *salt,
+    enum HuksChipsetPlatformDecryptScene scene, struct HuksBlob *publicKey);
Parameters
-  const struct HksBlob *salt
-  Factor used to derive the chipset key pair.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- enum HksChipsetPlatformDecryptScene scene - Expected chipset platform decryption scenario. + const struct HuksBlob *salt + Pointer to the factor used to derive the chipset key pair.

- struct HksBlob *publicKey - The output parameters are the raw data of ECC P-256 x-axis and y-axis values, each of which are of 32 bytes. + enum HuksChipsetPlatformDecryptScene scene + Expected chipset decryption scenario. +

+ struct HuksBlob *publicKey + Pointer to the raw data of ECC P-256 x-axis and y-axis values, each of which are of 32 bytes.
+

Constraints - - 1. The input parameter **salt** must be of 16 bytes, and the content of the last byte will be ignored and filled by HUKS based on **scene**. - Currently, the chipset key pairs of HUKS are implemented by software. An ECC P-256 key pair is hard-coded, and the **salt** value is ignored. That is, the derived keys are the same regardless of the **salt**. In the hardware-based implementation of chipset key pairs, **salt** is a factor used to derive the key. That is, the key pair derived varies with the **salt** value. +The input parameter **salt** must be of 16 bytes, and the content of the last byte will be ignored and filled by HUKS based on **scene**. +Currently, the chipset key pairs of HUKS are implemented by software. An ECC P-256 key pair is hard-coded, and the **salt** value is ignored. That is, the derived keys are the same regardless of the **salt**. In the hardware-based implementation of chipset key pairs, **salt** is a factor used to derive the key. That is, the key pair derived varies with the **salt** value.


@@ -598,31 +710,35 @@ Exports the public key of a chipset key pair. - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - -#### HuksHdiUpgradeKey +#### UpgradeKey **API Description** Updates the key file when the key file version is earlier than the latest version. **Prototype** -
int32_t (*HuksHdiUpgradeKey)(const struct HksBlob *oldKey, const struct HksParamSet *paramSet, struct HksBlob *newKey);
+
int32_t UpgradeKey(struct IHuks *self, const struct HuksBlob *encOldKey, const struct HuksParamSet *paramSet,
+    struct HuksBlob *encNewKey);
Parameters
-  const struct HksBlob *oldKey
-  Key file data to update.
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
   

- const struct HksParamSet *paramSet - Parameters for updating the key file data. + const struct HuksBlob *encOldKey + Pointer to the key file data to update.

- struct HksBlob *newKey - New key file data. + const struct HuksParamSet *paramSet + Pointer to the parameters for updating the key file data. +

+ struct HuksBlob *newKey + Pointer to the new key file data.


@@ -632,40 +748,396 @@ Updates the key file when the key file version is earlier than the latest versio - **HKS_SUCCESS**: The operation is successful. - - Other value: The operation failed. + - Other values: The operation fails. - - - +#### GenerateRandom + +**API Description** + +Generates a random number. + +**Prototype** + +
int32_t GenerateRandom(struct IHuks *self, const struct HuksParamSet *paramSet, struct HuksBlob *random);
+
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksParamSet *paramSet + Pointer to the parameters of the random number to generate, such as the length. +

+ struct HuksBlob *random + Pointer to the random number generated. +
+
+ +

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### Sign + +**API Description** + +Signs data. + +**Prototype** +
int32_t Sign(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *srcData, struct HuksBlob *signature);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *encKey + Pointer to the key pair material (ciphertext) used for signing. +

+ const struct HuksParamSet *paramSet + Pointer to the parameters used for signing, such as the digest mode. +

+ const struct HuksBlob *srcData + Pointer to the data to be signed. +

+ struct HuksBlob *signature + Pointer to the signature generated. +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### Verify + +**API Description** + +Verifies a digital signature. + +**Prototype** +
int32_t Verify(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *srcData, const struct HuksBlob *signature);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *encKey + Pointer to the key pair material (ciphertext) used for signature verification. +

+ const struct HuksParamSet *paramSet + Pointer to the parameters for signature verification, such as the digest mode. +

+ const struct HuksBlob *srcData + Pointer to the data with the signature to be verified. +

+ const struct HuksBlob *signature + Pointer to the signature to verify. +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### Encrypt + +**API Description** + +Encrypts data. Different from the key session APIs that must be used together, this API completes data encryption in a single call. + +**Prototype** +
int32_t Encrypt(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+     const struct HuksBlob *plainText, struct HuksBlob *cipherText);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *encKey + Pointer to the key material (ciphertext) used for encryption. +

+ const struct HuksParamSet *paramSet + Pointer to the key parameters for encryption, such as the key working mode and padding mode. +

+ const struct HuksBlob *plainText + Pointer to the plaintext data to encrypt. +

+ const struct HuksBlob *cipherText + Pointer to the encrypted data (data in ciphertext). +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### Decrypt + +**API Description** + +Decrypts data. Different from the key session APIs that must be used together, this API completes data decryption in a single call. + +**Prototype** +
int32_t Decrypt(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *cipherText, struct HuksBlob *plainText);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *encKey + Pointer to the key material (ciphertext) used for decryption. +

+ const struct HuksParamSet *paramSet + Pointer to the key parameters for decryption, such as the key working mode and padding mode. +

+ const struct HuksBlob *cipherText + Pointer to the data to decrypt. +

+ const struct HuksBlob *plainText + Pointer to the encrypted data in plaintext. +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### AgreeKey + +**API Description** + +Performs key agreement. Different from the key session APIs that must be used together, this API returns an agreed key in a single call. + +**Prototype** +
int32_t AgreeKey(struct IHuks *self, const struct HuksParamSet *paramSet,
+    const struct HuksBlob *encPrivateKey, const struct HuksBlob *peerPublicKey, struct HuksBlob *agreedKey);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksParamSet *paramSet + Pointer to the parameters for key agreement, such as the length of the agreed key. +

+ const struct HuksBlob *encPrivateKey + Pointer to the private key material (ciphertext) used for key agreement. +

+ const struct HuksBlob *peerPublicKey + Pointer to the public key (plaintext) used for key agreement. +

+ struct HuksBlob *agreedKey + Pointer to the agreed key in plaintext. +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### DeriveKey + +**API Description** + +Derives a key. Different from the key session APIs that must be used together, this API derives a key in a single call. + +**Prototype** +
int32_t DeriveKey(struct IHuks *self, const struct HuksParamSet *paramSet, const struct HuksBlob *encKdfKey,
+     struct HuksBlob *derivedKey);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksParamSet *paramSet + Pointer to the parameters for key derivation, such as the length of the derived key. +

+ const struct HuksBlob *encKdfKey + Pointer to the key material (ciphertext) used for deriving a key. +

+ struct HuksBlob *derivedKey + Pointer to the derived key in plaintext. +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - + +#### Mac + +**API Description** + +Generates a MAC based on the given key. + +**Prototype** +
int32_t Mac(struct IHuks *self, const struct HuksBlob *encKey, const struct HuksParamSet *paramSet,
+     const struct HuksBlob *srcData, struct HuksBlob *mac);
+ +
+ Parameters +
+  struct IHuks *self
+  Pointer to the HUKS HDI struct.
+  

+ const struct HuksBlob *encKey + Pointer to the key material (ciphertext) used to generate the MAC. +

+ const struct HuksParamSet *paramSet + Pointer to the parameters for generating the MAC. +

+ const struct HuksBlob *srcData + Pointre to the source data for which the MAC is to be generated. +

+ struct HuksBlob *mac + Pointer to the MAC generated. +
+
+

+ +
+ Return Value + + - **HKS_SUCCESS**: The operation is successful. + + - Other values: The operation fails. +
+ +- - - ### Development Procedure -The directory structure is as follows: +#### Directory Structure + +The code for HDI adaptation is in the following directory. + +```undefined +//drivers_peripheral/huks +├── BUILD.gn # Build script. +├── hdi_service # Dependency loaded from libhuks_engine_core_standard.z.so (software implementation of the HUKS Core for reference only) by using dlopen(). + ├── huks_sa_type.h # Defines the data structs used in the HUKS service layer. + ├── huks_sa_hdi_struct.h # Defines the function pointer structs in libhuks_engine_core_standard.z.so. + ├── huks_hdi_template.h # Defines the conversion between the data structs of the HUKS service layer and the HDI. + ├── huks_hdi_service.c # Implementation of the HUKS passthrough HDI APIs. + └── huks_hdi_passthrough_adapter.c # Adaptation of HUKS passthrough HDI APIs to the HUKS Core. +└── test # Test code for the HUKS HDI APIs. + ├── BUILD.gn # Build script. + ├── fuzztest # Fuzz test. + └── unittest # Unit test. +``` + +The code of the HUKS Core software implementation is in the following directory. ```undefined -// base/security/user_auth/services/huks_standard/huks_engine/main -├── BUILD.gn # Build script -├── core_dependency # Dependencies of the implementation -└── core # Software implementation of the HUKS Core - ├── BUILD.gn # Build script +//base/security/huks/services/huks_standard/huks_engine +├── BUILD.gn # Build script. +├── core_dependency # HUKS Core dependency. +└── core # Software implementation of the HUKS Core. + ├── BUILD.gn # Build script. ├── include └── src - ├── hks_core_interfaces.c # Adaptation of the HDI to the HUKS Core - └── hks_core_service.c # Specific implementation - └── ... # Other function code + ├── hks_core_interfaces.c # Adaptation of the HDI to the HUKS Core. + └── hks_core_service.c # HUKS Core implementation. + └── ... # Code of other functions. ``` +**CAUTION** + +The software implementation of the HUKS Core contains hard-coded sensitive data, including the root key, AuthToken key for access control, key used to encrypt AuthToken, and certificate. You need to replace these code with your own implementation. /summary> + + - Root key + + The root key is used to encrypt the HUKS service key and is generally derived from the device root key. It is hard-coded in the HUKS Core software implementation. For details, see hks_openssl_get_main_key.c. + + - Key for generating an HMAC on AuthToken + + The key is used to generate an HMAC on AuthToken by the UserIAM for access control. The value is **huks_default_user_auth_token_key** and hard-coded in the HUKS Core software implementation. For details about the code, see hks_keyblob.c. + + - Key for encrypting sensitive fields of AuthToken + + The key is used to encrypt sensitive fields of AuthToken in access control. The value is **huks_default_user_auth_token_key** and hard-coded in the HUKS Core software implementation. For details about the code, see hks_keyblob.c. + + - Root certificate, device CA, and device certificate + + The root certificate, device CA, and device certificate are used for key attestation and preset in the secure storage of the hardware device by the device certificate management module. These certificates are hard-coded in the HUKS Core software implementation. For details about the code, see dcm_certs_and_key.h. -Init-Update-Finish must be used to implement HUKS Core APIs. The following provides the development procedure of Init-Update-Finish and sample code of the HUKS Core. You can refer to the following code to implement all HDI APIs. +#### Example -For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com/openharmony/security_huks/blob/master/services/huks_standard/huks_engine/main/core/src/hks_core_service.c). +The following uses the adaptation of the key session APIs **Init**, **Update**, and **Finish** in the HUKS Core as an example. The sample code is for reference only and cannot be used directly. For details about the executable code, see [HUKS source code](https://gitee.com/openharmony/security_huks). -1. Create a handle to enable the information about the operations on a key to be stored in a session. With this handle, multiple operations on the same key can be performed. +1. Create a handle to identify information about key operations in a session. With this handle, multiple operations on the same key can be performed. ```c - // Implement Init(). + // Initialize the key session. - int32_t HksCoreInit(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *handle, - struct HksBlob *token) + int32_t HksCoreInit(const struct HuksBlob *key, const struct HuksParamSet *paramSet, struct HuksBlob *handle, + struct HuksBlob *token) { HKS_LOG_D("HksCoreInit in Core start"); uint32_t pur = 0; @@ -686,7 +1158,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com HKS_LOG_E("the pointer param entered is invalid"); return HKS_ERROR_BAD_STATE; } - // Store information in a session based on the handle. The information stored can be used for the Update and Finish operations on the key. + // Store information in a session based on the handle. The information stored can be used for the Update() and Finish() operations on the key. handle->size = sizeof(uint64_t); (void)memcpy_s(handle->data, handle->size, &(keyNode->handle), handle->size); // Obtain the algorithm from the parameters. @@ -695,14 +1167,14 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com HksDeleteKeyNode(keyNode->handle); return ret; } - // Check the key parameters. + // Check key parameters. ret = HksCoreSecureAccessInitParams(keyNode, paramSet, token); if (ret != HKS_SUCCESS) { HKS_LOG_E("init secure access params failed"); HksDeleteKeyNode(keyNode->handle); return ret; } - // Obtain the initialization handler from the algorithm library based on the usage of the key. + // Obtain the initialization handler from the algorithm library based on the key purpose. uint32_t i; uint32_t size = HKS_ARRAY_SIZE(g_hksCoreInitHandler); for (i = 0; i < size; i++) { @@ -730,12 +1202,12 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com } ``` -2. Obtain the context based on the handle, and pass in data by segment or append data to obtain the operation result. +2. Obtain the context based on the handle, and pass in data by segment to obtain the operation result or append data. ```c - // Implement Update(). - int32_t HksCoreUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, - struct HksBlob *outData) + // Update data by segment. + int32_t HksCoreUpdate(const struct HuksBlob *handle, const struct HuksParamSet *paramSet, const struct HuksBlob *inData, + struct HuksBlob *outData) { HKS_LOG_D("HksCoreUpdate in Core start"); uint32_t pur = 0; @@ -748,7 +1220,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com uint64_t sessionId; struct HuksKeyNode *keyNode = NULL; - // Obtain the context based on the handle. + // Obtain the context required for the key session operation based on the handle. int32_t ret = GetParamsForUpdateAndFinish(handle, &sessionId, &keyNode, &pur, &alg); if (ret != HKS_SUCCESS) { HKS_LOG_E("GetParamsForCoreUpdate failed"); @@ -766,7 +1238,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com uint32_t size = HKS_ARRAY_SIZE(g_hksCoreUpdateHandler); for (i = 0; i < size; i++) { if (g_hksCoreUpdateHandler[i].pur == pur) { - struct HksBlob appendInData = { 0, NULL }; + struct HuksBlob appendInData = { 0, NULL }; ret = HksCoreAppendAuthInfoBeforeUpdate(keyNode, pur, paramSet, inData, &appendInData); if (ret != HKS_SUCCESS) { HKS_LOG_E("before update: append auth info failed"); @@ -796,12 +1268,12 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com } ``` -3. Finalize the key operation to obtain the result, and destroy the handle. +3. Finish the key operation to obtain the result, and destroy the handle. ```c - // Implement Finish(). - int32_t HksCoreFinish(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, - struct HksBlob *outData) + // Finish the key session operation. + int32_t HksCoreFinish(const struct HuksBlob *handle, const struct HuksParamSet *paramSet, const struct HuksBlob *inData, + struct HuksBlob *outData) { HKS_LOG_D("HksCoreFinish in Core start"); uint32_t pur = 0; @@ -814,7 +1286,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com uint64_t sessionId; struct HuksKeyNode *keyNode = NULL; - // Obtain the context based on the handle. + // Obtain the context required for the key session operation based on the handle. int32_t ret = GetParamsForUpdateAndFinish(handle, &sessionId, &keyNode, &pur, &alg); if (ret != HKS_SUCCESS) { HKS_LOG_E("GetParamsForCoreUpdate failed"); @@ -833,7 +1305,7 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com for (i = 0; i < size; i++) { if (g_hksCoreFinishHandler[i].pur == pur) { uint32_t outDataBufferSize = (outData == NULL) ? 0 : outData->size; - struct HksBlob appendInData = { 0, NULL }; + struct HuksBlob appendInData = { 0, NULL }; ret = HksCoreAppendAuthInfoBeforeFinish(keyNode, pur, paramSet, inData, &appendInData); if (ret != HKS_SUCCESS) { HKS_LOG_E("before finish: append auth info failed"); @@ -863,15 +1335,15 @@ For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com } ``` -### Verification +### Debugging -Use the [HUKS JS APIs](https://gitee.com/openharmony/security_huks/blob/master/interfaces/kits/js/@ohos.security.huks.d.ts) to develop a JavaScript application to verify HUKS capabilities. +Use [HUKS JS APIs](https://gitee.com/openharmony/security_huks/blob/master/interfaces/kits/js/@ohos.security.huks.d.ts) to develop a JavaScript application to verify HUKS capabilities. -The JS API corresponding to each HDI API is provided in [Available APIs](#available-apis). You can invoke the JS APIs to verify the capabilities of the corresponding HDI APIs or perform complete key operations to verify the capabilities of the APIs. +The JS APIs corresponding to HDI APIs are provided in [Available APIs](#available-apis). You can use the JS APIs to verify the capabilities of the corresponding HDI APIs or perform complete key operations to verify the capabilities of the APIs. -The JS test code is as follows. If the entire process is successful, the HDI APIs are functioning. For more information about key operations, see [HUKS Development](../../application-dev/security/huks-guidelines.md). +The following JS test code is for reference only. If the entire process goes properly, the HDI APIs are functioning. For more key operation types and samples, see [huks-guidelines.md](../../application-dev/security/huks-guidelines.md). -**Generating and Encrypting an AES Key** +**Generating an AES Key and Encrypting Data** 1. Import the HUKS module. @@ -879,102 +1351,109 @@ The JS test code is as follows. If the entire process is successful, the HDI API import huks from '@ohos.security.huks' ``` -2. Call **generateKey()** to generate a key. +2. Use **generateKey()** to generate a key. ```js - var alias = 'testAlias'; - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE - }; - var options = { - properties: properties - } - var resultA = huks.generateKey(alias, options); - ``` + + let aesKeyAlias = 'test_aesKeyAlias'; + let handle; + let IV = '001122334455'; + let cipherData:Uint8Array; + let plainData:Uint8Array; -3. Call **Init()** to perform initialization. + + function GetAesGenerateProperties() { + var properties = new Array(); + var index = 0; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + } + return properties; + } - ```js - var alias = 'test001' - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_DH - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096 - }; - var options = { - properties: properties - }; - huks.init(alias, options, function(err, data) { - if (err.code !== 0) { - console.log("test init err information: " + JSON.stringify(err)); - } else { - console.log(`test init data: ${JSON.stringify(data)}`); - } - }) + + async function GenerateAesKey() { + var genProperties = GetAesGenerateProperties(); + var options = { + properties: genProperties + } + await huks.generateKeyItem(aesKeyAlias, options).then((data) => { + console.log("generateKeyItem success"); + }).catch((err)=>{ + console.log("generateKeyItem failed"); + }) + } ``` - -4. Call **update()** to perform the **Update** operation. - ```js - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_DH - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096 - }; - var options = { - properties: properties - }; - var result = huks.update(handle, options) - ``` - -5. Call **finish()** to finalize the operation. +3. Use **huks.initSession** and **huks.finishSession** to encrypt data. ```js - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_DH - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096 - }; - var options = { - properties: properties - }; - var result = huks.finish(handle, options) + let plainText = '123456'; + + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } + + function GetAesEncryptProperties() { + var properties = new Array(); + var index = 0; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 + }; + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + } + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS7 + } + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC + } + properties[index++] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV) + } + return properties; + } + + async function EncryptData() { + var encryptProperties = GetAesEncryptProperties(); + var options = { + properties:encryptProperties, + inData: StringToUint8Array(plainText) + } + await huks.initSession(aesKeyAlias, options).then((data) => { + handle = data.handle; + }).catch((err)=>{ + console.log("initSession failed"); + }) + await huks.finishSession(handle, options).then((data) => { + console.log("finishSession success"); + cipherData = data.outData + }).catch((err)=>{ + console.log("finishSession failed"); + }) + } ``` diff --git a/en/device-dev/website.md b/en/device-dev/website.md index 6aad5f8a458451105fb5bfbb7657d35856304e58..3f979d4879c640e0e363ae7c3b3acea7914f2f8d 100644 --- a/en/device-dev/website.md +++ b/en/device-dev/website.md @@ -388,15 +388,22 @@ - [Configuring Parameters for Accelerating Local Build](subsystems/subsys-build-reference.md) - [Viewing Ninja Build Information](subsystems/subsys-build-reference.md) - [HAP Build Guide](subsystems/subsys-build-gn-hap-compilation-guide.md) + - Rust Compilation and Building + - [Rust Module Configuration Rules and Guide](subsystems/subsys-build-rust-compilation.md) + - [Interactive Tool User Guide](subsystems/subsys-build-bindgen-cxx-guide.md) + - [Using Cargo2gn](subsystems/subsys-build-cargo2gn-guide.md) - [FAQs](subsystems/subsys-build-FAQ.md) - [ArkCompiler Development](subsystems/subsys-arkcompiler-guide.md) - - [Distributed Remote Startup](subsystems/subsys-remote-start.md) + - ArkUI + - [Custom Window Title Bar Development](subsystems/subsys-arkui-customize_titlebar.md) - Graphics - [Graphics Overview](subsystems/subsys-graphics-overview.md) + - [Common Component Development](subsystems/subsys-graphics-common-guide.md) - [Container Component Development](subsystems/subsys-graphics-container-guide.md) - [Development of Layout Container Components](subsystems/subsys-graphics-layout-guide.md) - - [Common Component Development](subsystems/subsys-graphics-common-guide.md) - [Animator Development](subsystems/subsys-graphics-animation-guide.md) + - [Using Qt Creator on Windows](subsystems/subsys-graphics-simulator-guide.md) + - [Small-System Graphics Framework Integration](subsystems/subsys-graphics-porting-guide.md) - Multimedia - Camera - [Camera Overview](subsystems/subsys-multimedia-camera-overview.md) @@ -532,6 +539,7 @@ - Debugging - [Development Self-Test Framework User Guide](device-test/developer_test.md) - [xDevice User Guide](device-test/xdevice.md) + - [Smartperf-Host User Guide](device-test/smartperf-host.md) - R&D Tools - [bytrace](subsystems/subsys-toolchain-bytrace-guide.md) - [hdc](subsystems/subsys-toolchain-hdc-guide.md) diff --git a/en/release-notes/OpenHarmony-v3.2-release.md b/en/release-notes/OpenHarmony-v3.2-release.md index fed75e671895a0b6f6efc8d3f44465c44443efb3..f36be4f1d81c756222f7700096f8a5b1051d8263 100644 --- a/en/release-notes/OpenHarmony-v3.2-release.md +++ b/en/release-notes/OpenHarmony-v3.2-release.md @@ -125,7 +125,7 @@ Abilities and widgets can be queried, added, refreshed, and deleted across devic - The distributed camera supports video recording. -- Users can import account authentication information to the device security authentication system. Devices with the same login account can automatically complete authentication and networking. +- Users can use the device management native APIs to import account authentication information to the device security authentication system. Devices with the same login account can automatically complete authentication and networking. #### Distributed data management diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkui.md b/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..b155f52a104a047255cf904c09478e51b4169a84 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkui.md @@ -0,0 +1,21 @@ +# ArkUI Subsystem Changelog + +## cl.arkui.1 Change of Certain Predicates of uiAppearance from Public APIs to System APIs + +Changed the namespace **uiAppearance** and its internal **DarkMode** enum predicates from public APIs to system APIs. + +**Change Impact** + +None. The namespace **uiAppearance** and its internal **DarkMode** enum are used only by system APIs before and after the change. + +**Key API/Component Changes** + +The system API description is added to the following APIs: + +- declare namespace uiAppearance + +- enum DarkMode + +- ALWAYS_DARK = 0 + +- ALWAYS_LIGHT = 1 diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md b/en/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md index 85f6aebf03beb604a61c7be18c293507b8415eab..089253f0e410425b26d4b7c99b15c933957e5440 100644 --- a/en/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md +++ b/en/release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-arkui.md @@ -97,3 +97,117 @@ N/A When building a child component, do not assign values to the variables by **@LocalStorageLink** and **@LocalStorageProp** in the child component. To change these variables from the parent component, use the API provided by the **LocalStorage** (such as the **set** API) to assign values to them. + +## cl.arkui.3 Change of the bottom Definition in Toast Options in the PromptAction Module + +Changed the definition of the **bottom** attribute in toast options from distance between the top of the toast and the bottom of the screen to distance between the bottom of the toast and the bottom of the screen. + +**Example** + +```ts +import promptAction from '@ohos.promptAction'; +@Entry +@Component +struct Index { + build() { + Row() { + Button() + .onClick(() => { + try { + promptAction.showToast({ + message: 'Message Info', + duration: 2000 + }); + } catch (error) { + console.error(`showToast args error code is ${error.code}, message is ${error.message}`); + }; + }) + } + } +} +``` + +**Change Impacts** + +In the **PromptAction** module, the same value for the **bottom** attribute may result in different toast appearances, depending on whether the API version used by the compiler is earlier than 10 or not. + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +When setting the **bottom** attribute, account for the definition change. + +## cl.arkui.4 Content Layout Change of AlertDialog + +The content layout of the alert dialog box varies according to the following conditions: 1. whether there is a title. 2. whether the text is on a single line. + +Currently, only the single-line text without a title is centered. In other cases, the text is left-aligned. + +**Example** + +```ts +// xxx.ets +@Entry +@Component +struct AlertDialogExample { + build() { + Column({ space: 5 }) { + Button('one button dialog') + .onClick(() => { + AlertDialog.show( + { + title: 'title', + message: 'text'.repeat(20), + autoCancel: true, + alignment: DialogAlignment.Bottom, + offset: { dx: 0, dy: -20 }, + gridCount: 3, + confirm: { + value: 'button', + action: () => { + console.info('Button-clicking callback') + } + }, + cancel: () => { + console.info('Closed callbacks') + } + } + ) + }) + .backgroundColor(0x317aff) + }.width('100%').margin({ top: 5 }) + } +} +``` + +**Change Impacts** + +The layout for the text specified by the **message** attribute of the alert dialog box is subject to the title and number of lines of the text. + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +No proactive adaptation is required. You can also use **customDialog** for related implementation. + +## cl.arkui.5 Avoidance Behavior Optimization of Popup + +Before the change, the popup preferentially uses the lower area for avoidance. As a result, it cannot be displayed in the upper area even if the space is sufficient. + +After the change: The popup preferentially uses the upper area for avoidance when it is configured to show above the target component; it preferentially uses the upper or lower area for avoidance when it is configured to show below the target component. + +**Change Impacts** + +The optimized popup avoidance behavior occurs when the **bindpopup** attribute is used. + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +If the popup position is not as expected, you can adjust the **placement** settings. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.9.1/changelogs-accessToken.md b/en/release-notes/changelogs/OpenHarmony_4.0.9.1/changelogs-accessToken.md index 0706c71bb7683308cd657f170b197a1d36b346cf..00fd9772a0edcf712b71caedb84507089a7fa913 100644 --- a/en/release-notes/changelogs/OpenHarmony_4.0.9.1/changelogs-accessToken.md +++ b/en/release-notes/changelogs/OpenHarmony_4.0.9.1/changelogs-accessToken.md @@ -1,43 +1,71 @@ -# App Access Control Subsystem ChangeLog +# Application Access Control Subsystem Changelog -## cl.accessToken.1 Change of the Media and File Permission Group +## cl.accessToken.1 Change of the Media and Files Permission Group The original Media and File permission group contains the following permissions: - ohos.permission.MEDIA_LOCATION - ohos.permission.READ_MEDIA - ohos.permission.WRITE_MEDIA Changed the permission group as follows: -- Added **ohos.permission.MEDIA_LOCATION** to the Image and Video permission group. -- Added **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** to the File permission group. +- Added **ohos.permission.MEDIA_LOCATION** to the Images and Video permission group. +- Added **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** to the Documents permission group. **Change Impact** -The permission dialog boxes are displayed by permission group. +The dialog box for requesting permissions is displayed by permission group. -- Before the change, if the three permissions are applied for an application, a dialog box for applying for the media and file permissions will be displayed only once. -- After the change, if the three permissions are applied for an application, a dialog box for applying for the image and video permissions and a dialog box for applying for the file permission will be displayed. +- Before the change, if the three permissions are applied for an application, a dialog box for requesting the media and file permissions will be displayed only once. +- After the change, if the three permissions are applied for an application, a dialog box for requesting the image and video permissions and a dialog box for requesting the document permission will be displayed. **Key API/Component Changes** -Permission group before the change: +Permission groups before the change: | Permission | Permission Group | | -------- | ---------------------------- | -| ohos.permission.MEDIA_LOCATION | Media and File| -| ohos.permission.READ_MEDIA | Media and File| -| ohos.permission.WRITE_MEDIA | Media and File| +| ohos.permission.MEDIA_LOCATION | Media and file| +| ohos.permission.READ_MEDIA | Media and file| +| ohos.permission.WRITE_MEDIA | Media and file| Permission groups after the change: | Permission | Permission Group | | -------- | ---------------------------- | -| ohos.permission.MEDIA_LOCATION | Image and Video| -| ohos.permission.READ_MEDIA | File| -| ohos.permission.WRITE_MEDIA | File| +| ohos.permission.MEDIA_LOCATION | Images and videos | +| ohos.permission.READ_MEDIA | Documents | +| ohos.permission.WRITE_MEDIA | Documents | **Adaptation Guide** N/A +## cl.accessToken.2 Change of the Permission Requesting Modes of the Telephony, Messaging, and Call Logs Permission Groups +The permissions of the Telephony, Messaging, and Call Logs permission groups are available only to system applications. The three permission groups contain the following permissions: +- ohos.permission.ANSWER_CALL +- ohos.permission.MANAGE_VOICEMAIL +- ohos.permission.READ_CELL_MESSAGES +- ohos.permission.READ_MESSAGES +- ohos.permission.RECEIVE_MMS +- ohos.permission.RECEIVE_SMS +- ohos.permission.RECEIVE_WAP_MESSAGES +- ohos.permission.SEND_MESSAGES +- ohos.permission.READ_CALL_LOG +- ohos.permission.WRITE_CALL_LOG +- ohos.permission.MEDIA_LOCATION + +To enable third-party application developers to apply for these permissions, the method for requesting these permissions is changed to pre-authorization mode. + + +**Change Impact** + +The system applications can obtain these permissions only in pre-authorization mode, rather than requesting these permissions through a pop-up window, . + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +Apply for the preceding permissions in pre-authorization mode for system applications. diff --git a/zh-cn/application-dev/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index f2f89c45fe75c039447ce53593ccaa98b0c51dcd..8d124c2f0e91c74864a6af12879818269fc59e75 100644 --- a/zh-cn/application-dev/IDL/idl-guidelines.md +++ b/zh-cn/application-dev/IDL/idl-guidelines.md @@ -343,11 +343,10 @@ export default { #### 客户端调用IPC方法 -客户端调用connectAbility()以连接服务时,客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例。由于客户端和服务在不同应用内,所以客户端应用的目录内必须包含.idl文件(SDK工具会自动生成Proxy代理类)的副本。客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例,使用IRemoteObject创建IdlTestServiceProxy类的实例对象testProxy,然后调用相关IPC方法。示例代码如下: +客户端调用connectServiceExtensionAbility()以连接服务时,客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例。由于客户端和服务在不同应用内,所以客户端应用的目录内必须包含.idl文件(SDK工具会自动生成Proxy代理类)的副本。客户端的onAbilityConnectDone中的onConnect回调会接收服务的onConnect()方法返回的IRemoteObject实例,使用IRemoteObject创建IdlTestServiceProxy类的实例对象testProxy,然后调用相关IPC方法。示例代码如下: ```ts import IdlTestServiceProxy from './idl_test_service_proxy' -import featureAbility from '@ohos.ability.featureAbility'; function callbackTestIntTransaction(result: number, ret: number): void { if (result == 0 && ret == 124) { @@ -392,13 +391,13 @@ var onAbilityConnectDone = { } }; -function connectAbility: void { +function connectAbility(): void { let want = { bundleName: 'com.example.myapplicationidl', abilityName: 'com.example.myapplicationidl.ServiceAbility' }; let connectionId = -1; - connectionId = featureAbility.connectAbility(want, onAbilityConnectDone); + connectionId = this.context.connectServiceExtensionAbility(want, onAbilityConnectDone); } diff --git a/zh-cn/application-dev/application-dev-guide.md b/zh-cn/application-dev/application-dev-guide.md index 40b528f30b0dcbd37c5eb314bde88622ae283b42..7bf78e9180a883b5839126646023e7695f41d70c 100644 --- a/zh-cn/application-dev/application-dev-guide.md +++ b/zh-cn/application-dev/application-dev-guide.md @@ -32,7 +32,7 @@ - [WebGL](webgl/webgl-overview.md) - [媒体](media/media-application-overview.md) - [安全](security/userauth-overview.md) -- [AI](ai/mindspore-lite-js-guidelines.md) +- [AI](ai/ai-overview.md) - [网络与连接](connectivity/ipc-rpc-overview.md) - [电话服务](telephony/telephony-overview.md) - [数据管理](database/data-mgmt-overview.md) diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-creation.md b/zh-cn/application-dev/application-models/arkts-ui-widget-creation.md index 71c48410fea0aee1420ae1dab44b9dfa81ff1e63..248c23ea425fb67ad814d1402d100d799d0c5a34 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-creation.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-creation.md @@ -1,16 +1,23 @@ # 创建一个ArkTS卡片 -在已有的应用工程中,创建ArkTS卡片,具体的操作方式如下。 +创建卡片当前有两种入口: -1. 创建卡片。 +- 创建工程时,选择Application,默认不带卡片,可以在创建工程后右键新建卡片。 +- 创建工程时,选择Atomic Service,默认自带卡片,也可以在创建工程后右键新建卡片。 + +![WidgetCreateProject](figures/WidgetCreateProject.png) + +在已有的应用工程中,可以通过右键新建ArkTS卡片,具体的操作方式如下。 + +1. 右键新建卡片。 ![WidgetProjectCreate1](figures/WidgetProjectCreate1.png) 2. 根据实际业务场景,选择一个卡片模板。 ![WidgetProjectCreate2](figures/WidgetProjectCreate2.png) - + 3. 在选择卡片的开发语言类型(Language)时,选择ArkTS选项,然后单击“Finish”,即可完成ArkTS卡片创建。 ![WidgetProjectCreate3](figures/WidgetProjectCreate3.png) - + ArkTS卡片创建完成后,工程中会新增如下卡片相关文件:卡片生命周期管理文件(EntryFormAbility.ets)、卡片页面文件(WidgetCard.ets)和卡片配置文件(form_config.json)。 ![WidgetProjectView](figures/WidgetProjectView.png) diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md index dd1c84a41983ed354da06789357626beb1d3126a..776b129a1fabf15885e43d19f5949878acf9be02 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md @@ -11,12 +11,19 @@ @Entry(storage) @Component struct WidgetCard { - @LocalStorageProp('title') title: string = 'init'; - @LocalStorageProp('detail') detail: string = 'init'; + @LocalStorageProp('title') title: string = 'Title default'; + @LocalStorageProp('detail') detail: string = 'Description default'; build() { Column() { - Button('刷新') + Column() { + Text(`${this.title}`) + .margin(5).fontWeight(FontWeight.Medium).fontSize('14fp') + Text(`${this.detail}`) + .margin(5).fontColor(Color.Gray).fontSize('12fp').height('25%') + }.width('100%').alignItems(HorizontalAlign.Start) + Button('UPDATE') + .margin(15).width('90%') .onClick(() => { postCardAction(this, { 'action': 'message', @@ -25,11 +32,7 @@ } }); }) - Text(`${this.title}`) - Text(`${this.detail}`) - } - .width('100%') - .height('100%') + }.width('90%').height('90%').margin('5%') } } ``` @@ -46,8 +49,8 @@ // Called when a specified message event defined by the form provider is triggered. console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); let formData = { - 'title': 'Title Update Success.', // 和卡片布局中对应 - 'detail': 'Detail Update Success.', // 和卡片布局中对应 + 'title': 'Title Update.', // 和卡片布局中对应 + 'detail': 'Description update success.', // 和卡片布局中对应 }; let formInfo = formBindingData.createFormBindingData(formData) formProvider.updateForm(formId, formInfo).then((data) => { @@ -61,5 +64,8 @@ } ``` - 运行效果如下图所示。 - ![WidgetUpdatePage](figures/WidgetUpdatePage.png) + 运行效果如下图所示。 + + | 初始状态 | 点击刷新 | + | ------------------------------------------------------- | ----------------------------------------------------- | + | ![WidgetUpdateBefore](figures/widget-update-before.PNG) | ![WidgetUpdateAfter](figures/widget-update-after.PNG) | diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md index f32017a7ed10f405f292bd6ad26139df5613d189..e54036d3971d65b2a12cf45baec3640f079e6337 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md @@ -1,7 +1,7 @@ # 使用router事件跳转到指定UIAbility - 在卡片中使用**postCardAction**接口的router能力,能够快速拉起卡片提供方应用的指定UIAbility,因此UIAbility较多的应用往往会通过卡片提供不同的跳转按钮,实现一键直达的效果。例如相机卡片,卡片上提供拍照、录像等按钮,点击不同按钮将拉起相机应用的不同UIAbility,从而提高用户的体验。 + ![WidgerCameraCard](figures/WidgerCameraCard.png) diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-modules.md b/zh-cn/application-dev/application-models/arkts-ui-widget-modules.md index fffa5ca955827d9a76caa12c79bf74c095268bd1..219bdf5e85bb32edb9969c0f91ea464a0616c3ad 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-modules.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-modules.md @@ -15,7 +15,7 @@ - [formBindingData](../reference/apis/js-apis-app-form-formBindingData.md):提供卡片数据绑定的能力,包括FormBindingData对象的创建、相关信息的描述。 -- [页面布局(Card.ets)](arkts-ui-widget-page-overview.md):提供声明式范式的UI接口能力。 +- [页面布局(WidgetCard.ets)](arkts-ui-widget-page-overview.md):提供声明式范式的UI接口能力。 - [ArkTS卡片特有能力](arkts-ui-widget-event-overview.md):postCardAction用于卡片内部和提供方应用间的交互,仅在卡片中可以调用。 - [ArkTS卡片能力列表](arkts-ui-widget-page-overview.md#arkts卡片支持的页面能力):列举了能在ArkTS卡片中使用的API、组件、事件、属性和生命周期调度。 diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index 12030b09d65dda9f8bcc970cd9d6aed8827cb3f9..1630e686e1cddd466e859c66e9f17e720744df8f 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -32,7 +32,7 @@ 1. 数据提供方以`key + subscriberId`作为数据的标识,将数据存储到数据库。 2. 数据管理服务感知到数据库变化,将新的数据发布给当前注册的所有订阅实例。 3. 卡片管理服务从订阅实例中解析出数据,发送给卡片渲染服务。 -4. 卡片渲染服务运行卡片页面代码widgets.abc,widgets.abc按新数据进行渲染,并将渲染后的数据发送至卡片使用方对应的[卡片组件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md)。 +4. 卡片渲染服务运行卡片页面代码widgets.abc,widgets.abc按新数据进行渲染,并将渲染后的数据发送至卡片使用方对应的[卡片组件](../reference/arkui-ts/ts-basic-components-formcomponent.md)。 数据提供方提供的共享数据有两种类型: diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md b/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md index e40413e81bc389fd857b19081dc3b7bdd17159de..7585bbc02e566a5747acb8ba75acab6f8e224929 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md @@ -26,7 +26,7 @@ - 统一开发范式,提升开发体验和开发效率。 - OpenHarmony在2022年发布了声明式范式的UI开发框架,而卡片还延续了css/hml/json三段式类Web范式的开发方式,提高了开发者的学习成本,提供ArkTS卡片能力后,统一了卡片和页面的开发范式,页面的布局可以直接复用到卡片布局中,提升开发体验和开发效率。 + 提供ArkTS卡片能力后,统一了卡片和页面的开发范式,页面的布局可以直接复用到卡片布局中,提升开发体验和开发效率。 **图3** 卡片工程结构对比 ![WidgetProject](figures/WidgetProject.png) diff --git a/zh-cn/application-dev/application-models/context-switch.md b/zh-cn/application-dev/application-models/context-switch.md index d6128dfadc468b2d1b011d8a3a6881979812691e..7afa990d780227c94149610baed51abd09953e86 100644 --- a/zh-cn/application-dev/application-models/context-switch.md +++ b/zh-cn/application-dev/application-models/context-switch.md @@ -10,7 +10,7 @@ | [getBundleName(callback : AsyncCallback<string>): void;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7)
[getBundleName(): Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7-1) | application\UIAbilityContext.d.ts | [abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#属性) | | [getDisplayOrientation(callback : AsyncCallback<bundle.DisplayOrientation>): void;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7)
[getDisplayOrientation(): Promise<bundle.DisplayOrientation>;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7-1) | \@ohos.screen.d.ts | [readonly orientation: Orientation;](../reference/apis/js-apis-screen.md#orientation) | | [setDisplayOrientation(orientation:bundle.DisplayOrientation, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7)
[setDisplayOrientation(orientation:bundle.DisplayOrientation):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7-1) | \@ohos.screen.d.ts | [setOrientation(orientation: Orientation, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-screen.md#setorientation)
[setOrientation(orientation: Orientation): Promise<void>;](../reference/apis/js-apis-screen.md#setorientation-1) | -| [setShowOnLockScreen(show:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreen7)
[setShowOnLockScreen(show:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreen7-1) | \@ohos.window.d.ts | [setShowOnLockScreen(showOnLockScreen: boolean): void;](../reference/apis/js-apis-window.md#setshowonlockscreen9) | +| [setShowOnLockScreen(show:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreendeprecated)
[setShowOnLockScreen(show:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreendeprecated-1) | \@ohos.window.d.ts | [setShowOnLockScreen(showOnLockScreen: boolean): void;](../reference/apis/js-apis-window.md#setshowonlockscreen9) | | [setWakeUpScreen(wakeUp:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetwakeupscreen7)
[setWakeUpScreen(wakeUp:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetwakeupscreen7-1) | \@ohos.window.d.ts | [setWakeUpScreen(wakeUp: boolean): void;](../reference/apis/js-apis-window.md#setwakeupscreen9) | | [getProcessInfo(callback:AsyncCallback<ProcessInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessinfo7)
[getProcessInfo():Promise<ProcessInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessinfo7-1) | \@ohos.app.ability.abilityManager.d.ts | [getAbilityRunningInfos(callback: AsyncCallback<Array<AbilityRunningInfo>>): void;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos)
[getAbilityRunningInfos(): Promise<Array<AbilityRunningInfo>>;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos-1) | | [getElementName(callback:AsyncCallback<ElementName>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetelementname7)
[getElementName():Promise<ElementName>;](../reference/apis/js-apis-inner-app-context.md#contextgetelementname7-1) | application\UIAbilityContext.d.ts | [abilityInfo.name: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#属性)
[abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#属性) | diff --git a/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md b/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md index 31e35a31aeabed1da53d70e0ba58fb38990e1175..fc285a97f12eef0c1b677a5ddfe98b7692bd47e1 100644 --- a/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md @@ -18,7 +18,7 @@ | action | string | 否 | 否 | 系统匹配时将忽略该参数,但仍可作为参数传递给目标应用组件。 | | entities | Array<string> | 否 | 否 | 系统匹配时将忽略该参数,但仍可作为参数传递给目标应用组件。 | | flags | number | 否 | 否 | 不参与匹配,直接传递给系统处理,一般用来设置运行态信息,例如URI数据授权等。 | -| parameters | {[key: string]: any} | 否 | 否 | 不参与匹配,应用自定义数据将直接传递给目标应用组件。 | +| parameters | {[key: string]: Object} | 否 | 否 | 不参与匹配,应用自定义数据将直接传递给目标应用组件。 | ## 隐式Want匹配原理 @@ -35,7 +35,7 @@ | action | string | 是 | 否 | | | entities | Array<string> | 是 | 否 | | | flags | number | 否 | 否 | 不参与匹配,直接传递给系统处理,一般用来设置运行态信息,例如URI数据授权等。 | -| parameters | {[key: string]: any} | 否 | 否 | 不参与匹配,应用自定义数据将直接传递给目标应用组件。 | +| parameters | {[key: string]: Object} | 否 | 否 | 不参与匹配,应用自定义数据将直接传递给目标应用组件。 | 从隐式Want的定义,可得知: diff --git a/zh-cn/application-dev/application-models/figures/WidgetCreateProject.png b/zh-cn/application-dev/application-models/figures/WidgetCreateProject.png new file mode 100644 index 0000000000000000000000000000000000000000..2372e68a25c116ace77374eba86a8ea7a0680988 Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/WidgetCreateProject.png differ diff --git a/zh-cn/application-dev/application-models/figures/WidgetModules.png b/zh-cn/application-dev/application-models/figures/WidgetModules.png index e9a91b92b7ff81b5ab8a014aeeb779eb0653f25a..970a4a93159f697e505efbfa6fc7563b0d3c822a 100644 Binary files a/zh-cn/application-dev/application-models/figures/WidgetModules.png and b/zh-cn/application-dev/application-models/figures/WidgetModules.png differ diff --git a/zh-cn/application-dev/application-models/figures/WidgetProjectView.png b/zh-cn/application-dev/application-models/figures/WidgetProjectView.png index 9d1c06e47502131983b0b7cd56e66269b5be6d88..a1c8b42becc089b6b69f58c362569faeaf84f06f 100644 Binary files a/zh-cn/application-dev/application-models/figures/WidgetProjectView.png and b/zh-cn/application-dev/application-models/figures/WidgetProjectView.png differ diff --git a/zh-cn/application-dev/application-models/figures/WidgetUpdatePage.png b/zh-cn/application-dev/application-models/figures/WidgetUpdatePage.png deleted file mode 100644 index 24ba6ae125dac0acf426e61d6a9dd71630f55294..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/application-models/figures/WidgetUpdatePage.png and /dev/null differ diff --git a/zh-cn/application-dev/application-models/figures/widget-update-after.PNG b/zh-cn/application-dev/application-models/figures/widget-update-after.PNG new file mode 100644 index 0000000000000000000000000000000000000000..fddb9f651685332324af9a4d065c29638a58c0ba Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/widget-update-after.PNG differ diff --git a/zh-cn/application-dev/application-models/figures/widget-update-before.PNG b/zh-cn/application-dev/application-models/figures/widget-update-before.PNG new file mode 100644 index 0000000000000000000000000000000000000000..6355f1b66707af8073a2e1dea7f05e839f3a9818 Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/widget-update-before.PNG differ diff --git a/zh-cn/application-dev/application-models/hop-cross-device-migration.md b/zh-cn/application-dev/application-models/hop-cross-device-migration.md index f8e215e21f9661168291de9d3222ef2aada3aa91..855da0ff4beb9feda0e159841923800a5a274645 100644 --- a/zh-cn/application-dev/application-models/hop-cross-device-migration.md +++ b/zh-cn/application-dev/application-models/hop-cross-device-migration.md @@ -46,7 +46,7 @@ | **接口名** | **描述** | | -------- | -------- | -| onContinue(wantParam : {[key: string]: any}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常可以直接REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移接收端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 | +| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常可以直接REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移接收端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 | | onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | 应用迁移接收端为冷启动或多实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | | onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | 迁移接收端为单实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | diff --git a/zh-cn/application-dev/application-models/js-ui-widget-development.md b/zh-cn/application-dev/application-models/js-ui-widget-development.md index 85be9e3325327ce6ae69da98e88a909c167757be..24a6abb2d41705f9b7c76141f79f5ad2c1d0c2fb 100644 --- a/zh-cn/application-dev/application-models/js-ui-widget-development.md +++ b/zh-cn/application-dev/application-models/js-ui-widget-development.md @@ -55,7 +55,7 @@ FormExtensionAbility类拥有如下API接口,具体的API介绍详见[接口 | onFormEvent(formId: string, message: string): void | 卡片提供方接收处理卡片事件的通知接口。 | | onRemoveForm(formId: string): void | 卡片提供方接收销毁卡片的通知接口。 | | onConfigurationUpdate(config: Configuration): void | 当系统配置更新时调用。 | -| onShareForm?(formId: string): { [key: string]: any } | 卡片提供方接收卡片分享的通知接口。 | +| onShareForm?(formId: string): { [key: string]: Object } | 卡片提供方接收卡片分享的通知接口。 | formProvider类有如下API接口,具体的API介绍详见[接口文档](../reference/apis/js-apis-app-form-formProvider.md)。 diff --git a/zh-cn/application-dev/application-models/lifecycleapp-switch.md b/zh-cn/application-dev/application-models/lifecycleapp-switch.md index d1d37d01d3f44ed1c86ccb53a461ac20bfafed32..55eb8d71971f8cc80ef26719257e8db4f761c172 100644 --- a/zh-cn/application-dev/application-models/lifecycleapp-switch.md +++ b/zh-cn/application-dev/application-models/lifecycleapp-switch.md @@ -9,11 +9,11 @@ | onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) | | onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | Stage模型无对应接口 | 暂时未提供对应接口 | | onStartContinuation?(): boolean; | Stage模型无对应接口 | Stage模型上,应用无需感知迁移是否成功(由应用发起迁移请求时感知),onStartContinuation废弃 | -| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) | +| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: Object}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) | | onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | | onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)
多实例模式Ability迁移目标端在onCreate回调中完成数据恢复,单实例模式应用迁移目标端在onCreate回调中完成数据恢复,回调中通过判断launchParam.launchReason可获取迁移启动的场景,从而可以从Want中获取迁移前保存的数据 | | onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | -| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) | +| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) | | onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
应用重启后会触发Ability的onCreate方法,通过判断launchParam.launchReason可获取自恢复的场景,从而可以从Want中获取重启前保存的数据 | | onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) | | onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) | diff --git a/zh-cn/application-dev/application-models/lifecycleform-switch.md b/zh-cn/application-dev/application-models/lifecycleform-switch.md index fbe5ac639ba698dd5ec967a2f1983b8e9f2da32f..7b0414b44e6ea43cdd9891f31b83aae1d48120b2 100644 --- a/zh-cn/application-dev/application-models/lifecycleform-switch.md +++ b/zh-cn/application-dev/application-models/lifecycleform-switch.md @@ -10,4 +10,4 @@ | onEvent?(formId: string, message: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onFormEvent(formId: string, message: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) | | onDestroy?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onRemoveForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform) | | onAcquireFormState?(want: Want): formInfo.FormState; | \@ohos.app.form.FormExtensionAbility.d.ts | [onAcquireFormState?(want: Want): formInfo.FormState;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onacquireformstate) | -| onShare?(formId: string): {[key: string]: any}; | \@ohos.app.form.FormExtensionAbility.d.ts | [onShareForm?(formId: string): { [key: string]: any };](../reference/apis/js-apis-app-form-formExtensionAbility.md#onshareform) | +| onShare?(formId: string): {[key: string]: Object}; | \@ohos.app.form.FormExtensionAbility.d.ts | [onShareForm?(formId: string): { [key: string]: Object };](../reference/apis/js-apis-app-form-formExtensionAbility.md#onshareform) | diff --git a/zh-cn/application-dev/application-models/particleability-switch.md b/zh-cn/application-dev/application-models/particleability-switch.md index 8e85eb0d1789e958433d9cdfc50643dfc988dc1c..60f54af98a2109502b9eaf90377719b8bd8e7bbe 100644 --- a/zh-cn/application-dev/application-models/particleability-switch.md +++ b/zh-cn/application-dev/application-models/particleability-switch.md @@ -8,5 +8,5 @@ | [connectAbility(request: Want, options:ConnectOptions ): number;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityconnectability) | application\ServiceExtensionContext.d.ts | [connectAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability)
[connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability) | | [disconnectAbility(connection: number, callback:AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitydisconnectability)
[disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitydisconnectability-1) | application\ServiceExtensionContext.d.ts | [disconnectAbility(connection: number, callback:AsyncCallback<void>): void; ](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability)
[disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1)
[disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability)
[disconnectServiceExtensionAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1) | | [acquireDataAbilityHelper(uri: string): DataAbilityHelper;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityacquiredataabilityhelper) | \@ohos.data.dataShare.d.ts
[\@ohos.data.fileAccess.d.ts | [createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper)
[createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper>;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper-1)
[createFileAccessHelper(context: Context): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper-1)
[createFileAccessHelper(context: Context, wants: Array<Want>): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper) | -| [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning)
[startBackgroundRunning(id: number, request: NotificationRequest): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningcallback)
[startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningpromise) | -| [cancelBackgroundRunning(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning)
[cancelBackgroundRunning(): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningcallback)
[stopBackgroundRunning(context: Context): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningpromise) | +| [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning)
[startBackgroundRunning(id: number, request: NotificationRequest): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning)
[startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning-1) | +| [cancelBackgroundRunning(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning)
[cancelBackgroundRunning(): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning)
[stopBackgroundRunning(context: Context): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning-1) | diff --git a/zh-cn/application-dev/arkts-utils/xml-conversion.md b/zh-cn/application-dev/arkts-utils/xml-conversion.md index dfaa9db3f6d5ad6c53a06c400fbb3acd1a3e6a23..a47c733357337a7d2d52714df8d8c2bf160fa186 100644 --- a/zh-cn/application-dev/arkts-utils/xml-conversion.md +++ b/zh-cn/application-dev/arkts-utils/xml-conversion.md @@ -4,7 +4,7 @@ 将XML文本转换为JavaScript对象可以更轻松地处理和操作数据,并且更适合在JavaScript应用程序中使用。 -语言基础类库提供ConvertXML类将xml文本转换为JavaScript对象,输入为待转换的XML字符串及转换选项,输出为转换后的JavaScript对象。具体转换选项可见[API参考@ohos.convertxml](../reference/apis/js-apis-convertxml.md)。 +语言基础类库提供ConvertXML类将XML文本转换为JavaScript对象,输入为待转换的XML字符串及转换选项,输出为转换后的JavaScript对象。具体转换选项可见[API参考@ohos.convertxml](../reference/apis/js-apis-convertxml.md)。 ## 注意事项 diff --git a/zh-cn/application-dev/dfx/cppcrash-guidelines.md b/zh-cn/application-dev/dfx/cppcrash-guidelines.md index 33e34e3c0caee52f25231bf3e3aeeae40425686d..e4a18bdd91431ded5f42e4ca753e64ba1556b8ee 100644 --- a/zh-cn/application-dev/dfx/cppcrash-guidelines.md +++ b/zh-cn/application-dev/dfx/cppcrash-guidelines.md @@ -96,8 +96,10 @@ Thread name:crasher <- 异常线程名 使用addr2line工具根据偏移地址解析行号: + [product name]为具体设备名。 + ``` - root:~/OpenHarmony/out/rk3568/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c + root:~/OpenHarmony/out/[product name]/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c base/hiviewdfx/faultloggerd/tools/crasher/dfx_crasher.c:57 ``` diff --git a/zh-cn/application-dev/faqs/Readme-CN.md b/zh-cn/application-dev/faqs/Readme-CN.md index 5124f23cbedb7a8d44e567c070e24ba936a351a4..aaea1d7dcd0db10cf4ede3d40a8d2302bb76ec57 100644 --- a/zh-cn/application-dev/faqs/Readme-CN.md +++ b/zh-cn/application-dev/faqs/Readme-CN.md @@ -2,7 +2,7 @@ - [如何编译full-SDK](full-sdk-compile-guide.md) - [如何替换full-SDK](full-sdk-switch-guide.md) -- [如何在CMake工程中使用OpenHarmony SDK的Native API(NDK)](howto-migrate-cmake-with-ohosndk.md) +- [如何在CMake工程中使用NDK](cmake-with-ndk.md) - [应用模型常见问题](faqs-ability.md) - ArkUI框架开发常见问题(ArkTS) - [ArkTS语法使用常见问题](faqs-arkui-arkts.md) diff --git a/zh-cn/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md b/zh-cn/application-dev/faqs/cmake-with-ndk.md similarity index 79% rename from zh-cn/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md rename to zh-cn/application-dev/faqs/cmake-with-ndk.md index 18cbb9628113b1794e78d2ea7f5358e6637c5b6c..21bab6240e263c1211ce0318a2381c1056773c7d 100644 --- a/zh-cn/application-dev/faqs/howto-migrate-cmake-with-ohosndk.md +++ b/zh-cn/application-dev/faqs/cmake-with-ndk.md @@ -6,55 +6,55 @@ ## 如何下载Native API开发包(NDK) -1. 推荐OpenHarmony正式发布的SDK包 ,下载链接可以从OpenHarmony正式发布版本的[release-notes](../../release-notes/OpenHarmony-v3.2-release.md)中获取,点击release notes中【从站点镜像获取】章节下载。 +1. 推荐使用OpenHarmony正式发布的SDK包 ,下载链接可以从OpenHarmony正式发布版本的[release-notes](../../release-notes/OpenHarmony-v3.2-release.md)中获取,点击release notes中【从站点镜像获取】章节下载。 -2. IDE OpenHarmony SDK Manager中下载 +2. IDE OpenHarmony SDK Manager中下载。 -3. 从每日构建中下载,下载地址 http://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist ,形态组件选择ohos-sdk +3. 从每日构建中下载,下载地址 http://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist ,形态组件选择ohos-sdk。 ![](figures/ci_download.png) ## 解压Native API开发包 -下载完成之后,将压缩包放入自己创建好的文件夹下解压,解压完成效果如下图所示: +下载完成之后,将压缩包放入创建好的文件夹下解压,解压完成效果如下图所示: ![](figures/sdk-structure.png) 配置Linux下的环境,如果只是在IDE中使用,跳过下面几步: -将NDK自带的cmake编译工具添加到环境变量中 +将NDK自带的CMake编译工具添加到环境变量中。 ``` #打开.bashrc文件 vim ~/.bashrc - #在文件最后添加cmake路径,该路径是自己的放置文件的路径,之后保存退出 + #在文件最后添加CMake路径,具体路径用实际放置SDK路径代替 export PATH=~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin:$PATH #在命令行执行source ~/.bashrc使环境变量生效 source ~/.bashrc ``` -查看cmake默认路径 +查看CMake默认路径。 ``` - #在命令行输入which cmake + #在命令行输入which命令查询当前CMake所在路径 which cmake - #结果,和自己设置的路径一样 + #结果路径与.bashrc中设置一致 ~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin/cmake ``` ## 如何使用Native API开发包编译一个native程序 -应用开发者可以通过Native API开发包快速的开发出native动态库,静态库与可执行文件,ArkUI应用程序框架可以通过NAPI框架调用到native的动态库中。开发包提供CMake作为官方的编译构建工具。下面通过自己编写一个C/C++ demo工程来演示如何使用Native API开发包来编译C/C++动态库。 +应用开发者可以通过Native API开发包快速的开发出native动态库,静态库与可执行文件,ArkUI应用程序框架可以通过NAPI框架调用到native的动态库中。开发包提供CMake作为官方的编译构建工具。下面通过编写一个C/C++ demo工程来演示如何使用Native API开发包来编译C/C++动态库。 ### NDK中的文件夹简介 #### build目录中工具链文件ohos.toolchain.cmake -cmake编译时需要读取该文件中的默认值,比如编译器架构、C++库链接方式等,这个需要在编译时通过CMAKE_TOOLCHAIN_FILE指出该文件的路径,便于cmake在编译时定位到该文件。在编译的时候需要为cmake指定参数来控制编译目标的属性,具体要指定的参数在下面的[命令行构建](#命令行构建)会具体介绍。 +CMake编译时需要读取该文件中的默认值,比如编译器架构、C++库链接方式等,这个需要在编译时通过CMAKE_TOOLCHAIN_FILE指出该文件的路径,便于CMake在编译时定位到该文件。在编译的时候需要为CMake指定参数来控制编译目标的属性,具体要指定的参数在下面的[命令行构建](#命令行构建)会具体介绍。 #### build-tools文件夹放的是NDK提供的编译工具 ``` - #键入下一行命令查看cmake的版本 + #键入下一行命令查看CMake的版本 cmake -version #结果 cmake version 3.16.5 @@ -84,7 +84,7 @@ cmake编译时需要读取该文件中的默认值,比如编译器架构、C++ #### CMakeLists.txt内容 ``` - # 指定cmake的最小版本 + # 指定CMake的最小版本 CMAKE_MINIMUM_REQUIRED(VERSION 3.16) # 工程名称,这里我们就叫HELLO @@ -118,7 +118,7 @@ cmake编译时需要读取该文件中的默认值,比如编译器架构、C++ TARGET_LINK_LIBRARIES(Hello PUBLIC sum) ``` -详细CMake手册参考 https://cmake.org/cmake/help/v3.16/guide/tutorial/ +详细CMake手册参考 https://cmake.org/cmake/help/v3.16/guide/tutorial/ 。 #### 源码内容 @@ -166,9 +166,9 @@ sum.cpp源码 ### 命令行构建 -在工程目录下,创建build目录,用来放置cmake构建时产生的中间文件。注意: ohos-sdk是下载下来的SDK的根目录,开发者需要自行替换成实际的下载目录。 +在工程目录下,创建build目录,用来放置CMake构建时产生的中间文件。注意: ohos-sdk是下载下来的SDK的根目录,开发者需要自行替换成实际的下载目录。 -1. 采用OHOS_STL=c++_shared动态编译 +1. 采用OHOS_STL=c++_shared动态编译。 ``` >mkdir build && cd build @@ -176,7 +176,7 @@ sum.cpp源码 >cmake --build . ``` -2. 采用OHOS_STL=c++_static静态编译 +2. 采用OHOS_STL=c++_static静态编译。 ``` >mkdir build && cd build diff --git a/zh-cn/application-dev/faqs/faqs-ability.md b/zh-cn/application-dev/faqs/faqs-ability.md index e69186419239818a9ba9a966899e71fadf1234d1..8f82923f076a2c144b52ddbd544e45f3ffd5d190 100644 --- a/zh-cn/application-dev/faqs/faqs-ability.md +++ b/zh-cn/application-dev/faqs/faqs-ability.md @@ -221,7 +221,7 @@ Failure\[INSTALL\_FAILED\_SIZE\_TOO\_LARGE\] error while deploying hap? **参考链接** -[cacheDir](../application-models/application-context-stage.md#获取应用开发路径) +[cacheDir](../application-models/application-context-stage.md#获取应用文件路径) ## 服务卡片生命周期回调函数在哪个js文件中调用 @@ -266,7 +266,7 @@ DevEco Studio默认下载是public-sdk。 **参考链接** -[获取应用开发路径](../application-models/application-context-stage.md#获取应用开发路径) +[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径) ## terminateSelf方法销毁当前应用之后并没有在后台任务列表中删除 @@ -486,7 +486,7 @@ struct AbilityContextTest { [长时任务权限](../security/permission-list.md#ohospermissionkeep_background_running) -[长时任务开发指导](../task-management/continuous-task-dev-guide.md#基于stage模型) +[长时任务开发指导](../task-management/continuous-task.md) ## FA卡片如何进行数据交互 diff --git a/zh-cn/application-dev/faqs/faqs-arkui-animation-interactive-event.md b/zh-cn/application-dev/faqs/faqs-arkui-animation-interactive-event.md index 4860a20ecd34c00ba7d3d385123df465b9c61831..705dee0c10cd44b320c951a2bef8f608209b730d 100644 --- a/zh-cn/application-dev/faqs/faqs-arkui-animation-interactive-event.md +++ b/zh-cn/application-dev/faqs/faqs-arkui-animation-interactive-event.md @@ -194,7 +194,7 @@ struct PageTransition2 { **参考链接** -[页面转场动画](https://docs.openharmony.cn/pages/v3.2/zh-cn/application-dev/ui/arkts-page-transition-animation.md/) +[页面转场动画](../reference/arkui-ts/ts-page-transition-animation.md) ## 自定义组件间如何实现从底部滑入滑出的效果 @@ -269,5 +269,5 @@ struct ComponentChild2 { **参考链接** -[组件内转场动画](https://docs.openharmony.cn/pages/v3.2/zh-cn/application-dev/ui/arkts-transition-animation-within-component.md/) +[组件内转场动画](../ui/arkts-enter-exit-transition.md) diff --git a/zh-cn/application-dev/faqs/faqs-multimedia.md b/zh-cn/application-dev/faqs/faqs-multimedia.md index f22280c5696d4dfaf74e72ded586c69597d07ad9..06383db8238371a594b39842e8b6fd6a1404c2d4 100644 --- a/zh-cn/application-dev/faqs/faqs-multimedia.md +++ b/zh-cn/application-dev/faqs/faqs-multimedia.md @@ -98,7 +98,7 @@ AVSession对媒体播放做了管控,当三方应用从前台切入后台或 **参考链接** -[后台任务管理的长时任务开发指导参考](../task-management/continuous-task-dev-guide.md) +[后台任务管理的长时任务开发指导参考](../task-management/continuous-task.md) [AVSession开发指导参考](../media/using-avsession-developer.md) diff --git a/zh-cn/application-dev/file-management/app-file-access.md b/zh-cn/application-dev/file-management/app-file-access.md index e974394d85fb090deb66210fa3dd66a3958421af..e7924858d1033f6231df862bade0a22de13c673a 100644 --- a/zh-cn/application-dev/file-management/app-file-access.md +++ b/zh-cn/application-dev/file-management/app-file-access.md @@ -34,7 +34,7 @@ ## 开发示例 -在对应用文件开始访问前,开发者需要[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。以从UIAbilityContext获取HAP级别的文件路径为例进行说明,UIAbilityContext的获取方式请参见[获取UIAbility的上下文信息](../application-models/uiability-usage.md#获取uiability的上下文信息)。 +在对应用文件开始访问前,开发者需要[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。以从UIAbilityContext获取HAP级别的文件路径为例进行说明,UIAbilityContext的获取方式请参见[获取UIAbility的上下文信息](../application-models/uiability-usage.md#获取uiability的上下文信息)。 下面介绍几种常用操作示例。 diff --git a/zh-cn/application-dev/file-management/share-app-file.md b/zh-cn/application-dev/file-management/share-app-file.md index e3424cdb36636dfaa409068559842bf45ec8ba10..2d93e836d3387cbcbe2f1f18ce7741ad4bdc4aab 100644 --- a/zh-cn/application-dev/file-management/share-app-file.md +++ b/zh-cn/application-dev/file-management/share-app-file.md @@ -22,7 +22,7 @@ ## 分享文件给其他应用 -在分享文件给其他应用前,开发者需要先[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。 +在分享文件给其他应用前,开发者需要先[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 1. 获取文件在应用沙箱中的路径,并转换为文件URI。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/ide-using.md b/zh-cn/application-dev/key-features/multi-device-app-dev/ide-using.md index 0d9e8cfe73c3b13cfd09f3611dc0faa569e4fdc6..7f7cf3786f62b95754f79d066dd083db0a893039 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/ide-using.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/ide-using.md @@ -58,8 +58,6 @@ DevEco Studio的基本使用,请参考[DevEco Studio使用指南](../../quick- > **说明:** > - 在一个工程中同一个设备类型只支持一个Entry类型的模块。 > -> - 当前的DevEco Studio(3.1.1 Release)在创建工程时,设备类型仅能选择phone和tablet,默认该模块已经选择了entry类型,那么在创建wearable这个模块,只能选择feature类型。 -> > - 在下一个小节,我们将介绍如何修改Module的配置,包括Module的类型以及其支持的设备类型等。 @@ -115,7 +113,7 @@ DevEco Studio的基本使用,请参考[DevEco Studio使用指南](../../quick- 同样的,修改feature1和feature2模块中的oh-package.json文件,使其可以使用common模块中的代码。 -修改oh-package.json文件后,一定要点击右上角的“Sync Now”,否则改动不会生效! +修改oh-package.json文件后,请点击右上角的“Sync Now”,否则改动不会生效。 ## 引用ohpm包中的代码 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md index 78e8fced82673e71ce3a09a726d46a10124a7621..0817e2f588d3b5400ba5684aa5f80566d51a5997 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md @@ -354,16 +354,10 @@ struct MultiLaneList { struct SideBarSample { @StorageLink('currentBreakpoint') private currentBreakpoint: string = "md"; private breakpointSystem: BreakpointSystem = new BreakpointSystem() - @State showSideBar: boolean = false @State selectIndex: number = 0; aboutToAppear() { - this.breakpointSystem.register() - if (this.currentBreakpoint === 'sm') { - this.showSideBar = false - } else { - this.showSideBar = true - } + this.breakpointSystem.register() } aboutToDisappear() { @@ -382,9 +376,6 @@ struct SideBarSample { .height(36) .onClick(() => { this.selectIndex = index - if (this.currentBreakpoint === 'sm') { - this.showSideBar = false - } }) } @@ -412,9 +403,8 @@ struct SideBarSample { .maxSideBarWidth(this.currentBreakpoint === 'sm' ? '100%' : '33.33%') .showControlButton(this.currentBreakpoint === 'sm') .autoHide(false) - .showSideBar(this.showSideBar) .onChange((isBarShow: boolean) => { - this.showSideBar = isBarShow + }) } } diff --git a/zh-cn/application-dev/media/Readme-CN.md b/zh-cn/application-dev/media/Readme-CN.md index 5b3d92fad526aed9daaf7202ef0cc267e59f4d63..863a030c1944ff138d1e0ec10f5ea49bc1318c2e 100755 --- a/zh-cn/application-dev/media/Readme-CN.md +++ b/zh-cn/application-dev/media/Readme-CN.md @@ -31,6 +31,7 @@ - [开发音频通话功能](audio-call-development.md) - [视频播放](video-playback.md) - [视频录制](video-recording.md) + - [屏幕录制](avscreen-capture.md) - 音视频编解码 - [获取支持的编解码能力](obtain-supported-codecs.md) - [音频编码](audio-encoding.md) diff --git a/zh-cn/application-dev/media/audio-playback-overview.md b/zh-cn/application-dev/media/audio-playback-overview.md index 779bde89fd1dafa86bf9c528ffdb2cf870968aa5..d2d0fd340d2161f15bde2fd380b6ac40a9370cef 100644 --- a/zh-cn/application-dev/media/audio-playback-overview.md +++ b/zh-cn/application-dev/media/audio-playback-overview.md @@ -20,6 +20,6 @@ 1. 使用媒体会话功能注册到系统内统一管理,否则在应用进入后台时,播放将被强制停止。具体参考[媒体会话开发指导](avsession-overview.md)。 -2. 申请长时任务避免进入挂起(Suspend)状态。具体参考[长时任务开发指导](../task-management/continuous-task-dev-guide.md)。 +2. 申请长时任务避免进入挂起(Suspend)状态。具体参考[长时任务开发指导](../task-management/continuous-task.md)。 当应用进入后台,播放被中断,如果被媒体会话管控,将打印日志“pause id”;如果没有该日志,则说明被长时任务管控。 diff --git a/zh-cn/application-dev/media/avscreen-capture.md b/zh-cn/application-dev/media/avscreen-capture.md new file mode 100644 index 0000000000000000000000000000000000000000..b1614258308d05aeb6d5d0a957aa3fabaec6c071 --- /dev/null +++ b/zh-cn/application-dev/media/avscreen-capture.md @@ -0,0 +1,237 @@ +# 屏幕录制 + +屏幕录制主要为主屏幕录屏功能。 + +开发者可以调用录屏(AVScreenCapture)模块的Native API接口,完成屏幕录制,采集设备内、麦克风等的音视频源数据。当开发直播、办公等应用时,可以调用录屏模块获取音视频原始码流,然后通过流的方式流转到其他模块处理,达成直播时共享桌面的场景。 + +录屏模块和窗口(Window)、图形(Graphic)等模块完成整个视频采集的流程。 + +当前在进行屏幕录制时默认使用主屏,图形默认根据主屏生产录屏帧数据到显示数据缓冲队列,录屏框架从显示数据缓冲队列获取数据进行相应消费处理。 + +## 开发指导 + +使用AVScreenCapture录制屏幕涉及到AVScreenCapture实例的创建、音视频采集参数的配置、采集的开始与停止、资源的释放等。本开发指导将以一次录制屏幕数据的过程为例,向开发者讲解如何使用AVScreenCapturer进行屏幕录制,详细的API声明请参考[AVScreenCapture API参考](../reference/native-apis/_a_v_screen_capture.md)。 + +使用AVScreenCapture时要明确其状态的变化,在创建实例后,调用对应的方法可以进入指定的状态实现对应的行为。 +在确定的状态下执行不合适的方法会导致AVScreenCapture发生错误,开发者需要在调用状态转换的方法前进行状态检查,避免程序运行异常。 + +### 权限说明 + +在开发前,请根据应用实际需求,参考[访问控制授权申请指导](../security/accesstoken-guidelines.md)申请以下权限: + +| 权限名 | 说明 | 授权方式 | 权限级别 | +| ------ | ----- | --------| ------- | +| ohos.permission.CAPTURE_SCREEN | 允许应用截取屏幕图像。| system_grant | system_core | +| ohos.permission.MICROPHONE | 允许应用使用麦克风(可选)。 +如需录制麦克风源的音频,需要申请该权限。| user_grant | normal | + +### 开发步骤及注意事项 + +开发者可以通过以下几个步骤来实现一个简单的屏幕录制功能。 + +1. 创建AVScreenCapture实例capture。 + + ```c++ + OH_AVScreenCapture* capture = AVScreenCapture_Create(); + ``` + +2. 配置屏幕录制参数。 + 创建AVScreenCapture实例capture后,可以设置屏幕录制所需要的参数。 + + ```c++ + OH_AudioCaptureInfo miccapinfo = { + .audioSampleRate = 16000, + .audioChannels = 2, + .audioSource = OH_MIC + }; + + OH_VideoCaptureInfo videocapinfo = { + .videoFrameWidth = display->GetWidth(), + .videoFrameHeight = display->Height(), + .videoSource = OH_VIDEO_SOURCE_SURFACE_RGBA + }; + + OH_AudioInfo audioinfo = { + .micCapInfo = miccapinfo, + }; + + OH_VideoInfo videoinfo = { + .videoCapInfo = videocapinfo + }; + + OH_RecorderInfo recorderinfo = { + .url = name + }; + + OH_AVScreenCaptureConfig config = { + .captureMode = OH_CAPTURE_HOME_SCREEN, + .dataType = OH_ORIGINAL_STREAM, + .audioInfo = audioinfo, + .videoInfo = videoinfo, + .recorderInfo = recorderinfo + }; + + OH_AVScreenCapture_Init(capture, config); + ``` + +3. 设置麦克风开关。 + + ```c++ + bool isMic = true; + OH_AVScreenCapture_SetMicrophoneEnabled(capture, isMic); + ``` + +4. 回调函数的设置,主要监听录屏过程中的错误事件的发生,音频流和视频流数据的产生事件。 + + ```c++ + OH_AVScreenCaptureCallback callback; + callback.onAudioBufferAvailable = OnAudioBufferAvailable; + callback.onVideoBufferAvailable = OnVideoBufferAvailable; + OH_AVScreenCapture_SetCallback(capture, callback); + ``` + +5. 调用StartScreenCapture方法开始进行屏幕录制。 + + ```c++ + OH_AVScreenCapture_StartScreenCapture(capture); + ``` + +6. 调用StopScreenCapture()方法停止录制。 + + ```c++ + OH_AVScreenCapture_StopScreenCapture(capture_); + ``` + +7. 调用AcquireAudioBuffer()获取音频原始码流数据 + + ```c++ + OH_AVScreenCapture_AcquireAudioBuffer(capture, &audiobuffer, type); + ``` + +8. 调用AcquireVideoBuffer()获取音频原始码流数据。 + + ```c++ + OH_NativeBuffer* buffer = OH_ScreenCapture_AcquireVideoBuffer(capture, &fence, ×tamp, &damage); + ``` + +9. 调用ReleaseAudioBuffer方法释放音频buffer。 + + ```c++ + OH_ScreenCapture_ReleaseAudioBuffer(capture, type); + ``` + +10. 调用ReleaseVideoBuffer()释放视频数据。 + + ```c++ + OH_ScreenCapture_ReleaseVideoBuffer(capture); + ``` + +11. 调用release()方法销毁实例,释放资源。 + + ```c++ + OH_AVScreenCapture_Release(capture); + ``` + +### 完整示例 + +下面展示了使用AVScreenCapture屏幕录制的完整示例代码。 +目前阶段流程结束后返回的buffer为原始码流,针对原始码流可以进行编码并以mp4等文件格式保存以供播放。编码格式与文件格式当前阶段仅作预留,待后续版本实现。 + +```c++ + +#include "multimedia/player_framework/native_avscreen_capture.h" +#include "multimedia/player_framework/native_avscreen_capture_base.h" +#include "multimedia/player_framework/native_avscreen_capture_errors.h" + +void OnError(struct OH_AVScreenCapture *capture, int32_t errorCode) +{ + (void) capture; + (void) errorCode; +} + +void OnAudioBufferAvailable(struct OH_AVScreenCapture *capture, bool isReady, OH_AudioCapSourceType type) +{ + if (isReady) { + OH_AudioBuffer *audiobuffer = (struct OH_AudioBuffer*) malloc (sizeof(OH_AudioBuffer)); + //获取音频流 + int32_t ret = OH_AVScreenCapture_AcquireAudioBuffer(capture, &audiobuffer, type); + /* get buffer */ + (void)audiobuffer->buf; + /* getbuffer size */ + (void)audiobuffer->size; + /* get audiobuffer timestampe */ + (void)audiobuffer->timestamp; + free(audiobuffer); + audiobuffer = nullptr; + //释放音频流 + int32_t ret = OH_ScreenCapture_ReleaseAudioBuffer(capture, type); + } +} + +void OnVideoBufferAvailable(struct OH_ScreenCapture *capture, bool isReady) +{ + if (isReady) { + int32_t fence = 0; + int64_t timestamp = 0; + struct OH_Rect damage; + //获取视频流 + OH_NativeBuffer* buffer = OH_ScreenCapture_AcquireVideoBuffer(capture, &fence, ×tamp, &damage); + void *virAddr = nullptr; + OH_NativeBuffer_Map(buffer, &virAddr); //获取buffer + OH_NativeBuffer_Config config; + OH_NativeBuffer_GetNativeBufferConfig(buffer, config); //获取config信息 宽,高,format + // fence, timestampe, damage 获取fence,时间戳,坐标信息 + OH_NativeBuffer_UnMap(buffer); //释放buffer + //释放视频流 + int32_t ret = OH_ScreenCapture_ReleaseVideoBuffer(capture); + } +} + +int main() +{ + //实例化ScreenCapture + struct OH_AVScreenCapture* capture = OH_AVScreenCapture_Create(void); + //设置回调 + struct OH_AVScreenCaptureCallback callback; + callback.onError = OnError; + callack.onAudioBufferAvailable = OnAudioBufferAvailable ; + callack.onVideoBufferAvailable = OnVideoBufferAvailable; + int32_t ret = OH_AVScreenCapture_SetCallback(capture, callback); + //初始化录屏,传入配置信息OH_AVScreenRecorderConfig + OH_AudioCaptureInfo miccapinfo = { + .audioSampleRate = 16000, + .audioChannels = 2, + .audioSource = OH_MIC + }; + OH_VideoCaptureInfo videocapinfo = { + .videoFrameWidth = 720, + .videoFrameHeight = 1280, + .videoSource = OH_VIDEO_SOURCE_SURFACE_RGBA + }; + OH_AudioInfo audioinfo = { + .micCapInfo = miccapinfo, + }; + OH_VideoInfo videoinfo = { + .videoCapInfo = videocapinfo + }; + OH_AVScreenCaptureConfig config = { + .captureMode = OH_CAPTURE_HOME_SCREEN, + .dataType = OH_ORIGINAL_STREAM, + .audioInfo = audioinfo, + .videoInfo = videoinfo, + .recorderInfo = recorderinfo + }; + OH_AVScreenCapture_Init(capture, config); + int32_t ret = OH_AVScreenCapture_Init(capture, &config); + //开始录屏 + int32_t ret = OH_AVScreenCapture_StartScreenCapture(capture); + //mic开关设置 + int32_t ret = OH_ScreenCapture_SetMicrophoneEnable(capture, true); + sleep(10); //录制10s + //结束录屏 + int32_t ret = OH_ScreenCapture_StopScreenCapture(capture); + //释放ScreenCapture + int32_t ret = OH_ScreenCapture_Realease(capture); + return 0; +} +``` diff --git a/zh-cn/application-dev/media/avsession-overview.md b/zh-cn/application-dev/media/avsession-overview.md index 446e027ad0d8c1d745c7941ee47d4a371cf7bbfe..148ae02a01b2f16189579fdf04feefa9c9948b34 100644 --- a/zh-cn/application-dev/media/avsession-overview.md +++ b/zh-cn/application-dev/media/avsession-overview.md @@ -4,7 +4,7 @@ 音视频类应用接入媒体会话后,可以发送应用的数据(比如正在播放的歌曲、歌曲的播放状态等),用户可以通过系统播控中心、语音助手等应用切换多个应用、多个设备播放。音视频类应用如果不接入媒体会话,将无法在后台播放,在应用进入后台时,会被强制停止播放。 -实现后台播放,还需申请长时任务避免进入挂起(Suspend)状态。具体参考[长时任务开发指导](../task-management/continuous-task-dev-guide.md)。 +实现后台播放,还需申请长时任务避免进入挂起(Suspend)状态。具体参考[长时任务开发指导](../task-management/continuous-task.md)。 ## 基础概念 diff --git a/zh-cn/application-dev/media/camera-preview.md b/zh-cn/application-dev/media/camera-preview.md index ec2f45a39cc887d96551acbb6c33a65dfcb1c9e3..2836389c3b3db5ed27629f249bbf333e3ec7caaf 100644 --- a/zh-cn/application-dev/media/camera-preview.md +++ b/zh-cn/application-dev/media/camera-preview.md @@ -34,7 +34,7 @@ } ``` -2. 通过CameraOutputCapability类中的previewProfiles()方法获取当前设备支持的预览能力,返回previewProfilesArray数组 。通过createPreviewOutput()方法创建预览输出流,其中,createPreviewOutput()方法中的而两个参数分别是previewProfilesArray数组中的第一项和步骤一中获取的surfaceId。 +2. 通过CameraOutputCapability类中的previewProfiles()方法获取当前设备支持的预览能力,返回previewProfilesArray数组 。通过createPreviewOutput()方法创建预览输出流,其中,createPreviewOutput()方法中的两个参数分别是previewProfilesArray数组中的第一项和步骤一中获取的surfaceId。 ```ts let previewProfilesArray = cameraOutputCapability.previewProfiles; diff --git a/zh-cn/application-dev/media/using-avplayer-for-playback.md b/zh-cn/application-dev/media/using-avplayer-for-playback.md index 95edec4d34a45afc308a10cc216ae38e6914b011..9806dae07b64c72166f388bef40f343746a2f5a5 100644 --- a/zh-cn/application-dev/media/using-avplayer-for-playback.md +++ b/zh-cn/application-dev/media/using-avplayer-for-playback.md @@ -2,7 +2,7 @@ 使用AVPlayer可以实现端到端播放原始媒体资源,本开发指导将以完整地播放一首音乐作为示例,向开发者讲解AVPlayer音频播放相关功能。 -以下指导仅介绍如何实现媒体资源播放,如果要实现后台播放或熄屏播放,需要使用[AVSession(媒体会话)](avsession-overview.md)和[申请长时任务](../task-management/continuous-task-dev-guide.md),避免播放被系统强制中断。 +以下指导仅介绍如何实现媒体资源播放,如果要实现后台播放或熄屏播放,需要使用[AVSession(媒体会话)](avsession-overview.md)和[申请长时任务](../task-management/continuous-task.md),避免播放被系统强制中断。 播放的全流程包含:创建AVPlayer,设置播放资源,设置播放参数(音量/倍速/焦点模式),播放控制(播放/暂停/跳转/停止),重置,销毁资源。 @@ -40,7 +40,7 @@ > > 下面代码示例中的url仅作示意使用,开发者需根据实际情况,确认资源有效性并设置: > - > - 如果使用本地资源播放,必须确认资源文件可用,并使用应用沙箱路径访问对应资源,参考[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。应用沙箱的介绍及如何向应用沙箱推送文件,请参考[文件管理](../file-management/app-sandbox-directory.md)。 + > - 如果使用本地资源播放,必须确认资源文件可用,并使用应用沙箱路径访问对应资源,参考[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。应用沙箱的介绍及如何向应用沙箱推送文件,请参考[文件管理](../file-management/app-sandbox-directory.md)。 > > - 如果使用网络播放路径,需[申请相关权限](../security/accesstoken-guidelines.md):ohos.permission.INTERNET。 > diff --git a/zh-cn/application-dev/media/video-playback.md b/zh-cn/application-dev/media/video-playback.md index da324f48191e3ca2a66506bb3650363ad56255ab..229bbbc3e2d12f2bacc596403252c84e0b9f5e3f 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -6,7 +6,7 @@ - Video组件:封装了视频播放的基础能力,需要设置数据源以及基础信息即可播放视频,但相对扩展能力较弱。Video组件由ArkUI提供能力,相关指导请参考UI开发文档-[Video组件](../ui/arkts-common-components-video-player.md)。 -本开发指导将介绍如何使用AVPlayer开发视频播放功能,以完整地播放一个视频作为示例,实现端到端播放原始媒体资源。如果要实现后台播放或熄屏播放,需要使用[AVSession(媒体会话)](avsession-overview.md)和[申请长时任务](../task-management/continuous-task-dev-guide.md),避免播放过程中音频模块被系统强制中断。 +本开发指导将介绍如何使用AVPlayer开发视频播放功能,以完整地播放一个视频作为示例,实现端到端播放原始媒体资源。如果要实现后台播放或熄屏播放,需要使用[AVSession(媒体会话)](avsession-overview.md)和[申请长时任务](../task-management/continuous-task.md),避免播放过程中音频模块被系统强制中断。 ## 开发指导 @@ -46,7 +46,7 @@ > > 下面代码示例中的url仅作示意使用,开发者需根据实际情况,确认资源有效性并设置: > - > - 如果使用本地资源播放,必须确认资源文件可用,并使用应用沙箱路径访问对应资源,参考[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。应用沙箱的介绍及如何向应用沙箱推送文件,请参考[文件管理](../file-management/app-sandbox-directory.md)。 + > - 如果使用本地资源播放,必须确认资源文件可用,并使用应用沙箱路径访问对应资源,参考[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。应用沙箱的介绍及如何向应用沙箱推送文件,请参考[文件管理](../file-management/app-sandbox-directory.md)。 > > - 如果使用网络播放路径,需[申请相关权限](../security/accesstoken-guidelines.md):ohos.permission.INTERNET。 > diff --git a/zh-cn/application-dev/napi/Readme-CN.md b/zh-cn/application-dev/napi/Readme-CN.md index ba6b1f29271ff7493ffd828c11f1713deea332f5..64e7a67ce018243582afb87f5988521e32056d8d 100644 --- a/zh-cn/application-dev/napi/Readme-CN.md +++ b/zh-cn/application-dev/napi/Readme-CN.md @@ -19,3 +19,7 @@ - [Purgeable memory开发指导](purgeable-memory-guidelines.md) - 设备管理 - [USB DDK开发指导](usb-ddk-guidelines.md) + +- 数据管理 + - [RelationalStore开发指导](native-relational-store-guidelines.md) + diff --git a/zh-cn/application-dev/napi/native-buffer-guidelines.md b/zh-cn/application-dev/napi/native-buffer-guidelines.md index 7feff7533d16ceca5ca35ff81e678323b8ab73a0..63c7f769a6b2c70ac6ad7b3d32fde0f6c5019d0d 100644 --- a/zh-cn/application-dev/napi/native-buffer-guidelines.md +++ b/zh-cn/application-dev/napi/native-buffer-guidelines.md @@ -25,6 +25,13 @@ NativeBuffer是`OpenHarmony`提供**共享内存**的模块。开发者可以通 以下步骤描述了在**OpenHarmony**中如何使用`NativeBuffer`提供的Native API接口,创建`OH_NativeBuffer`实例获取内存的属性信息,并把对应的ION内存映射到进程空间。 +**添加动态链接库** + +CMakeLists.txt中添加以下lib。 +```txt +libnative_buffer.so +``` + **头文件** ```c++ #include diff --git a/zh-cn/application-dev/napi/native-image-guidelines.md b/zh-cn/application-dev/napi/native-image-guidelines.md index 1f200277b2ccc1285b42338268e9a38dc4e262f5..a8d1d01f68ed2dd5cfee99922c34bde977e7d8e2 100644 --- a/zh-cn/application-dev/napi/native-image-guidelines.md +++ b/zh-cn/application-dev/napi/native-image-guidelines.md @@ -26,6 +26,17 @@ NativeImage是`OpenHarmony`提供**Surface关联OpenGL外部纹理**的模块, 以下步骤描述了在**OpenHarmony**中如何使用`NativeImage`提供的Native API接口,创建`OH_NativeImage`实例作为消费者端,将数据内容更新到OpenGL外部纹理上。 +**添加动态链接库** + +CMakeLists.txt中添加以下lib。 +```txt +libEGL.so +libGLESv3.so +libnative_image.so +libnative_window.so +libnative_buffer.so +``` + **头文件** ```c++ #include diff --git a/zh-cn/application-dev/napi/native-relational-store-guidelines.md b/zh-cn/application-dev/napi/native-relational-store-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..ff4a3aaeaa80a4c8f4db2901d16d1e3ee1370f97 --- /dev/null +++ b/zh-cn/application-dev/napi/native-relational-store-guidelines.md @@ -0,0 +1,176 @@ +# RelationalStore开发指导 + + +## 场景介绍 + +RelationalStore提供了一套完整的对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。 + + +## 基本概念 + +- **谓词**:数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 + +- **结果集**:指用户查询之后的结果集合,可以对数据进行访问。结果集提供了灵活的数据访问方式,可以更方便地拿到用户想要的数据。 + + +## 约束限制 + +- 系统默认日志方式是WAL(Write Ahead Log)模式,系统默认落盘方式是FULL模式。 + +- 数据库中连接池的最大数量是4个,用以管理用户的读操作。 + +- 为保证数据的准确性,数据库同一时间只能支持一个写操作。 + +- 当应用被卸载完成后,设备上的相关数据库文件及临时文件会被自动清除。 + + +## 接口说明 + +详细的接口说明请参考[RDB](../reference/native-apis/_r_d_b.md)。 + +| 接口名称 | 描述 | +| -------- | -------- | +| OH_Rdb_GetOrOpen(const OH_Rdb_Config *config, int *errCode) | 获得一个相关的OH_Rdb_Store实例,操作关系型数据库。 | +| OH_Rdb_Execute(OH_Rdb_Store *store, const char *sql) | 执行包含指定参数但不返回值的SQL语句。 | +| OH_Rdb_Insert(OH_Rdb_Store *store, const char *table, OH_VBucket *valuesBucket) | 向目标表中插入一行数据。 | +| OH_Rdb_Update(OH_Rdb_Store *store, OH_VBucket *valuesBucket, OH_Predicates *predicates); | 根据OH_Predicates的指定实例对象更新数据库中的数据。 | +| OH_Rdb_Delete(OH_Rdb_Store *store, OH_Predicates *predicates) | 根据OH_Predicates的指定实例对象从数据库中删除数据。 | +| OH_Rdb_Query(OH_Rdb_Store *store, OH_Predicates *predicates, const char *const *columnNames, int length) | 根据指定条件查询数据库中的数据。 | +| OH_Rdb_DeleteStore(const OH_Rdb_Config *config) | 删除数据库。 | + + +## 开发步骤 + +1. 获取OH_Rdb_Store实例,创建数据库文件。示例代码如下所示: + + ```c + // 创建OH_Rdb_Config对象 + OH_Rdb_Config config; + // 该路径为应用沙箱路径 + config.dataBaseDir = "xxx"; + // 数据库文件名 + config.storeName = "RdbTest.db"; + // 应用包名 + config.bundleName = "xxx"; + // 应用模块名 + config.moduleName = "xxx"; + // 数据库文件安全等级 + config.securityLevel = OH_Rdb_SecurityLevel::S1; + // 数据库是否加密 + config.isEncrypt = false; + // config所占内存大小 + config.selfSize = sizeof(OH_Rdb_Config); + + int errCode = 0; + // 获取获取OH_Rdb_Store实例 + OH_Rdb_Store *store_ = OH_Rdb_GetOrOpen(&config, &errCode); + ``` + +2. 获取到OH_Rdb_Store后,调用OH_Rdb_Execute接口创建表,并调用OH_Rdb_Insert接口插入数据。示例代码如下所示: + + ```c + char createTableSql[] = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, " + "AGE INTEGER, SALARY REAL, CODES BLOB)"; + // 执行建表语句 + OH_Rdb_Execute(store_, createTableSql); + + // 创建键值对实例 + OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket(); + valueBucket->putText(valueBucket, "NAME", "Lisa"); + valueBucket->putInt64(valueBucket, "AGE", 18); + valueBucket->putReal(valueBucket, "SALARY", 100.5); + uint8_t arr[] = {1, 2, 3, 4, 5}; + int len = sizeof(arr) / sizeof(arr[0]); + valueBucket->putBlob(valueBucket, "CODES", arr, len); + // 插入数据 + int rowId = OH_Rdb_Insert(store_, "EMPLOYEE", valueBucket); + // 销毁键值对实例 + valueBucket->destroy(valueBucket); + ``` + + > **说明:** + > + > 关系型数据库没有显式的flush操作实现持久化,数据插入即保存在持久化文件。 + +3. 根据谓词指定的实例对象,对数据进行修改或删除。 + + 调用OH_Rdb_Update方法修改数据,调用OH_Rdb_Delete方法删除数据。示例代码如下所示: + + ```c + // 修改数据 + OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket(); + valueBucket->putText(valueBucket, "NAME", "Rose"); + valueBucket->putInt64(valueBucket, "AGE", 22); + valueBucket->putReal(valueBucket, "SALARY", 200.5); + uint8_t arr[] = {1, 2, 3, 4, 5}; + int len = sizeof(arr) / sizeof(arr[0]); + valueBucket->putBlob(valueBucket, "CODES", arr, len); + + OH_Predicates *predicates = OH_Rdb_CreatePredicates("EMPLOYEE"); + OH_VObject *valueObject = OH_Rdb_CreateValueObject(); + const char *name = "Lisa"; + valueObject->putText(valueObject, name); + predicates->equalTo(predicates, "NAME", valueObject)->andOperate(predicates); + uint32_t count = 1; + double salary = 100.5; + valueObject->putDouble(valueObject, &salary, count); + predicates->equalTo(predicates, "SALARY", valueObject); + + int changeRows = OH_Rdb_Update(store_, valueBucket, predicates); + valueObject->destroy(valueObject); + valueBucket->destroy(valueBucket); + predicates->destroy(predicates); + ``` + + ```c + // 删除数据 + OH_Predicates *predicates = OH_Rdb_CreatePredicates("EMPLOYEE"); + OH_VObject *valueObject = OH_Rdb_CreateValueObject(); + const char *name = "Lisa"; + valueObject->putText(valueObject, name); + predicates->equalTo(predicates, "NAME", valueObject); + int deleteRows = OH_Rdb_Delete(store_, predicates); + valueObject->destroy(valueObject); + predicates->destroy(predicates); + ``` + +4. 根据谓词指定的查询条件查找数据。 + + 调用OH_Rdb_Query方法查找数据,返回一个OH_Cursor结果集。示例代码如下所示: + + ```c + OH_Predicates *predicates = OH_Rdb_CreatePredicates("EMPLOYEE"); + + const char *columnNames[] = {"NAME", "AGE"}; + int len = sizeof(columnNames) / sizeof(columnNames[0]); + OH_Cursor *cursor = OH_Rdb_Query(store_, predicates, columnNames, len); + + int columnCount = 0; + cursor->getColumnCount(cursor, &columnCount); + + // OH_Cursor是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始 + int64_t age; + while (cursor->goToNextRow(cursor) == OH_Rdb_ErrCode::RDB_OK) { + cursor->getInt64(cursor, 1, &age); + } + + // 释放谓词实例 + predicates->destroy(predicates); + // 释放结果集 + cursor->destroy(cursor); + ``` + +5. 删除数据库。 + + 调用OH_Rdb_DeleteStore方法,删除数据库及数据库相关文件。示例代码如下: + + + ```c + // 释放数据库实例 + OH_Rdb_CloseStore(store_); + // 删除数据库文件 + OH_Rdb_DeleteStore(&config); + ``` + + + diff --git a/zh-cn/application-dev/napi/native-vsync-guidelines.md b/zh-cn/application-dev/napi/native-vsync-guidelines.md index 63da1350b96d2d4603dacf90da13db4ca485c145..0261621db13cf1e36772e7ef2bb1732cfba346a0 100644 --- a/zh-cn/application-dev/napi/native-vsync-guidelines.md +++ b/zh-cn/application-dev/napi/native-vsync-guidelines.md @@ -19,6 +19,13 @@ NativeVsync模块用来获取系统VSync信号,提供了OH_NativeVSync实例 以下步骤描述了在**OpenHarmony**中如何使用`NativeVsync`提供的Native API接口,创建和销毁`OH_NativeVsync`实例,以及如何设置VSync回调函数。 +**添加动态链接库** + +CMakeLists.txt中添加以下lib。 +```txt +libnative_vsync.so +``` + **头文件** ```c++ #include diff --git a/zh-cn/application-dev/napi/native-window-guidelines.md b/zh-cn/application-dev/napi/native-window-guidelines.md index 6ed367948c2be42737efa31bca8966fc9bfd756c..4e191da6e2e5a8256c338d489d8efb906df0cb6f 100644 --- a/zh-cn/application-dev/napi/native-window-guidelines.md +++ b/zh-cn/application-dev/napi/native-window-guidelines.md @@ -23,6 +23,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生 以下步骤描述了在**OpenHarmony**中如何使用`NativeWindow`提供的Native API接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 **添加动态链接库** + CMakeLists.txt中添加以下lib。 ```txt libace_ndk.z.so diff --git a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md index 4fa36ff1f15e23b4d8d1a311384fcf7e42ba2bea..bdde437188c2cc9a9da8ddbdcb2b2eec1056c61b 100644 --- a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md +++ b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md @@ -19,13 +19,14 @@ Neural Network Runtime部件的环境要求如下: - 开发环境:Ubuntu 18.04及以上。 - 接入设备:OpenHarmony定义的标准设备,并且系统中内置的硬件加速器驱动,已通过HDI接口对接Neural Network Runtime。 -由于Neural Network Runtime通过OpenHarmony Native API对外开放,需要通过OpenHarmony的Native开发套件编译Neural Network Runtime应用。在社区的[每日构建](http://ci.openharmony.cn/dailys/dailybuilds)下载对应系统版本的ohos-sdk压缩包,从压缩包中提取对应平台的Native开发套件。以Linux为例,Native开发套件的压缩包命名为`native-linux-{版本号}.zip`。 +由于Neural Network Runtime通过OpenHarmony Native API对外开放,需要通过OpenHarmony的Native开发套件编译Neural Network Runtime应用。 ### 环境搭建 1. 打开Ubuntu编译服务器的终端。 -2. 把下载好的Native开发套件压缩包拷贝至当前用户根目录下。 +2. 把Native开发套件压缩包拷贝至当前用户根目录下。 3. 执行以下命令解压Native开发套件的压缩包。 + ```shell unzip native-linux-{版本号}.zip ``` @@ -470,16 +471,19 @@ Neural Network Runtime的开发流程主要包含**模型构造**、**模型编 > 模型的IR需要传递到硬件驱动层,由HDI服务将统一的IR图,编译成硬件专用的计算图,编译的过程非常耗时。Neural Network Runtime支持计算图缓存的特性,可以将HDI服务编译生成的计算图,缓存到设备存储中。当下一次在同一个加速芯片上编译同一个模型时,通过指定缓存的路径,Neural Network Runtime可以直接加载缓存文件中的计算图,减少编译消耗的时间。 检查缓存目录下的缓存文件: + ```shell ls /data/local/tmp ``` 以下为打印结果: + ```text # 0.nncache cache_info.nncache ``` 如果缓存不再使用,需要手动删除缓存,可以参考以下命令,删除缓存文件。 + ```shell rm /data/local/tmp/*nncache ``` @@ -487,5 +491,5 @@ Neural Network Runtime的开发流程主要包含**模型构造**、**模型编 ## 相关实例 第三方AI推理框架对接Neural Network Runtime的流程,可以参考以下相关实例: -- [Tensorflow Lite接入NNRt Delegate开发指南](https://gitee.com/openharmony/neural_network_runtime/tree/master/example/deep_learning_framework) - + +- [Tensorflow Lite接入NNRt Delegate开发指南](https://gitee.com/openharmony/ai_neural_network_runtime/tree/master/example/deep_learning_framework) diff --git a/zh-cn/application-dev/napi/vulkan-guidelines.md b/zh-cn/application-dev/napi/vulkan-guidelines.md index d8331926f4e3664362ba63cd825f935d2ce85632..f0bf36a0225106d05611f4526c7c2031d7fcf220 100644 --- a/zh-cn/application-dev/napi/vulkan-guidelines.md +++ b/zh-cn/application-dev/napi/vulkan-guidelines.md @@ -18,6 +18,15 @@ Vulkan是一套用来做2D和3D渲染的图形应用程序接口,其中创建V 以下步骤说明了如何在OpenHarmony平台创建一个VkSurfaceKHR对象。 +**添加动态链接库** + +CMakeLists.txt中添加以下lib。 +```txt +libace_ndk.z.so +libnative_window.so +libvulkan.so +``` + **头文件** ```c++ #include diff --git a/zh-cn/application-dev/napi/xcomponent-guidelines.md b/zh-cn/application-dev/napi/xcomponent-guidelines.md index 179fca2339061e6d98bc73fdd130befbc8aaea99..14d176da8269fbaa801ad4f46f7ce301b64cabd6 100644 --- a/zh-cn/application-dev/napi/xcomponent-guidelines.md +++ b/zh-cn/application-dev/napi/xcomponent-guidelines.md @@ -81,7 +81,7 @@ XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' } // ... ``` -2. **Napi模块注册**,具体使用请参考[Native API在应用工程中的使用指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/napi/napi-guidelines.md)。 +2. **Napi模块注册**,具体使用请参考[Native API在应用工程中的使用指导](napi-guidelines.md)。 ```c++ // 在napi_init.cpp文件中,Init方法注册接口函数,从而将封装的C++方法传递出来,供JS侧调用 diff --git a/zh-cn/application-dev/quick-start/arkts-builder.md b/zh-cn/application-dev/quick-start/arkts-builder.md index b3c1e91eb13e3796404520ff096c01d077f14211..6b151dab926c7407ff3360029c3fccf87fff1b8a 100644 --- a/zh-cn/application-dev/quick-start/arkts-builder.md +++ b/zh-cn/application-dev/quick-start/arkts-builder.md @@ -21,14 +21,14 @@ ```ts -@Builder myBuilderFunction({ ... }) +@Builder MyBuilderFunction({ ... }) ``` 使用方法: ```ts -this.myBuilderFunction({ ... }) +this.MyBuilderFunction({ ... }) ``` - 允许在自定义组件内定义一个或多个自定义构建函数,该函数被认为是该组件的私有、特殊类型的成员函数。 diff --git a/zh-cn/application-dev/quick-start/arkts-localstorage.md b/zh-cn/application-dev/quick-start/arkts-localstorage.md index a9b76cf6ddf4d079295a5087cd059a61b6cc4eae..8b658b0d12cd99bad49ee2874866acb5289a2f37 100644 --- a/zh-cn/application-dev/quick-start/arkts-localstorage.md +++ b/zh-cn/application-dev/quick-start/arkts-localstorage.md @@ -36,7 +36,7 @@ LocalStorage根据与\@Component装饰的组件的同步类型不同,提供了 ## 限制条件 - LocalStorage创建后,命名属性的类型不可更改。后续调用Set时必须使用相同类型的值。 -- LocalStorage是页面级存储,[GetShared](../reference/arkui-ts/ts-state-management.md#getshared9)接口仅能获取当前stage,通过[windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9)传入的LocalStorage实例,否则返回undefined。例子可见[将LocalStorage实例从UIAbility共享到一个或多个视图](#将localstorage实例从uiability共享到一个或多个视图)。 +- LocalStorage是页面级存储,[GetShared](../reference/arkui-ts/ts-state-management.md#getshared10)接口仅能获取当前stage,通过[windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9)传入的LocalStorage实例,否则返回undefined。例子可见[将LocalStorage实例从UIAbility共享到一个或多个视图](#将localstorage实例从uiability共享到一个或多个视图)。 ## \@LocalStorageProp diff --git a/zh-cn/application-dev/quick-start/arkts-mvvm.md b/zh-cn/application-dev/quick-start/arkts-mvvm.md index 6185ed8d6574e2083605b4d2a4171ca768918106..8f0a9b1fb98430d34f544c8cc7f0b98b71333ca7 100644 --- a/zh-cn/application-dev/quick-start/arkts-mvvm.md +++ b/zh-cn/application-dev/quick-start/arkts-mvvm.md @@ -775,7 +775,7 @@ struct ViewA { 开发一个电话簿应用,实现功能如下: -- 显示联系人和本机("Me")电话号码 。 +- 显示联系人和设备("Me")电话号码 。 - 选中联系人时,进入可编辑态”Edit“,可以更新该联系人详细信息,包括电话号码,住址。 @@ -788,8 +788,8 @@ ViewModel需要包括: - AddressBook(class) - - me (本机): 存储一个Person类。 - - contacts(本机联系人):存储一个Person类数组。 + - me (设备): 存储一个Person类。 + - contacts(设备联系人):存储一个Person类数组。 AddressBook类声明如下: @@ -936,11 +936,11 @@ export class ObservedArray extends Array { @Component struct PageEntry { @Provide addrBook: AddressBook = new AddressBook( - new Person("Gigi", "Itamerenkatu 9", 180, "Helsinki", ["+358441234567", "+35891234567", "+49621234567889"]), + new Person("Gigi", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********", "18*********"]), [ - new Person("Oly", "Itamerenkatu 9", 180, "Helsinki", ["+358449876543", "+3589456789"]), - new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["+358509876543", "+358910101010"]), - new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["+358400908070", "+35894445555"]), + new Person("Oly", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), + new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), + new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), ]); build() { @@ -1099,236 +1099,236 @@ export class ObservedArray extends Array { 完整应用代码如下: - ```ts - // ViewModel classes - let nextId = 0; - - @Observed - export class ObservedArray extends Array { - constructor(args?: any[]) { - console.log(`ObservedArray: ${JSON.stringify(args)} `) - if (Array.isArray(args)) { - super(...args); - } else { - super(args) - } - } - } - - @Observed - export class Address { - street: string; - zip: number; - city: string; - - constructor(street: string, - zip: number, - city: string) { - this.street = street; - this.zip = zip; - this.city = city; - } - } - - @Observed - export class Person { - id_: string; - name: string; - address: Address; - phones: ObservedArray; - - constructor(name: string, - street: string, - zip: number, - city: string, - phones: string[]) { - this.id_ = `${nextId}`; - nextId++; - this.name = name; - this.address = new Address(street, zip, city); - this.phones = new ObservedArray(phones); - } +```ts + + // ViewModel classes + let nextId = 0; + + @Observed + export class ObservedArray extends Array { + constructor(args?: any[]) { + console.log(`ObservedArray: ${JSON.stringify(args)} `) + if (Array.isArray(args)) { + super(...args); + } else { + super(args) } - - - export class AddressBook { - me: Person; - contacts: ObservedArray; - - constructor(me: Person, contacts: Person[]) { - this.me = me; - this.contacts = new ObservedArray(contacts); + } + } + + @Observed + export class Address { + street: string; + zip: number; + city: string; + + constructor(street: string, + zip: number, + city: string) { + this.street = street; + this.zip = zip; + this.city = city; + } + } + + @Observed + export class Person { + id_: string; + name: string; + address: Address; + phones: ObservedArray; + + constructor(name: string, + street: string, + zip: number, + city: string, + phones: string[]) { + this.id_ = `${nextId}`; + nextId++; + this.name = name; + this.address = new Address(street, zip, city); + this.phones = new ObservedArray(phones); + } + } + + export class AddressBook { + me: Person; + contacts: ObservedArray; + + constructor(me: Person, contacts: Person[]) { + this.me = me; + this.contacts = new ObservedArray(contacts); + } + } + + //渲染出Person对象的名称和Observed数组中的第一个号码 + //为了更新电话号码,这里需要@ObjectLink person和@ObjectLink phones, + //不能使用this.person.phones,内部数组的更改不会被观察到。 + // 在AddressBookView、PersonEditView中的onClick更新selectedPerson + @Component + struct PersonView { + @ObjectLink person: Person; + @ObjectLink phones: ObservedArray; + @Link selectedPerson: Person; + + build() { + Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { + Text(this.person.name) + if (this.phones.length) { + Text(this.phones[0]) } } - - //渲染出Person对象的名称和手机Observed数组中的第一个号码 - //为了更新电话号码,这里需要@ObjectLink person和@ObjectLink phones, - //不能使用this.person.phones,内部数组的更改不会被观察到。 - // 在AddressBookView、PersonEditView中的onClick更新selectedPerson - @Component - struct PersonView { - @ObjectLink person: Person; - @ObjectLink phones: ObservedArray; - @Link selectedPerson: Person; - - build() { - Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { - Text(this.person.name) - if (this.phones.length) { - Text(this.phones[0]) - } - } - .height(55) - .backgroundColor(this.selectedPerson.name == this.person.name ? "#ffa0a0" : "#ffffff") - .onClick(() => { - this.selectedPerson = this.person; + .height(55) + .backgroundColor(this.selectedPerson.name == this.person.name ? "#ffa0a0" : "#ffffff") + .onClick(() => { + this.selectedPerson = this.person; + }) + } + } + + // 渲染Person的详细信息 + // @Prop装饰的变量从父组件AddressBookView深拷贝数据,将变化保留在本地, TextInput的变化只会在本地副本上进行修改。 + // 点击 "Save Changes" 会将所有数据的复制通过@Prop到@Link, 同步到其他组件 + @Component + struct PersonEditView { + @Consume addrBook: AddressBook; + + /* 指向父组件selectedPerson的引用 */ + @Link selectedPerson: Person; + + /*在本地副本上编辑,直到点击保存*/ + @Prop name: string; + @Prop address: Address; + @Prop phones: ObservedArray; + + selectedPersonIndex(): number { + return this.addrBook.contacts.findIndex((person) => person.id_ == this.selectedPerson.id_); + } + + build() { + Column() { + TextInput({ text: this.name }) + .onChange((value) => { + this.name = value; }) - } - } - - // 渲染Person的详细信息 - // @Prop装饰的变量从父组件AddressBookView深拷贝数据,将变化保留在本地, TextInput的变化只会在本地副本上进行修改。 - // 点击 "Save Changes" 会将所有数据的复制通过@Prop到@Link, 同步到其他组件 - @Component - struct PersonEditView { - @Consume addrBook: AddressBook; - - /* 指向父组件selectedPerson的引用 */ - @Link selectedPerson: Person; - - /*在本地副本上编辑,直到点击保存*/ - @Prop name: string; - @Prop address: Address; - @Prop phones: ObservedArray; - - selectedPersonIndex(): number { - return this.addrBook.contacts.findIndex((person) => person.id_ == this.selectedPerson.id_); - } - - build() { - Column() { - TextInput({ text: this.name }) - .onChange((value) => { - this.name = value; - }) - TextInput({ text: this.address.street }) - .onChange((value) => { - this.address.street = value; - }) - - TextInput({ text: this.address.city }) - .onChange((value) => { - this.address.city = value; - }) - - TextInput({ text: this.address.zip.toString() }) - .onChange((value) => { - const result = parseInt(value); - this.address.zip = isNaN(result) ? 0 : result; - }) - - if (this.phones.length > 0) { - ForEach(this.phones, - (phone, index) => { - TextInput({ text: phone }) - .width(150) - .onChange((value) => { - console.log(`${index}. ${value} value has changed`) - this.phones[index] = value; - }) - }, - (phone, index) => `${index}-${phone}` - ) - } - - Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { - Text("Save Changes") - .onClick(() => { - // 将本地副本更新的值赋值给指向父组件selectedPerson的引用 - // 避免创建新对象,在现有属性上进行修改 - this.selectedPerson.name = this.name; - this.selectedPerson.address.street = this.address.street - this.selectedPerson.address.city = this.address.city - this.selectedPerson.address.zip = this.address.zip - this.phones.forEach((phone: string, index: number) => { - this.selectedPerson.phones[index] = phone - }); + TextInput({ text: this.address.street }) + .onChange((value) => { + this.address.street = value; + }) + + TextInput({ text: this.address.city }) + .onChange((value) => { + this.address.city = value; + }) + + TextInput({ text: this.address.zip.toString() }) + .onChange((value) => { + const result = parseInt(value); + this.address.zip = isNaN(result) ? 0 : result; + }) + + if (this.phones.length > 0) { + ForEach(this.phones, + (phone, index) => { + TextInput({ text: phone }) + .width(150) + .onChange((value) => { + console.log(`${index}. ${value} value has changed`) + this.phones[index] = value; }) - if (this.selectedPersonIndex() != -1) { - Text("Delete Contact") - .onClick(() => { - let index = this.selectedPersonIndex(); - console.log(`delete contact at index ${index}`); - - // 删除当前联系人 - this.addrBook.contacts.splice(index, 1); - - // 删除当前selectedPerson,选中态前移一位 - index = (index < this.addrBook.contacts.length) ? index : index - 1; - - // 如果contract被删除完,则设置me为选中态 - this.selectedPerson = (index >= 0) ? this.addrBook.contacts[index] : this.addrBook.me; - }) - } - } - - } + }, + (phone, index) => `${index}-${phone}` + ) } - } - - @Component - struct AddressBookView { - @ObjectLink me: Person; - @ObjectLink contacts: ObservedArray; - @State selectedPerson: Person = undefined; - - aboutToAppear() { - this.selectedPerson = this.me; - } - - build() { - Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start }) { - Text("Me:") - PersonView({ person: this.me, phones: this.me.phones, selectedPerson: this.$selectedPerson }) - - Divider().height(8) - - ForEach(this.contacts, - contact => { - PersonView({ person: contact, phones: contact.phones, selectedPerson: this.$selectedPerson }) - }, - contact => contact.id_ - ) - - Divider().height(8) - - Text("Edit:") - PersonEditView({ - selectedPerson: this.$selectedPerson, - name: this.selectedPerson.name, - address: this.selectedPerson.address, - phones: this.selectedPerson.phones + + Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { + Text("Save Changes") + .onClick(() => { + // 将本地副本更新的值赋值给指向父组件selectedPerson的引用 + // 避免创建新对象,在现有属性上进行修改 + this.selectedPerson.name = this.name; + this.selectedPerson.address.street = this.address.street + this.selectedPerson.address.city = this.address.city + this.selectedPerson.address.zip = this.address.zip + this.phones.forEach((phone: string, index: number) => { + this.selectedPerson.phones[index] = phone + }); }) + if (this.selectedPersonIndex() != -1) { + Text("Delete Contact") + .onClick(() => { + let index = this.selectedPersonIndex(); + console.log(`delete contact at index ${index}`); + + // 删除当前联系人 + this.addrBook.contacts.splice(index, 1); + + // 删除当前selectedPerson,选中态前移一位 + index = (index < this.addrBook.contacts.length) ? index : index - 1; + + // 如果contract被删除完,则设置me为选中态 + this.selectedPerson = (index >= 0) ? this.addrBook.contacts[index] : this.addrBook.me; + }) } - .borderStyle(BorderStyle.Solid).borderWidth(5).borderColor(0xAFEEEE).borderRadius(5) } + } - - @Entry - @Component - struct PageEntry { - @Provide addrBook: AddressBook = new AddressBook( - new Person("Gigi", "Itamerenkatu 9", 180, "Helsinki", ["+358441234567", "+35891234567", "+49621234567889"]), - [ - new Person("Oly", "Itamerenkatu 9", 180, "Helsinki", ["+358449876543", "+3589456789"]), - new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["+358509876543", "+358910101010"]), - new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["+358400908070", "+35894445555"]), - ]); - - build() { - Column() { - AddressBookView({ me: this.addrBook.me, contacts: this.addrBook.contacts, selectedPerson: this.addrBook.me }) - } - } + } + } + + @Component + struct AddressBookView { + @ObjectLink me: Person; + @ObjectLink contacts: ObservedArray; + @State selectedPerson: Person = undefined; + + aboutToAppear() { + this.selectedPerson = this.me; + } + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start }) { + Text("Me:") + PersonView({ person: this.me, phones: this.me.phones, selectedPerson: this.$selectedPerson }) + + Divider().height(8) + + ForEach(this.contacts, + contact => { + PersonView({ person: contact, phones: contact.phones, selectedPerson: this.$selectedPerson }) + }, + contact => contact.id_ + ) + + Divider().height(8) + + Text("Edit:") + PersonEditView({ + selectedPerson: this.$selectedPerson, + name: this.selectedPerson.name, + address: this.selectedPerson.address, + phones: this.selectedPerson.phones + }) } - ``` \ No newline at end of file + .borderStyle(BorderStyle.Solid).borderWidth(5).borderColor(0xAFEEEE).borderRadius(5) + } + } + + @Entry + @Component + struct PageEntry { + @Provide addrBook: AddressBook = new AddressBook( + new Person("Gigi", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********", "18*********"]), + [ + new Person("Oly", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), + new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), + new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["18*********", "18*********"]), + ]); + + build() { + Column() { + AddressBookView({ me: this.addrBook.me, contacts: this.addrBook.contacts, selectedPerson: this.addrBook.me }) + } + } + } +``` \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md b/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md index 9a27960acb511a7f413ae331ab862193f9b2abf1..4a2397a02a144d9965c9d6c1e452311412cd97c0 100644 --- a/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md +++ b/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @@ -180,7 +180,9 @@ struct Child { - 如果调用的是router.replaceUrl,则当前Index页面被销毁,执行的生命周期流程将变为:Index onPageHide --> MyComponent aboutToDisappear --> Child aboutToDisappear。上文已经提到,组件的销毁是从组件树上直接摘下子树,所以先调用父组件的aboutToDisappear,再调用子组件的aboutToDisAppear,然后执行初始化新页面的生命周期流程。 -- 点击返回按钮,触发页面生命周期Index onBackPress。最小化应用或者应用进入后台,触发Index onPageHide。这两个状态下应用都没有被销毁,所以并不会执行组件的aboutToDisappear 。应用回到前台,执行Index onPageShow。 +- 点击返回按钮,触发页面生命周期Index onBackPress,且触发返回一个页面后会导致当前Index页面被销毁。 + +- 最小化应用或者应用进入后台,触发Index onPageHide。当前Index页面没有被销毁,所以并不会执行组件的aboutToDisappear。应用回到前台,执行Index onPageShow。 - 退出应用,执行Index onPageHide --> MyComponent aboutToDisappear --> Child aboutToDisappear。 diff --git a/zh-cn/application-dev/quick-start/arkts-prop.md b/zh-cn/application-dev/quick-start/arkts-prop.md index acea773b145bcb930519ae0ed4ab1f32da28a5fc..341ab9509d03acfce605e8f6dfa29906bfb46e6c 100644 --- a/zh-cn/application-dev/quick-start/arkts-prop.md +++ b/zh-cn/application-dev/quick-start/arkts-prop.md @@ -374,7 +374,7 @@ struct Index { 如果图书馆有一本图书和两位用户,每位用户都可以将图书标记为已读,此标记行为不会影响其它读者用户。从代码角度讲,对\@Prop图书对象的本地更改不会同步给图书馆组件中的\@State图书对象。 -在此示例中,图书类可以使用\@Observed装饰器,但不是必须的,只有在嵌套结构时需要此装饰器。这一点我们会在[从父组件中的\@State数组项到\@Prop class类型的同步](#从父组件中的\@State数组项到\@Prop class类型的同步)说明。 +在此示例中,图书类可以使用\@Observed装饰器,但不是必须的,只有在嵌套结构时需要此装饰器。这一点我们会在[从父组件中的@State数组项到@Prop class类型的同步](#从父组件中的state数组项到prop-class类型的同步)说明。 ```ts diff --git a/zh-cn/application-dev/quick-start/figures/chooseStageModel.png b/zh-cn/application-dev/quick-start/figures/chooseStageModel.png index b7dd96b6b7c5d2afd241e0c6fd9ee91977692115..dffb66f40999c09e20edfa1b094aee8e62952f61 100644 Binary files a/zh-cn/application-dev/quick-start/figures/chooseStageModel.png and b/zh-cn/application-dev/quick-start/figures/chooseStageModel.png differ diff --git a/zh-cn/application-dev/quick-start/figures/deleteRuntimeOS.png b/zh-cn/application-dev/quick-start/figures/deleteRuntimeOS.png index 8087b03be057d646ae6e3348abae73c1e840b781..c75770635cb1bb3ab927968afe97664ff8c2ebde 100644 Binary files a/zh-cn/application-dev/quick-start/figures/deleteRuntimeOS.png and b/zh-cn/application-dev/quick-start/figures/deleteRuntimeOS.png differ diff --git a/zh-cn/application-dev/quick-start/figures/project.png b/zh-cn/application-dev/quick-start/figures/project.png new file mode 100644 index 0000000000000000000000000000000000000000..e1f2db2da30489fa3c4b64587db203a2ef173533 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/project.png differ diff --git a/zh-cn/application-dev/quick-start/figures/secondPage.png b/zh-cn/application-dev/quick-start/figures/secondPage.png index 2c08d85c610336a71b06407800603ed5c101606d..efca1a48d38136c2a09c3d36e6b4a8b54785cf70 100644 Binary files a/zh-cn/application-dev/quick-start/figures/secondPage.png and b/zh-cn/application-dev/quick-start/figures/secondPage.png differ 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 abdbd30f2daaa8a3e70878246c8660d832f48638..adc7bbb143679b67904b1a0050659f06e203969f 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 @@ -1,11 +1,11 @@ # 构建第一个ArkTS应用(Stage模型) -> **说明:** -> -> 请使用**DevEco Studio V3.0.0.900 Beta3**及更高版本。 -> -> 为确保运行效果,本文以使用**DevEco Studio 4.0 Beta1**版本为例,点击[此处](../../release-notes/OpenHarmony-v4.0-beta1.md#配套关系)获取下载链接。 +> **说明:** +> +> 请使用**DevEco Studio V3.0.0.900 Beta3**及更高版本。 +> +> 为确保运行效果,本文以使用**DevEco Studio 4.0 Beta2**版本为例,点击[此处](../../release-notes/OpenHarmony-v4.0-beta2.md#配套关系)获取下载链接。 ## 创建ArkTS工程 @@ -23,6 +23,8 @@ 3. 进入配置工程界面,**Compile SDK**选择“**3.1.0(API 9)**”,其他参数保持默认设置即可。 + 其中**Node**用来配置当前工程运行的Node.js版本,可选择使用已有的Node.js或下载新的Node.js版本。 + ![chooseStageModel](figures/chooseStageModel.png) > **说明:** @@ -42,11 +44,12 @@ ![targetSdkVersion](figures/targetSdkVersion.png) -7. 将其他各模块级别的build-profile.json5文件中targets字段下的runtimeOS配置删除。 +7. 在模块级**entry > build-profile.json5**文件中,将targets字段下的runtimeOS配置删除。 ![deleteRuntimeOS](figures/deleteRuntimeOS.png) -8. 单击Sync Now完成同步。此时工程对应为API 10的OpenHarmony工程。 +8. 单击**Sync Now**完成同步。此时工程对应为API 10的OpenHarmony工程。 + ### 创建API 9的OpenHarmony工程 @@ -58,6 +61,8 @@ 3. 进入配置工程界面,**Compile SDK**选择“**3.1.0(API 9)**”,其他参数保持默认设置即可。 + 其中**Node**用来配置当前工程运行的Node.js版本,可选择使用已有的Node.js或下载新的Node.js版本。 + ![chooseStageModel](figures/chooseStageModel.png) > **说明:** @@ -69,18 +74,18 @@ 4. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 -5. 在模块级**entry > build-profile.json5**文件中,将targets中的**runtimeOS**配置为“**OpenHarmony**”。 +5. 在模块级**entry > build-profile.json5**文件中,将targets中的runtimeOS配置为“OpenHarmony”。 -6. 单击Sync Now完成同步。此时工程对应为API 9的OpenHarmony工程。 +6. 单击**Sync Now**完成同步。此时工程对应为API 9的OpenHarmony工程。 ## ArkTS工程目录结构(Stage模型)(API 10) -![zh-cn_image_0000001364054489](figures/zh-cn_image_0000001364054489.png) +![project](figures/project.png) - **AppScope > app.json5**:应用的全局配置信息。 -- **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 +- **entry**:OpenHarmony工程模块,编译构建生成一个HAP包。 - **src > main > ets**:用于存放ArkTS源码。 - **src > main > ets > entryability**:应用/服务的入口。 @@ -101,13 +106,14 @@ - **hvigorfile.ts**:应用级编译构建任务脚本。 + ## ArkTS工程目录结构(Stage模型)(API 9) -![zh-cn_image_0000001364054489](figures/zh-cn_image_0000001364054489.png) +![project](figures/project.png) - **AppScope > app.json5**:应用的全局配置信息。 -- **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 +- **entry**:OpenHarmony工程模块,编译构建生成一个HAP包。 - **src > main > ets**:用于存放ArkTS源码。 - **src > main > ets > entryability**:应用/服务的入口。 diff --git a/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md index 083638d33287c0464b22dac0ee85808b92a95ef8..0d4553fa5cd806134a393ca02af5e895a864e760 100644 --- a/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -651,7 +651,7 @@ interface Identity { interface Contact { email: string - phone: string + phoneNumber: string } type Employee = Identity & Contact @@ -667,7 +667,7 @@ interface Identity { interface Contact { email: string - phone: string + phoneNumber: string } interface Employee extends Identity, Contact {} @@ -3174,8 +3174,8 @@ class Person { const person: Person = { name: "John", age: 30, - email: "john@example.com", - phone: 1234567890, + email: "***@example.com", + phoneNumber: 18*********, } ``` @@ -3186,18 +3186,18 @@ class Person { name: string age: number email: string - phone: number + phoneNumber: number - constructor(name: string, age: number, email: string, phone: number) { + constructor(name: string, age: number, email: string, phoneNumber: number) { this.name = name this.age = age this.email = email - this.phone = phone + this.phoneNumber = phoneNumber } } function main(): void { - const person: Person = new Person("John", 30, "john@example.com", 1234567890) + const person: Person = new Person("John", 30, "***@example.com", 18*********) } ``` diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 9597a88ad7f29b3c919f72c3fb29206e9e086167..2508b074a9c31fbc6b451e30074990d2afc0d880 100644 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -198,22 +198,23 @@ - UI界面 - [@ohos.animator (动画)](js-apis-animator.md) - [@ohos.arkui.componentSnapshot (组件截图)](js-apis-arkui-componentSnapshot.md) + - [@ohos.arkui.componentUtils (componentUtils)](js-apis-arkui-componentUtils.md) - [@ohos.arkui.dragController (DragController)](js-apis-arkui-dragController.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.inspector (布局回调)](js-apis-arkui-inspector.md) + - [ @ohos.arkui.performanceMonitor (性能监测)](js-apis-arkui-performancemonitor.md) - [@ohos.arkui.UIContext (UIContext)](js-apis-arkui-UIContext.md) - [@ohos.arkui.componentUtils (componentUtils)](js-apis-arkui-componentUtils.md) - [@ohos.curves (插值计算)](js-apis-curve.md) - [@ohos.font (注册自定义字体)](js-apis-font.md) - [@ohos.matrix4 (矩阵变换)](js-apis-matrix4.md) + - [@ohos.measure (文本计算)](js-apis-measure.md) - [@ohos.mediaquery (媒体查询)](js-apis-mediaquery.md) - [@ohos.pluginComponent (PluginComponentManager)](js-apis-plugincomponent.md) - [@ohos.promptAction (弹窗)](js-apis-promptAction.md) - [@ohos.router (页面路由)](js-apis-router.md) - - [@ohos.measure (文本计算)](js-apis-measure.md) - [@ohos.uiAppearance (用户界面外观)](js-apis-uiappearance.md) - - [ @ohos.arkui.performanceMonitor (性能监测)](js-apis-arkui-performancemonitor.md) - + - 图形图像 - [@ohos.animation.windowAnimationManager (窗口动画管理)](js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (窗口扩展能力)](js-apis-application-windowExtensionAbility.md) @@ -228,12 +229,15 @@ - [webgl2 (WebGL2)](js-apis-webgl2.md) - 媒体 + - [@ohos.app.ability.MediaControlExtensionAbility (播控扩展能力)](js-apis-app-ability-MediaControlExtensionAbility.md) - [@ohos.multimedia.audio (音频管理)](js-apis-audio.md) - [@ohos.multimedia.avsession (媒体会话管理)](js-apis-avsession.md) - [@ohos.multimedia.camera (相机管理)](js-apis-camera.md) - [@ohos.multimedia.image (图片处理)](js-apis-image.md) - [@ohos.multimedia.media (媒体服务)](js-apis-media.md) - [@ohos.multimedia.systemSoundManager (系统声音管理)](js-apis-systemSoundManager.md) + - application + - [MediaControlExtensionContext (播控扩展能力上下文)](js-apis-inner-application-MediaControlExtensionContext.md) - multimedia - [ringtonePlayer (铃声播放器)](js-apis-inner-multimedia-ringtonePlayer.md) diff --git a/zh-cn/application-dev/reference/apis/common_event/commonEvent-account.md b/zh-cn/application-dev/reference/apis/common_event/commonEvent-account.md index d054bd8600f056a764d5a5872d212e153ec045d2..8874a4e86d322e2fdebabdc33575b13aecf08747 100644 --- a/zh-cn/application-dev/reference/apis/common_event/commonEvent-account.md +++ b/zh-cn/application-dev/reference/apis/common_event/commonEvent-account.md @@ -64,23 +64,23 @@ ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN (预留事件,暂未支持)表示分布式帐号登录成功的动作。 -- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGIN +- 值: common.event.DISTRIBUTED_ACCOUNT_LOGIN - 订阅者所需权限: 无 ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT (预留事件,暂未支持)表示分布式帐号登出成功的动作。 -- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOUT +- 值: common.event.DISTRIBUTED_ACCOUNT_LOGOUT - 订阅者所需权限: 无 ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID (预留事件,暂未支持)表示分布式帐号token令牌无效的动作。 -- 值: usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID +- 值: common.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID - 订阅者所需权限: 无 ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF (预留事件,暂未支持)表示分布式帐号注销的动作。 -- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOFF +- 值: common.event.DISTRIBUTED_ACCOUNT_LOGOFF - 订阅者所需权限: 无 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-animator.md b/zh-cn/application-dev/reference/apis/js-apis-animator.md index b8c7db9204ff2d698da536c69a1836e33300b1fa..12c3103acfdc89c237cad32d6125caaa6ab350c6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-animator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-animator.md @@ -257,7 +257,7 @@ animatorResult.onrepeat = function() { | 名称 | 类型 | 必填 | 说明 | | ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | duration | number | 是 | 动画播放的时长,单位毫秒。 | -| easing | string | 是 | 动画插值曲线,仅支持以下可选值:
"linear":动画线性变化。
"ease":动画开始和结束时的速度较慢,cubic-bezier(0.25、0.1、0.25、1.0)。
"ease-in":动画播放速度先慢后快,cubic-bezier(0.42, 0.0, 1.0, 1.0)。
"ease-out":动画播放速度先快后慢,cubic-bezier(0.0, 0.0, 0.58, 1.0)。
"ease-in-out":动画播放速度先加速后减速,cubic-bezier(0.42, 0.0, 0.58, 1.0)。
"fast-out-slow-in":标准曲线,cubic-bezier(0.4,0.0,0.2,1.0)。
"linear-out-slow-in":减速曲线,cubic-bezier(0.0,0.0,0.2,1.0)。
"friction":阻尼曲线,cubic-bezier(0.2, 0.0, 0.2, 1.0)。
"extreme-deceleration":急缓曲线,cubic-bezier(0.0, 0.0, 0.0, 1.0)。
"rhythm":节奏曲线,cubic-bezier(0.7, 0.0, 0.2, 1.0)。
"sharp":锐利曲线,cubic-bezier(0.33, 0.0, 0.67, 1.0)。
"smooth":平滑曲线,cubic-bezier(0.4, 0.0, 0.4, 1.0)。
cubic-bezier(x1, y1, x2, y2):在三次贝塞尔函数中定义动画变化过程,入参的值必须处于0-1之间。
steps(number, step-position):阶梯曲线。number必须设置,支持的类型为int。step-position参数可选,支持设置start或end,默认值为end。 | +| easing | string | 是 | 动画插值曲线,仅支持以下可选值:
"linear":动画线性变化。
"ease":动画开始和结束时的速度较慢,cubic-bezier(0.25、0.1、0.25、1.0)。
"ease-in":动画播放速度先慢后快,cubic-bezier(0.42, 0.0, 1.0, 1.0)。
"ease-out":动画播放速度先快后慢,cubic-bezier(0.0, 0.0, 0.58, 1.0)。
"ease-in-out":动画播放速度先加速后减速,cubic-bezier(0.42, 0.0, 0.58, 1.0)。
"fast-out-slow-in":标准曲线,cubic-bezier(0.4,0.0,0.2,1.0)。
"linear-out-slow-in":减速曲线,cubic-bezier(0.0,0.0,0.2,1.0)。
"friction":阻尼曲线,cubic-bezier(0.2, 0.0, 0.2, 1.0)。
"extreme-deceleration":急缓曲线,cubic-bezier(0.0, 0.0, 0.0, 1.0)。
"rhythm":节奏曲线,cubic-bezier(0.7, 0.0, 0.2, 1.0)。
"sharp":锐利曲线,cubic-bezier(0.33, 0.0, 0.67, 1.0)。
"smooth":平滑曲线,cubic-bezier(0.4, 0.0, 0.4, 1.0)。
"cubic-bezier(x1,y1,x2,y2)":三次贝塞尔曲线,x1、x2的值必须处于0-1之间。例如"cubic-bezier(0.42,0.0,0.58,1.0)"。
"steps(number,step-position)":阶梯曲线,number必须设置,为正整数,step-position参数可选,支持设置start或end,默认值为end。例如"steps(3,start)"。 | | delay | number | 是 | 动画延时播放时长,单位毫秒,设置为0时,表示不延时。 | | fill | "none" \| "forwards" \| "backwards" \| "both" | 是 | 动画执行后是否恢复到初始状态,动画执行后,动画结束时的状态(在最后一个关键帧中定义)将保留。
"none":在动画执行之前和之后都不会应用任何样式到目标上。
"forwards":在动画结束后,目标将保留动画结束时的状态(在最后一个关键帧中定义)。
"backwards":动画将在animation-delay期间应用第一个关键帧中定义的值。当animation-direction为"normal"或"alternate"时应用from关键帧中的值,当animation-direction为"reverse"或"alternate-reverse"时应用to关键帧中的值。
"both":动画将遵循forwards和backwards的规则,从而在两个方向上扩展动画属性。 | | direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | 是 | 动画播放模式。
"normal": 动画正向循环播放。
"reverse": 动画反向循环播放。
"alternate":动画交替循环播放,奇数次正向播放,偶数次反向播放。
"alternate-reverse":动画反向交替循环播放,奇数次反向播放,偶数次正向播放。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..1661fe67effbfaa8ff976ce97974f527350b9e18 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md @@ -0,0 +1,17 @@ +# @ohos.app.ability.MediaControlExtensionAbility (播控扩展能力) + +MediaControlExtensionAbility模块提供播放控制的扩展能力,继承自[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md),无其他新增接口。在实际开发时,需要开发者实现父类中的接口,使用UIExtensiton的生命周期和能力,不支持直接调用基类。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +> **说明:** +> +> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块接口仅可在Stage模型下使用。 +> - 本模块接口为系统接口。 + +## 导入模块 + +```js +import MediaControlExtensionAbility from @ohos.app.ability.MediaControlExtensionAbility; +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index 48bf88b532e925535f83eac60ac14ebb54b91d7a..35a26c0cbbfc5ef6343808250471d7ca7ff7c2e4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -202,7 +202,7 @@ onContinue(wantParam: { [key: string]: Object }): AbilityConstant.OnContinueResu | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| wantParam | {[key: string]: any} | 是 | want相关参数。 | +| wantParam | {[key: string]: Object} | 是 | want相关参数。 | **返回值:** @@ -289,7 +289,7 @@ onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Objec | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | 是 | 回调保存状态的原因。 | -| wantParam | {[key: string]: any} | 是 | want相关参数。 | +| wantParam | {[key: string]: Object} | 是 | want相关参数。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..2b2332422f59af67c269335da4894a7f42f4af26 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md @@ -0,0 +1,84 @@ +# @ohos.app.ability.UIExtensionAbility (带界面扩展能力基类) + +UIExtensionAbility是特定场景下带界面扩展能力的基类,继承自[ExtensionAbility](js-apis-app-ability-extensionAbility.md),新增带界面扩展能力相关的属性和方法。不支持开发者直接继承该基类。 + +> **说明:** +> +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口仅可在Stage模型下使用。 + +## 导入模块 + +```ts +import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility'; +``` + +## 属性 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| context | [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md) | 是 | 否 | 上下文。 | + +## UIExtensionAbility.onCreate + +onCreate(): void + +UIExtensionAbility创建时回调,执行初始化业务逻辑操作。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## UIExtensionAbility.onSessionCreate + +onSessionCreate(want: Want, session: UIExtensionContentSession): void + +当UIExtensionAbility界面内容对象创建后调用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | 是 | 当前UIExtensionAbility的Want类型信息,包括ability名称、bundle名称等。 | +| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | UIExtensionAbility界面内容相关信息。 | + +## UIExtensionAbility.onSessionDestroy + +onSessionDestroy(session: UIExtensionContentSession): void + +当UIExtensionAbility界面内容对象销毁后调用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | UIExtensionAbility界面内容相关信息。 | + +## UIExtensionAbility.onForeground + +onForeground(): void; + +UIExtensionAbility生命周期回调,当UIExtensionAbility从后台转到前台时触发。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## UIExtensionAbility.onBackground + +onBackground(): void; + +UIExtensionAbility生命周期回调,当UIExtensionAbility从前台转到后台时触发。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +## UIExtensionAbility.onDestroy + +onDestroy(): void | Promise<void>; + +UIExtensionAbility生命周期回调,在销毁时回调,执行资源清理等操作。 +在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md new file mode 100644 index 0000000000000000000000000000000000000000..ea086e8f5f5c8587372f655f002c75654ae7d225 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md @@ -0,0 +1,211 @@ +# @ohos.app.ability.UIExtensionContentSession (带界面扩展能力界面操作类) + +UIExtensionContentSession是[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)加载界面内容时创建的实例对象,当UIExtensionComponent控件拉起指定的UIExtensionAbility时,UIExtensionAbility会创建UIExtensionContentSession对象,并通过[onSessionCreate](js-apis-app-ability-uiExtensionAbility.md#uiextensionabilityonsessioncreate)回调传递给开发者。一个UIExtensionComponent控件对应一个UIExtensionContentSession对象,提供界面加载,结果通知等方法。每个UIExtensionAbility的UIExtensionContentSession之间互不影响,可以各自进行操作。 + +> **说明:** +> +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口仅可在Stage模型下使用。 + +## 导入模块 + +```ts +import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; +``` + +## UIExtensionContentSession.sendData + +sendData(data: { [key: string]: Object }): void + +发送数据给UIExtensionComponent控件。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| data | {[key: string]: Object} | 是 | 发送给UIExtensionComponent控件的数据参数。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContentSession.setReceiveDataCallback + +setReceiveDataCallback(callback: (data: { [key: string]: Object }) => void): void + +设置从UIExtensionComponent控件接收数据的回调方法。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | (data: { [key: string]: Object }) => void | 是 | 接收数据的回调方法。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContentSession.loadContent + +loadContent(path: string, storage?: LocalStorage): Promise<void> + +为当前UIExtensionComponent控件对应的窗口加载与LocalStorage相关联的具体页面内容。 + +**系统能力:** SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | 是 | 设置加载页面的路径。 | +| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContentSession.terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +停止UIExtensionContentSession对应的窗口界面对象(callback形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | 是 | 停止UIExtensionContentSession对应的窗口界面对象的回调函数。 | + +## UIExtensionContentSession.terminateSelf + +terminateSelf(): Promise<void>; + +停止UIExtensionContentSession对应的窗口界面对象(promise形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 停止UIExtensionContentSession对应的窗口界面对象的回调函数。 | + +## UIExtensionContentSession.terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; + +停止UIExtensionContentSession对应的窗口界面对象,并将结果返回给UIExtensionComponent控件(callback形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给UIExtensionComponent控件的信息。 | +| callback | AsyncCallback<void> | 是 | callback形式返回停止结果。 | + +## UIExtensionContentSession.terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult): Promise<void>; + +停止UIExtensionContentSession对应的窗口界面对象,并将结果返回给UIExtensionComponent控件(promise形式)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 是 | 返回给UIExtensionComponent控件的信息。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | promise形式返回停止结果。 | + +## UIExtensionContentSession.setWindowBackgroundColor + +setWindowBackgroundColor(color: string): void + +设置UIExtensionAbility加载界面的背景色。该接口需要在[loadContent()](#uiextensioncontentsessionloadcontent)调用生效后使用。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| color | string | 是 | 需要设置的背景色,为十六进制RGB或ARGB颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContentSession.setWindowPrivacyMode + +setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void> + +设置窗口是否为隐私模式,使用Promise异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。 + +**系统能力:** SystemCapability.Ability.AbilityRuntime.AbilityCore + +**需要权限:** ohos.permission.PRIVACY_WINDOW + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ------- | -- | ----------------------------------------------------- | +| isPrivacyMode | boolean | 是 | 窗口是否为隐私模式。true表示模式开启;false表示模式关闭。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------ | +| Promise<void> | 无返回结果的Promise对象。 | + +## UIExtensionContentSession.setWindowPrivacyMode + +setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void + +设置窗口是否为隐私模式,使用callback异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。 + +**系统能力:** SystemCapability.Ability.AbilityRuntime.AbilityCore + +**需要权限:** ohos.permission.PRIVACY_WINDOW + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ------------------------- | -- | ------------------------------------------------------ | +| isPrivacyMode | boolean | 是 | 窗口是否为隐私模式。true表示模式开启;false表示模式关闭。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md index 6fa259689307bde652829c8f2bb91c0643dc6952..c2983efcd2fe9963b150a5bcd53ab9bae5ffc760 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -1202,95 +1202,6 @@ try { } ``` -## getRunningFormInfos10+ - -getRunningFormInfos(callback: AsyncCallback<Array<formInfo.RunningFormInfo>>, hostBundleName?: string): void - -获取设备上正在运行的所有非临时卡片信息。使用callback异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<formInfo.RunningFormInfo>> | 是 | 回调函数。获取设备上指定应用为卡片使用方的当前卡片信息成功,error为undefined,data为查询到的卡片信息。| -| hostBundleName | string | 否 | 指定要查询的卡片使用方名称,指定后会仅返回该卡片使用方下正在运行的非临时卡片信息。
缺省时,返回设备上所有正在运行的非临时卡片信息。 | - -**错误码:** -以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - -| 错误码ID | 错误信息 | -| -------- | -------- | -| 16500050 | An IPC connection error happened. | -| 16500060 | A service connection error happened, please try again later. || - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; - -try { - formHost.getRunningFormInfos((error, data) => { - if (error) { - console.error(`error, code: ${error.code}, message: ${error.message}`); - } else { - console.log('formHost getRunningFormInfos, data: ${JSON.stringify(data)}'); - } - }, 'com.example.ohos.formjsdemo'); -} catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); -} -``` - -## getRunningFormInfos10+ - -getRunningFormInfos(hostBundleName?: string): Promise<Array<formInfo.RunningFormInfo>> - -获取设备上正在运行的所有非临时卡片信息。使用Promise异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| hostBundleName | string | 否 | 指定要查询的卡片使用方名称,指定后会仅返回该卡片使用方下正在运行的非临时卡片信息。
缺省时,返回设备上所有正在运行的非临时卡片信息。 | - -**返回值:** - -| 类型 | 说明 | -| :----------------------------------------------------------- | :---------------------------------- | -| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Promise对象,返回查询到的卡片信息。 | - -**错误码:** -以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - -| 错误码ID | 错误信息 | -| -------- | -------- | -| 16500050 | An IPC connection error happened. | -| 16500060 | A service connection error happened, please try again later. || - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; - -try { - formHost.getRunningFormInfos('com.example.ohos.formjsdemo').then((data) => { - console.log('formHost getRunningFormInfos, data: ${JSON.stringify(data)}'); - }).catch((error) => { - console.error(`error, code: ${error.code}, message: ${error.message}`); - }); -} catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); -} -``` - ## deleteInvalidForms deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void @@ -1583,138 +1494,6 @@ let callback = function(formId) { formHost.off('formUninstall', callback); ``` -## on('formAdd')10+ - - on(type: 'formAdd', observerCallback: Callback<formInfo.RunningFormInfo>, bundleName?: string): void - -订阅卡片新增事件。使用callback异步回调,返回当前新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| type | string | 是 | 填写'formAdd',表示卡片新增事件。 | -| callback | Callback<formInfo.RunningFormInfo> | 是 | 回调函数。返回新增卡片的RunningFormInfo。 | -| bundleName | string | 否 | 指定订阅卡片使用方包的bundleName。缺省则订阅所有卡片使用方的卡片新增事件。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('a new form added, data: ${JSON.stringify(data)'); -} - -formHost.on('formAdd', callback); -formHost.on('formAdd', callback, bundleName); -``` - -## off('formAdd')10+ - - off(type: "formAdd", observerCallback?: Callback<formInfo.RunningFormInfo>, bundleName?: string): void - -取消订阅卡片新增事件。使用callback异步回调,返回当前新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| type | string | 是 | 填写'formAdd',表示卡片新增事件。 | -| callback | Callback<formInfo.RunningFormInfo> | 否 | 回调函数。返回卡片RunningFormInfo。缺省时,表示注销对应已注册事件回调。
需与对应on('formAdd')的callback一致。| -| bundleName | string | 否 | 指定订阅卡片使用方包的bundleName。
填写该参数时,与注册时填写bundleName的on接口对应。
缺省则订阅所有卡片使用方的卡片删除事件,与注册时未填写bundleName的on接口相对应。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('a new form added, data: ${JSON.stringify(data)'); -} - -formHost.off('formAdd', callback); -formHost.off('formAdd', callback, bundleName); -``` -> **说明:** -> on('formAdd', callback)与off('formAdd', callback)相对应; -> on('formAdd', callback, bundleName)与off('formAdd', callback, bundleName)相对应; -> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 - -## on('formRemove')10+ - - on(type: 'formRemove', observerCallback: Callback<formInfo.RunningFormInfo>, bundleName?: string): void - -订阅卡片删除事件。使用callback异步回调,返回当前删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| type | string | 是 | 填写'formRemove',表示卡片删除事件。 | -| callback | Callback<formInfo.RunningFormInfo> | 是 | 回调函数。返回删除卡片的RunningFormInfo。 | -| bundleName | string | 否 | 指定订阅卡片使用方包的bundleName。缺省则订阅所有卡片使用方的卡片删除事件。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('a new form added, data: ${JSON.stringify(data)'); -} - -formHost.on('formRemove', callback); -formHost.on('formRemove', callback, bundleName); -``` - -## off('formRemove')10+ - -off(type: "formRemove", observerCallback?: Callback<formInfo.RunningFormInfo>, bundleName?: string): void - -取消订阅卡片删除事件。使用callback异步回调,返回当前删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| type | string | 是 | 填写'formRemove',表示卡片删除事件。 | -| callback | Callback<formInfo.RunningFormInfo> | 否 | 回调函数。返回卡片RunningFormInfo。缺省时,表示注销对应已注册事件回调。
需与对应on('formRemove')的callback一致。| -| bundleName | string | 否 | 指定订阅卡片使用方包的bundleName。
填写该参数时,与注册时填写bundleName的on接口对应。
缺省则订阅所有卡片使用方的卡片删除事件,与注册时未填写bundleName的on接口相对应。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('a new form added, data: ${JSON.stringify(data)'); -} - -formHost.off('formRemove', callback); -formHost.off('formRemove', callback, bundleName); -``` -> **说明:** -> on('formRemove', callback)与off('formRemove', callback)相对应; -> on('formRemove', callback, bundleName)与off('formRemove', callback, bundleName)相对应; -> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 - ## notifyFormsVisible notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void @@ -2221,350 +2000,3 @@ try { console.error(`catch error, code: ${error.code}, message: ${error.message}`); } ``` - -## getRunningFormInfosByFilter10+ - -getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter): Promise<Array<formInfo.RunningFormInfo>> - -根据提供方信息查询卡片已有的使用方列表信息。使用Promise异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | --------------- | ---- | -------------------------------- | -| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | 是 | 卡片提供方应用信息。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md#RunningFormInfo)>> | Promise对象,返回查询到的使用方列表信息。 | - -**错误码:** - -以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - -| 错误码ID | 错误信息 | -| -------- | -------- | -| 201 | Permissions denied. | -| 202 | The application is not a system application. | -| 401 | If the input parameter is not valid parameter. | -| 16500050 | An IPC connection error happened. | -| 16500100 | Failed to obtain the configuration information. | -| 16501000 | An internal functional error occurred. | - - -```ts -import formHost from '@ohos.app.form.formHost'; - -let formInstanceFilter = { - bundleName: "com.example.formprovide", - abilityName: "EntryFormAbility", - formName: "widget", - moduleName: "entry" -} -try { - formHost.getRunningFormInfosByFilter(formInstanceFilter).then(data1 => { - console.info('formHost getRunningFormInfosByFilter return err :'); - }).catch((error) => { - console.error(`error, code: ${error.code}, message: ${error.message}`); - }); -} catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); -} -``` - -## getRunningFormInfosByFilter10+ - -getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback<Array<formInfo.RunningFormInfo>>): void - -根据提供方信息查询卡片已有的使用方列表信息。使用callback异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | --------------- | ---- | -------------------------------- | -| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | 是 | 卡片提供方应用信息。 | -| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到的使用方列表信息,error为undefined,data为查询到的使用方列表信息;否则为错误对象。 | - -**错误码:** - -以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - -| 错误码ID | 错误信息 | -| -------- | -------- | -| 201 | Permissions denied. | -| 202 | The application is not a system application. | -| 401 | If the input parameter is not valid parameter. | -| 16500050 | An IPC connection error happened. | -| 16500100 | Failed to obtain the configuration information. | -| 16501000 | An internal functional error occurred. | - - -```ts -import formHost from '@ohos.app.form.formHost'; - -let formInstanceFilter = { - bundleName: "com.example.formprovide", - abilityName: "EntryFormAbility", - formName: "widget", - moduleName: "entry" -} -try { - formHost.getRunningFormInfosByFilter(formInstanceFilter,(error, data) => { - if (error) { - console.error(`error, code: ${error.code}, message: ${error.message}`); - } else { - console.log('formHost getRunningFormInfosByFilter, data: ${JSON.stringify(data)}'); - } - }); -} catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); -} -``` - -## getRunningFormInfoById10+ - -getRunningFormInfoById(formId: string): Promise<formInfo.RunningFormInfo> - - -根据formId查询卡片已有的使用方列表信息。使用Promise异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | --------------- | ---- | -------------------------------- | -| formId | string | 是 | 卡片标识。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Promise对象,返回查询到的使用方列表信息。 | - -**错误码:** - -以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - -| 错误码ID | 错误信息 | -| -------- | -------- | -| 201 | Permissions denied. | -| 202 | The application is not a system application. | -| 401 | If the input parameter is not valid parameter. | -| 16500050 | An IPC connection error happened. | -| 16500100 | Failed to obtain the configuration information. | -| 16501000 | An internal functional error occurred. | - - -```ts -import formHost from '@ohos.app.form.formHost'; -let formId = '12400633174999288'; -try { - formHost.getRunningFormInfoById(formId).then(data1 => { - console.info('formHost getRunningFormInfoById return err :'); - }).catch((error) => { - console.error(`error, code: ${error.code}, message: ${error.message}`); - }); -} catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); -} -``` - -## getRunningFormInfoById10+ - -getRunningFormInfoById(formId: string, callback: AsyncCallback<formInfo.RunningFormInfo>): void - -根据提供方信息查询卡片已有的使用方列表信息。使用callback异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | --------------- | ---- | -------------------------------- | -| formId | string | 是 | 卡片标识。 | -| callback | AsyncCallback<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | 是 | 回调函数。返回查询到的使用方列表信息,error为undefined,data为查询到的使用方列表信息;否则为错误对象。 | - -**错误码:** - -以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - -| 错误码ID | 错误信息 | -| -------- | -------- | -| 201 | Permissions denied. | -| 202 | The application is not a system application. | -| 401 | If the input parameter is not valid parameter. | -| 16500050 | An IPC connection error happened. | -| 16500100 | Failed to obtain the configuration information. | -| 16501000 | An internal functional error occurred. | - -```ts -import formHost from '@ohos.app.form.formHost'; - -let formId = '12400633174999288'; -try { - formHost.getRunningFormInfoById(formId,(error, data) => { - if (error) { - console.error(`error, code: ${error.code}, message: ${error.message}`); - } else { - console.log('formHost getRunningFormInfoById, data: ${JSON.stringify(data)}'); - } - }); -} catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); -} -``` - -## on('notifyVisible')10+ - - on(type: 'notifyVisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void - -订阅通知卡片可见的事件。 - -​触发通知卡片可见场景为:调用notifyVisibleForms接口通知对应卡片可见性变更为可见状态 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 仅允许填写'notifyVisible',表示订阅通知卡片可见的事件。 | -| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回订阅通知卡片可见的RunningFormInfo。 | -| bundleName | string | 否 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('form change visibility, data: ${JSON.stringify(data)'); -} - -formHost.on('notifyVisible', callback); -formHost.on('notifyVisible', callback, bundleName); -``` - -## off('notifyVisible')10+ - - off(type: "notifyVisible", observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void - -取消订阅通知卡片可见的事件。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 仅允许填写'notifyVisible',表示取消订阅通知卡片为可见的事件。 | -| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 否 | 入参,注册时注册进去的callback。缺省时,表示注销对应已注册订阅的回调。
需与对应on('notifyVisible')的callback一致。 | -| bundleName | string | 否 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。
填写该参数时,与注册时填写bundleName的on接口对应。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('form change visibility, data: ${JSON.stringify(data)'); -} - -formHost.off('notifyVisible', callback); -formHost.off('notifyVisible', callback, bundleName); -``` - -> **说明:** -> on('notifyVisible', callback)与off('notifyVisible', callback)相对应; -> on('notifyVisible', callback, bundleName)与off('notifyVisible', callback, bundleName)相对应; -> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 - - - -## on('notifyInvisible')10+ - - on(type: 'notifyInvisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void - -订阅通知卡片不可见的事件。 - -​触发通知卡片不可见场景为:调用notifyInvisibleForms接口通知对应卡片可见性变更为不可见状态 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 仅允许填写'notifyInvisible',表示订阅卡片不可见的事件。 | -| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回订阅通知卡片不可见的RunningFormInfo。 | -| bundleName | string | 否 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。 | - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('form change invisibility, data: ${JSON.stringify(data)'); -} - -formHost.on('notifyInvisible', callback); -formHost.on('notifyInvisible', callback, bundleName); -``` - -## off('notifyInvisible')10+ - - off(type: "notifyInvisible", observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>, bundleName?: string): void - -取消订阅通知卡片不可见事件。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 仅允许填写'notifyInvisible',表示卡片可见性变更为不可见。 | -| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 否 | 入参,注册时注册进去的callback。缺省时,表示注销对应已注册事件回调。
需与对应on('notifyInvisible')的callback一致。 | -| bundleName | string | 否 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。
填写该参数时,与注册时填写bundleName的on接口对应。
| - -**示例:** - -```ts -import formHost from '@ohos.app.form.formHost'; -let bundleName = 'ohos.samples.FormApplication'; -let callback = function(data) { - console.log('form change invisibility, data: ${JSON.stringify(data)'); -} - -formHost.off('notifyInvisible', callback); -formHost.off('notifyInvisible', callback, bundleName); -``` - -> **说明:** -> on('notifyInvisible', callback)与off('notifyInvisible', callback)相对应; -> on('notifyInvisible', callback, bundleName)与off('notifyInvisible', callback, bundleName)相对应; -> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md new file mode 100644 index 0000000000000000000000000000000000000000..7a3ed1f4cd871af1563f3c97d046cd1ad8d49f10 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md @@ -0,0 +1,699 @@ +# @ohos.app.form.formObserver (formObserver) + +formObserver模块提供了卡片监听方相关接口的能力,包括对同一用户下安装的卡片新增、删除、可见性变化事件的订阅和取消订阅,获取正在运行的卡片信息等。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口均为系统接口。 + +## 导入模块 + +```ts +import formObserver from '@ohos.app.form.formObserver'; +``` + +## on('formAdd') + + on(type: 'formAdd', observerCallback: Callback<formInfo.RunningFormInfo>): void + +订阅卡片新增事件。使用callback异步回调,返回当前新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| type | string | 是 | 填写'formAdd',表示卡片新增事件。 | +| callback | Callback<formInfo.RunningFormInfo> | 是 | 回调函数。返回新增卡片的RunningFormInfo。 | + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let callback = function(data) { + console.log('a new form added, data: ${JSON.stringify(data)'); +} + +formObserver.on('formAdd', callback); +``` + +## on('formAdd') + + on(type: 'formAdd', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void + +订阅卡片新增事件。使用callback异步回调,返回指定卡片使用方应用新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| type | string | 是 | 填写'formAdd',表示卡片新增事件。 | +| bundleName | string | 是 | 指定订阅卡片使用方包的bundleName。缺省则订阅所有卡片使用方的卡片新增事件。 | +| callback | Callback<formInfo.RunningFormInfo> | 是 | 回调函数。返回新增卡片的RunningFormInfo。 | + + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('a new form added, data: ${JSON.stringify(data)'); +} + +formObserver.on('formAdd', bundleName, callback); +``` + +## off('formAdd') + + off(type: "formAdd", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void + +取消订阅卡片新增事件。使用callback异步回调,返回当前新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| type | string | 是 | 填写'formAdd',表示卡片新增事件。 | +| bundleName | string | 否 | 指定订阅卡片使用方包的bundleName。
填写该参数时,与注册时填写bundleName的on接口对应。
缺省则订阅所有卡片使用方的卡片删除事件,与注册时未填写bundleName的on接口相对应。 | +| callback | Callback<formInfo.RunningFormInfo> | 否 | 回调函数。返回卡片RunningFormInfo。缺省时,表示注销对应已注册事件回调。
需与对应on('formAdd')的callback一致。| + + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('a new form added, data: ${JSON.stringify(data)'); +} + +formObserver.off('formAdd', callback); +formObserver.off('formAdd', bundleName, callback); +``` +> **说明:** +> on('formAdd', callback)与off('formAdd', callback)相对应; +> on('formAdd', bundleName, callback)与off('formAdd', bundleName, callback)相对应; +> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 + +## on('formRemove') + + on(type: 'formRemove', observerCallback: Callback<formInfo.RunningFormInfo>): void + +订阅卡片删除事件。使用callback异步回调,返回当前删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| type | string | 是 | 填写'formRemove',表示卡片删除事件。 | +| callback | Callback<formInfo.RunningFormInfo> | 是 | 回调函数。返回删除卡片的RunningFormInfo。 | + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let callback = function(data) { + console.log('form deleted, data: ${JSON.stringify(data)'); +} + +formObserver.on('formRemove', callback); +``` + +## on('formRemove') + + on(type: 'formRemove', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void + +订阅卡片删除事件。使用callback异步回调,返回指定卡片使用方应用被删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| type | string | 是 | 填写'formRemove',表示卡片删除事件。 | +| bundleName | string | 是 | 指定订阅卡片使用方包的bundleName。缺省则订阅所有卡片使用方的卡片删除事件。 | +| callback | Callback<formInfo.RunningFormInfo> | 是 | 回调函数。返回删除卡片的RunningFormInfo。 | + + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form deleted, data: ${JSON.stringify(data)'); +} + +formObserver.on('formRemove', bundleName, callback); +``` + +## off('formRemove') + +off(type: "formRemove", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void + +取消订阅卡片删除事件。使用callback异步回调,返回当前删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| type | string | 是 | 填写'formRemove',表示卡片删除事件。 | +| bundleName | string | 否 | 指定订阅卡片使用方包的bundleName。
填写该参数时,与注册时填写bundleName的on接口对应。
缺省则订阅所有卡片使用方的卡片删除事件,与注册时未填写bundleName的on接口相对应。 | +| callback | Callback<formInfo.RunningFormInfo> | 否 | 回调函数。返回卡片RunningFormInfo。缺省时,表示注销对应已注册事件回调。
需与对应on('formRemove')的callback一致。| + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('a new form added, data: ${JSON.stringify(data)'); +} + +formObserver.off('formRemove', callback); +formObserver.off('formRemove', bundleName, callback); +``` +> **说明:** +> on('formRemove', callback)与off('formRemove', callback)相对应; +> on('formRemove', bundleName, callback)与off('formRemove', bundleName, callback)相对应; +> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 + +## on('notifyVisible') + + on(type: 'notifyVisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + +订阅通知卡片可见的事件。 + +​触发通知卡片可见场景为:调用notifyVisibleForms接口通知对应卡片可见性变更为可见状态 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 仅允许填写'notifyVisible',表示订阅通知卡片可见的事件。 | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回订阅通知卡片可见的RunningFormInfo。 | + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let callback = function(data) { + console.log('form change visibility, data: ${JSON.stringify(data)'); +} + +formObserver.on('notifyVisible', callback); +``` + +## on('notifyVisible') + + on(type: 'notifyVisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + +订阅通知卡片可见的事件。 + +​触发通知卡片可见场景为:调用notifyVisibleForms接口通知对应卡片可见性变更为可见状态 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 仅允许填写'notifyVisible',表示订阅通知卡片可见的事件。 | +| bundleName | string | 是 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。 | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回订阅通知卡片可见的RunningFormInfo。 | + + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change visibility, data: ${JSON.stringify(data)'); +} + +formObserver.on('notifyVisible', bundleName, callback); +``` + +## off('notifyVisible') + + off(type: "notifyVisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + +取消订阅通知卡片可见的事件。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 仅允许填写'notifyVisible',表示取消订阅通知卡片为可见的事件。 | +| bundleName | string | 否 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。
填写该参数时,与注册时填写bundleName的on接口对应。 | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 否 | 入参,注册时注册进去的callback。缺省时,表示注销对应已注册订阅的回调。
需与对应on('notifyVisible')的callback一致。 | + + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change visibility, data: ${JSON.stringify(data)'); +} + +formObserver.off('notifyVisible', callback); +formObserver.off('notifyVisible', bundleName, callback); +``` + +> **说明:** +> on('notifyVisible', callback)与off('notifyVisible', callback)相对应; +> on('notifyVisible', bundleName, callback)与off('notifyVisible', bundleName, callback)相对应; +> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 + +## on('notifyInvisible') + + on(type: 'notifyInvisible', observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + +订阅通知卡片不可见的事件。 + +​触发通知卡片不可见场景为:调用notifyInvisibleForms接口通知对应卡片可见性变更为不可见状态 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 仅允许填写'notifyInvisible',表示订阅卡片不可见的事件。 | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回订阅通知卡片不可见的RunningFormInfo。 | + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let callback = function(data) { + console.log('form change invisibility, data: ${JSON.stringify(data)'); +} + +formObserver.on('notifyInvisible', callback); +``` + + +## on('notifyInvisible') + + on(type: 'notifyInvisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + +订阅通知卡片不可见的事件。 + +​触发通知卡片不可见场景为:调用notifyInvisibleForms接口通知对应卡片可见性变更为不可见状态 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 仅允许填写'notifyInvisible',表示订阅卡片不可见的事件。 | +| bundleName | string | 是 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。 | +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回订阅通知卡片不可见的RunningFormInfo。 | + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change invisibility, data: ${JSON.stringify(data)'); +} + +formObserver.on('notifyInvisible', bundleName, callback); +``` + +## off('notifyInvisible') + + off(type: "notifyInvisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void + +取消订阅通知卡片不可见事件。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 仅允许填写'notifyInvisible',表示卡片可见性变更为不可见。 | +| bundleName | string | 否 | 指定卡片使用方的bundleName,用于订阅卡片在该使用方的可见状态变更事件。
填写该参数时,与注册时填写bundleName的on接口对应。
| +| callback | Callback <Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 否 | 入参,注册时注册进去的callback。缺省时,表示注销对应已注册事件回调。
需与对应on('notifyInvisible')的callback一致。 | + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let bundleName = 'ohos.samples.FormApplication'; +let callback = function(data) { + console.log('form change invisibility, data: ${JSON.stringify(data)'); +} + +formObserver.off('notifyInvisible', callback); +formObserver.off('notifyInvisible', bundleName, callback); +``` + +> **说明:** +> on('notifyInvisible', callback)与off('notifyInvisible', callback)相对应; +> on('notifyInvisible', bundleName, callback)与off('notifyInvisible', bundleName, callback)相对应; +> 订阅(on)只能由自己对应的取消订阅接口(off)取消。 + + +## getRunningFormInfos + +getRunningFormInfos(callback: AsyncCallback<Array<formInfo.RunningFormInfo>>, hostBundleName?: string): void + +获取设备上正在运行的所有非临时卡片信息。使用callback异步回调。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<formInfo.RunningFormInfo>> | 是 | 回调函数。获取设备上指定应用为卡片使用方的当前卡片信息成功,error为undefined,data为查询到的卡片信息。| +| hostBundleName | string | 否 | 指定要查询的卡片使用方名称,指定后会仅返回该卡片使用方下正在运行的非临时卡片信息。
缺省时,返回设备上所有正在运行的非临时卡片信息。 | + +**错误码:** +以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. || + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; + +try { + formObserver.getRunningFormInfos((error, data) => { + if (error) { + console.error(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formObserver getRunningFormInfos, data: ${JSON.stringify(data)}'); + } + }, 'com.example.ohos.formjsdemo'); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getRunningFormInfos + +getRunningFormInfos(hostBundleName?: string): Promise<Array<formInfo.RunningFormInfo>> + +获取设备上正在运行的所有非临时卡片信息。使用Promise异步回调。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------- | +| hostBundleName | string | 否 | 指定要查询的卡片使用方名称,指定后会仅返回该卡片使用方下正在运行的非临时卡片信息。
缺省时,返回设备上所有正在运行的非临时卡片信息。 | + +**返回值:** + +| 类型 | 说明 | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | Promise对象,返回查询到的卡片信息。 | + +**错误码:** +以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. || + +**示例:** + +```ts +import formObserver from '@ohos.app.form.formObserver'; + +try { + formObserver.getRunningFormInfos('com.example.ohos.formjsdemo').then((data) => { + console.log('formObserver getRunningFormInfos, data: ${JSON.stringify(data)}'); + }).catch((error) => { + console.error(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getRunningFormInfosByFilter + +getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter): Promise<Array<formInfo.RunningFormInfo>> + +根据提供方信息查询卡片已有的使用方列表信息。使用Promise异步回调。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------- | ---- | -------------------------------- | +| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | 是 | 卡片提供方应用信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md#RunningFormInfo)>> | Promise对象,返回查询到的使用方列表信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + + +```ts +import formObserver from '@ohos.app.form.formObserver'; + +let formInstanceFilter = { + bundleName: "com.example.formprovide", + abilityName: "EntryFormAbility", + formName: "widget", + moduleName: "entry" +} +try { + formObserver.getRunningFormInfosByFilter(formInstanceFilter).then(data1 => { + console.info('formObserver getRunningFormInfosByFilter return err :'); + }).catch((error) => { + console.error(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getRunningFormInfosByFilter + +getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback<Array<formInfo.RunningFormInfo>>): void + +根据提供方信息查询卡片已有的使用方列表信息。使用callback异步回调。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------- | ---- | -------------------------------- | +| formProviderFilter | [formInfo.FormProviderFilter](js-apis-app-form-formInfo.md#formProviderFilter) | 是 | 卡片提供方应用信息。 | +| callback | AsyncCallback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到的使用方列表信息,error为undefined,data为查询到的使用方列表信息;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + + +```ts +import formObserver from '@ohos.app.form.formObserver'; + +let formInstanceFilter = { + bundleName: "com.example.formprovide", + abilityName: "EntryFormAbility", + formName: "widget", + moduleName: "entry" +} +try { + formObserver.getRunningFormInfosByFilter(formInstanceFilter,(error, data) => { + if (error) { + console.error(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formObserver getRunningFormInfosByFilter, data: ${JSON.stringify(data)}'); + } + }); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getRunningFormInfoById + +getRunningFormInfoById(formId: string): Promise<formInfo.RunningFormInfo> + + +根据formId查询卡片已有的使用方列表信息。使用Promise异步回调。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------- | ---- | -------------------------------- | +| formId | string | 是 | 卡片标识。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | Promise对象,返回查询到的使用方列表信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + + +```ts +import formObserver from '@ohos.app.form.formObserver'; +let formId = '12400633174999288'; +try { + formObserver.getRunningFormInfoById(formId).then(data1 => { + console.info('formObserver getRunningFormInfoById return err :'); + }).catch((error) => { + console.error(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getRunningFormInfoById + +getRunningFormInfoById(formId: string, callback: AsyncCallback<formInfo.RunningFormInfo>): void + +根据提供方信息查询卡片已有的使用方列表信息。使用callback异步回调。 + +**需要权限**:ohos.permission.OBSERVE_FORM_RUNNING + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------- | ---- | -------------------------------- | +| formId | string | 是 | 卡片标识。 | +| callback | AsyncCallback<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)> | 是 | 回调函数。返回查询到的使用方列表信息,error为undefined,data为查询到的使用方列表信息;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + +```ts +import formObserver from '@ohos.app.form.formObserver'; + +let formId = '12400633174999288'; +try { + formObserver.getRunningFormInfoById(formId,(error, data) => { + if (error) { + console.error(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formObserver getRunningFormInfoById, data: ${JSON.stringify(data)}'); + } + }); +} catch(error) { + console.error(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md index 6eca3fc7b20924a6f6af6db1cd42a385a89606cc..f483bde4cbcf7d38e91f6a05814d31db24dd3690 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -610,7 +610,7 @@ getRectangleById(id: string): componentUtils.ComponentInfo | 类型 | 说明 | | -------------------------------------------------------- | ------------------------------------------------ | -| [ComponentInfo](js-apis-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 | +| [ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-avsession.md b/zh-cn/application-dev/reference/apis/js-apis-avsession.md index ff43b8196f407b4362f434c84766af1f614be8ed..ccd28aba9b7daf8f3aedda65d7e0063950588415 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-avsession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-avsession.md @@ -1038,7 +1038,7 @@ startCastDeviceDiscovery(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功并开始搜索,err为undefined,否则返回错误对象。 | **示例:** @@ -1057,7 +1057,7 @@ avSession.startCastDeviceDiscovery(function (err) { startCastDeviceDiscovery(filter: number, callback: AsyncCallback\): void -开始设备搜索发现。结果通过callback异步回调方式返回。 +指定过滤条件,开始设备搜索发现。结果通过callback异步回调方式返回。 **系统能力:** SystemCapability.Multimedia.AVSession.AVCast @@ -1068,7 +1068,7 @@ startCastDeviceDiscovery(filter: number, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------- | | filter | number | 是 | 进行设备发现的过滤条件,由ProtocolType的组合而成 | -| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功并开始搜索,err为undefined,否则返回错误对象。 | **示例:** @@ -1103,7 +1103,7 @@ startCastDeviceDiscovery(filter?: number): Promise\ **返回值:** | 类型 | 说明 | | -------------- | ----------------------------- | -| Promise\ | Promise对象。当开始设备搜索成功,无返回结果,否则返回错误对象。 | +| Promise\ | Promise对象。当命令发送成功并开始搜索,无返回结果,否则返回错误对象。 | **示例:** @@ -1130,7 +1130,7 @@ stopCastDeviceDiscovery(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当成功停止搜索,err为undefined,否则返回错误对象。 | **示例:** @@ -1159,7 +1159,7 @@ stopCastDeviceDiscovery(): Promise\ | 类型 | 说明 | | -------------- | ----------------------------- | -| Promise\ | Promise对象。当停止搜索成功,无返回结果,否则返回错误对象。 | +| Promise\ | Promise对象。当成功停止搜索,无返回结果,否则返回错误对象。 | **示例:** @@ -1186,7 +1186,7 @@ setDiscoverable(enable: boolean, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------- | | enable | boolean | 是 | 是否允许本设备被发现. true: 允许被发现, false:不允许被发现 | -| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当设置成功,err为undefined,否则返回错误对象。 | **示例:** @@ -1221,7 +1221,7 @@ setDiscoverable(enable: boolean): Promise\ | 类型 | 说明 | | -------------- | ----------------------------- | -| Promise\ | Promise对象。当停止搜索成功,无返回结果,否则返回错误对象。 | +| Promise\ | Promise对象。当设置成功,无返回结果,否则返回错误对象。 | **示例:** @@ -1247,7 +1247,7 @@ on(type: 'deviceAvailable', callback: (device: OutputDeviceInfo) => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持事件`'deviceAvailable'`,有设备更新时触发回调。 | +| type | string | 是 | 事件回调类型,支持事件`'deviceAvailable'`,有设备被发现时触发回调。 | | callback | (device: OutputDeviceInfo) => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则返回错误对象。 | **错误码:** @@ -1432,8 +1432,8 @@ startCasting(session: SessionToken, device: OutputDeviceInfo, callback: AsyncCal | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------- | | session | [SessionToken](#sessiontoken) | 是 | 会话令牌。SessionToken表示单个token。 | -| device | [OutputDeviceInfo](#outputdeviceinfo10) | 是 | 设备相关信息 | -| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | +| device | [OutputDeviceInfo](#outputdeviceinfo10) | 是 | 设备相关信息 | +| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功并启动投播,err为undefined,否则返回错误对象。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -1503,7 +1503,7 @@ startCasting(session: SessionToken, device: OutputDeviceInfo): Promise\ | 类型 | 说明 | | -------------- | ----------------------------- | -| Promise\ | Promise对象。当停止搜索成功,无返回结果,否则返回错误对象。 | +| Promise\ | Promise对象。当命令发送成功并启动投播,无返回结果,否则返回错误对象。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -1563,7 +1563,7 @@ stopCasting(session: SessionToken, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------- | | session | [SessionToken](#sessiontoken) | 是 | 会话令牌。SessionToken表示单个token。 | -| callback | AsyncCallback\ | 是 | 回调函数。当命令发送成功,err为undefined,否则返回错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当成功结束投播,err为undefined,否则返回错误对象。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -1624,7 +1624,7 @@ stopCasting(session: SessionToken): Promise\ | 类型 | 说明 | | -------------- | ----------------------------- | -| Promise\ | Promise对象。当停止搜索成功,无返回结果,否则返回错误对象。 | +| Promise\ | Promise对象。当成功结束投播,无返回结果,否则返回错误对象。 | **错误码:** 错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -2917,7 +2917,7 @@ on(type:'playNext', callback: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件是` 'playNext'`,当播放下一首命令被发送到会话时,触发该事件回调。 | +| type | string | 是 | 事件回调类型,支持的事件是`'playNext'`,当播放下一首命令被发送到会话时,触发该事件回调。 | | callback | callback: () => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则为错误对象。 | **错误码:** @@ -2948,7 +2948,7 @@ on(type:'playPrevious', callback: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件是` 'playPrevious'`当播放上一首命令被发送到会话时,触发该事件回调。 | +| type | string | 是 | 事件回调类型,支持的事件是`'playPrevious'`当播放上一首命令被发送到会话时,触发该事件回调。 | | callback | callback: () => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则为错误对象。 | **错误码:** @@ -3010,7 +3010,7 @@ on(type:'rewind', callback: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持的事件是` 'rewind'`,当快退命令被发送到会话时,触发该事件回调。 | +| type | string | 是 | 事件回调类型,支持的事件是`'rewind'`,当快退命令被发送到会话时,触发该事件回调。 | | callback | callback: () => void | 是 | 回调函数。当监听事件注册成功,err为undefined,否则为错误对象。 | **错误码:** @@ -3318,7 +3318,7 @@ off(type: 'pause', callback?: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- | -| type | string | 是 | 关闭对应的监听事件,支持的事件是` 'pause'`。 | +| type | string | 是 | 关闭对应的监听事件,支持的事件是`'pause'`。 | | callback | callback: () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** @@ -3405,7 +3405,7 @@ off(type: 'playPrevious', callback?: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- | -| type | string | 是 | 关闭对应的监听事件,支持的事件是` 'playPrevious'`。 | +| type | string | 是 | 关闭对应的监听事件,支持的事件是`'playPrevious'`。 | | callback | callback: () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** @@ -3434,7 +3434,7 @@ off(type: 'fastForward', callback?: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- | -| type | string | 是 | 关闭对应的监听事件,支持的事件是` 'fastForward'`。 | +| type | string | 是 | 关闭对应的监听事件,支持的事件是`'fastForward'`。 | | callback | callback: () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** @@ -3463,7 +3463,7 @@ off(type: 'rewind', callback?: () => void): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------- | -| type | string | 是 | 关闭对应的监听事件,支持的事件是` 'rewind'`。 | +| type | string | 是 | 关闭对应的监听事件,支持的事件是`'rewind'`。 | | callback | callback: () => void | 否 | 回调函数。当监听事件取消成功,err为undefined,否则返回错误对象。
该参数为可选参数,若不填写该参数,则认为取消所有相关会话的事件监听。 | **错误码:** @@ -3758,7 +3758,7 @@ stopCasting(): Promise\ | 类型 | 说明 | | -------------- | ----------------------------- | -| Promise\ | Promise对象。当停止投播索成功,无返回结果,否则返回错误对象。 | +| Promise\ | Promise对象。当成功结束投播,无返回结果,否则返回错误对象。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -3881,7 +3881,7 @@ aVCastController.setDisplaySurface(function (err, value) { getAVPlaybackState(callback: AsyncCallback\): void -设备建立连接后,获取投播控制器。结果通过callback异步回调方式返回。 +获取当前的远端播放状态。结果通过callback异步回调方式返回。 **系统能力:** SystemCapability.Multimedia.AVSession.AVCast @@ -3889,7 +3889,7 @@ getAVPlaybackState(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[[AVPlaybackState](#avplaybackstate10))\> | 是 | 回调函数,返回投播控制器实例。 | +| callback | AsyncCallback<[[AVPlaybackState](#avplaybackstate10)\> | 是 | 回调函数,返回远端播放状态。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -3922,7 +3922,7 @@ getAVPlaybackState(): Promise\; | 类型 | 说明 | | --------- | ------------------------------------------------------------ | -| Promise<[AVPlaybackState](#avplaybackstate10)\> | Promise对象。返回投播控制器实例。 | +| Promise<[AVPlaybackState](#avplaybackstate10)\> | Promise对象。返回远端播放状态。。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -4289,7 +4289,7 @@ aVCastController.getCurrentItem(function (err, value) { getCurrentItem(): Promise\ -结束投播。结果通过Promise异步回调方式返回。 +获取当前投播的资源信息。结果通过Promise异步回调方式返回。 **系统能力:** SystemCapability.Multimedia.AVSession.AVCast @@ -4392,8 +4392,8 @@ on(type: 'mediaItemChange', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持事件`'mediaItemChange'`:当播放状态变化时,触发该事件。 | -| callback | (state: [AVQueueItem](#avqueueitem10)) => void | 是 | 回调函数,参数AVQueueItem是d当前正在播放的媒体内容。 | +| type | string | 是 | 事件回调类型,支持事件`'mediaItemChange'`:当播放的媒体内容变化时,触发该事件。 | +| callback | (state: [AVQueueItem](#avqueueitem10)) => void | 是 | 回调函数,参数AVQueueItem是当前正在播放的媒体内容。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -4506,7 +4506,7 @@ on(type: 'playPrevious', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 事件回调类型,支持事件`'playPrevious'`:当播放下一首状态变化时,触发该事件。 | +| type | string | 是 | 事件回调类型,支持事件`'playPrevious'`:当播放上一首状态变化时,触发该事件。 | | callback | Callback\ | 是 | 回调函数 | **错误码:** @@ -4671,7 +4671,7 @@ on(type: 'error', callback: ErrorCallback): void **错误码:** -以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-media.md)。 +以下错误码的详细介绍请参见[媒体服务错误码](../errorcodes/errorcode-media.md)。 | 错误码ID | 错误信息 | | -------- | --------------------- | @@ -4707,7 +4707,7 @@ off(type: 'error'): void **错误码:** -以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-media.md)。 +以下错误码的详细介绍请参见[媒体服务错误码](../errorcodes/errorcode-media.md)。 | 错误码ID | 错误信息 | | -------- | --------------------- | @@ -4726,7 +4726,7 @@ aVCastController.off('error') ## ConnectionState10+ -播放设备的类别枚举。 +连接状态枚举。 **系统能力:** SystemCapability.Multimedia.AVSession.Core @@ -4831,7 +4831,7 @@ aVCastController.off('error') ## AVCastCategory10+ -播放设备的类别枚举。 +投播的类别枚举。 **系统能力:** SystemCapability.Multimedia.AVSession.AVCast @@ -4861,7 +4861,7 @@ aVCastController.off('error') | 名称 | 类型 | 必填 | 说明 | | ---------- | -------------- | ---- | ---------------------- | -| castCategory | AVCastCategory | 是 | 播放设备的类别 | +| castCategory | AVCastCategory | 是 | 投播的类别。 | | deviceId | string | 是 | 播放设备的ID。 | | deviceName | string | 是 | 播放设备的名称。 | | deviceType | DeviceType | 是 | 播放设备的类型。 | @@ -4955,7 +4955,7 @@ avSession.createController(currentAVSession.sessionId).then((controller) => { getAVPlaybackState(callback: AsyncCallback\): void -设备建立连接后,获取投播控制器。结果通过callback异步回调方式返回。 +获取当前的远端播放状态。结果通过callback异步回调方式返回。 **系统能力:** SystemCapability.Multimedia.AVSession.Core @@ -4963,7 +4963,7 @@ getAVPlaybackState(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | --------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[[AVPlaybackState](#avplaybackstate10))\> | 是 | 回调函数,返回投播控制器实例。 | +| callback | AsyncCallback<[[AVPlaybackState](#avplaybackstate10)\> | 是 | 回调函数,返回远端播放状态。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 @@ -4990,7 +4990,7 @@ avsessionController.getAVPlaybackState(function (err, state) { getAVPlaybackState(): Promise\; -获取当前的远端播放状态。结果通过callback异步回调方式返回。 +获取当前的远端播放状态。结果通过Promise异步回调方式返回。 **系统能力:** SystemCapability.Multimedia.AVSession.Core @@ -4998,7 +4998,7 @@ getAVPlaybackState(): Promise\; | 类型 | 说明 | | --------- | ------------------------------------------------------------ | -| Promise<[AVPlaybackState](#avplaybackstate10)\> | Promise对象。返回投播控制器实例。 | +| Promise<[AVPlaybackState](#avplaybackstate10)\> | Promise对象。返回远端播放状态。 | **错误码:** 以下错误码的详细介绍请参见[媒体会话管理错误码](../errorcodes/errorcode-avsession.md)。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-base.md b/zh-cn/application-dev/reference/apis/js-apis-base.md index 5524b1852b829c838b29798a47b0c15974bd7044..7aed8b1614ce6d14af6dc976212b3598097428a8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-base.md +++ b/zh-cn/application-dev/reference/apis/js-apis-base.md @@ -40,7 +40,7 @@ ErrorCallback\ { 通用回调函数,携带错误参数。 -回调返回的信息为[BusinessError](https://gitee.com/openharmony/docs/pulls/20172/files#businesserror)类型的信息。 +回调返回的信息为[BusinessError](#businesserror)类型的信息。 **系统能力**:SystemCapability.Base @@ -60,7 +60,7 @@ AsyncCallback\ { 通用回调函数,携带错误参数和异步返回值。 -错误参数为[BusinessError](https://gitee.com/openharmony/docs/pulls/20172/files#businesserror)类型的信息。 +错误参数为[BusinessError](#businesserror)类型的信息。 异步返回值的类型由开发者自定义,回调将返回对应类型的信息。 @@ -68,7 +68,7 @@ AsyncCallback\ { | 名称 | 类型 | 必填 | 说明 | | ---- | ------------------------------------------------------------ | ---- | ---------------------------- | -| err | [BusinessError](https://gitee.com/openharmony/docs/pulls/20172/files#businesserror) | 是 | 接口调用失败的公共错误信息。 | +| err | [BusinessError](#businesserror) | 是 | 接口调用失败的公共错误信息。 | | data | T | 是 | 接口调用时的公共回调信息。 | ## BusinessError diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md index 7c8c593a3f36b33d18921666fb3f811fdd03a04c..3035de8a699c537f713d47ef716980a172f82867 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-baseProfile.md @@ -358,7 +358,7 @@ try { off(type: 'connectionStateChange', callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -取消订阅a2dp连接状态变化事件。 +取消订阅连接状态变化事件。 **需要权限**:ohos.permission.ACCESS_BLUETOOTH diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md index d8e3fee736112202464cc18c2b4007f603c6a76d..a9875e133df4292bd4d7108ebc632e75f1151744 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md @@ -1,6 +1,6 @@ # @ohos.bluetooth.ble (蓝牙ble模块) -ble模块提供了访问蓝牙个人区域网相关功能的方法。 +ble模块提供了对蓝牙操作和管理的方法。 > **说明:** > @@ -19,7 +19,7 @@ import ble from '@ohos.bluetooth.ble'; createGattServer(): GattServer -创建Gatt profile实例。 +创建GattServer实例。 **系统能力**:SystemCapability.Communication.Bluetooth.Core。 @@ -27,7 +27,7 @@ createGattServer(): GattServer | 类型 | 说明 | | ----------------------------- | ---------- | -| GattServer | 返回一个JavaScript Gatt服务的实例。 | +| GattServer | 返回一个Gatt服务的实例。 | **示例:** @@ -2210,7 +2210,7 @@ try { off(type: 'BLEMtuChange', callback?: Callback<number>): void -订阅Mtu状态变化事件。 +取消订阅Mtu状态变化事件。 **需要权限**:ohos.permission.ACCESS_BLUETOOTH diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-pan.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-pan.md index 4147424f19186f84e1d3f6610c80ed7a721a63d7..6d9586058b46a8a0238c912130e78ef3be9a25e3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-pan.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-pan.md @@ -1,4 +1,4 @@ -# @ohos.bluetooth.pan (蓝牙socket模块) +# @ohos.bluetooth.pan (蓝牙pan模块) pan模块提供了访问蓝牙个人区域网相关功能的方法。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md index bfe37ba4628f2cc6a74d066251539ebc71781e8a..083fa52fcdb9e85fd007497856702e1bc1f157c6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @@ -4,7 +4,7 @@ > **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 从API Version 9开始,该接口不再维护,推荐使用新接口[bluetoothManager](js-apis-bluetoothManager.md)。 +> 从API Version 9 开始,该接口不再维护,推荐使用[`@ohos.bluetooth.ble`](js-apis-bluetooth-ble.md)等相关profile接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md b/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md index a594e5145f5d5cbdd8913e8ed58c30fd1f4b2d07..caa21c0ebe5057b4d301cf6cbf60e1db202f3129 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetoothManager.md @@ -5,6 +5,7 @@ > **说明:** > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 从API Version 10 开始,该接口不再维护,推荐使用[`@ohos.bluetooth.ble`](js-apis-bluetooth-ble.md)等相关profile接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md index 672f5d26a695a14975c4350b1be5a616e8d87ed5..96c49aecb7488c3f6157fa8fdb44544d0acfa6ef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @@ -99,7 +99,7 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。 | 名称 | 值 | 说明 | |:----------------:|:---:|-----| | FORM | 0 | [FormExtensionAbility](../../application-models/service-widget-overview.md):卡片扩展能力,提供卡片开发能力。 | -| WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md):延时任务扩展能力,允许应用在系统闲时执行实时性不高的任务。 | +| WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler.md):延时任务扩展能力,允许应用在系统闲时执行实时性不高的任务。 | | INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md):输入法扩展能力,用于开发输入法应用。 | | SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md):后台服务扩展能力,提供后台运行并对外提供相应能力。 | | ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md):无障碍服务扩展能力,支持访问与操作前台界面。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-curve.md b/zh-cn/application-dev/reference/apis/js-apis-curve.md index 9172b5325d79a8137dbda13292f3d81b3e2c0c7b..8b4bc5f92e324a09621a44792bb51901577fc3a5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-curve.md +++ b/zh-cn/application-dev/reference/apis/js-apis-curve.md @@ -78,7 +78,7 @@ stepsCurve(count: number, end: boolean): ICurve | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | 是 | 阶梯的数量,需要为正整数。
取值范围:[0, +∞)
**说明:**
设置小于0的值时,按值为0处理。 | +| count | number | 是 | 阶梯的数量,需要为正整数。
取值范围:[1, +∞)
**说明:**
设置小于1的值时,按值为1处理。 | | end | boolean | 是 | 在每个间隔的起点或是终点发生阶跃变化。
-true:在终点发生阶跃变化。
-false:在起点发生阶跃变化。 | **返回值:** @@ -174,7 +174,7 @@ springMotion(response?: number, dampingFraction?: number, overlapDuration?: numb | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ----- | | response | number | 否 | 弹簧自然振动周期,决定弹簧复位的速度。
默认值:0.55
单位:秒
取值范围:[0, +∞)
**说明:**
设置小于0的值时,按默认值0.55处理。 | -| dampingFraction | number | 否 | 阻尼系数。
0表示无阻尼,一直处于震荡状态;
大于0小于1的值为欠阻尼,运动过程中会超出目标值;
等于1为临界阻尼;
大于1为过阻尼,运动过程中逐渐趋于目标值。
默认值:0.825
单位:秒
取值范围:[0, +∞)
**说明:**
设置小于0的值时,按默认值0.55处理。 | +| dampingFraction | number | 否 | 阻尼系数。
0表示无阻尼,一直处于震荡状态;
大于0小于1的值为欠阻尼,运动过程中会超出目标值;
等于1为临界阻尼;
大于1为过阻尼,运动过程中逐渐趋于目标值。
默认值:0.825
单位:秒
取值范围:[0, +∞)
**说明:**
设置小于0的值时,按默认值0.825处理。 | | overlapDuration | number | 否 | 弹性动画衔接时长。发生动画继承时,如果前后两个弹性动画response不一致,response参数会在overlapDuration时间内平滑过渡。
默认值:0
单位:秒
取值范围:[0, +∞)。
**说明:**
设置小于0的值时,按默认值0处理。
弹性动画曲线为物理曲线,[animation](../arkui-ts/ts-animatorproperty.md)、[animateTo](../arkui-ts/ts-explicit-animation.md)中的duration参数不生效,动画持续时间取决于springMotion动画曲线参数和之前的速度。时间不能归一,故不能通过该曲线的interpolate函数获得插值。 | @@ -237,10 +237,10 @@ interpolatingSpring(velocity: number, mass: number, stiffness: number, damping: **参数:** | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ----- | -| velocity | number | 是 | 初始速度。外部因素对弹性动效产生的影响参数,目的是保证对象从之前的运动状态平滑地过渡到弹性动效。该速度是归一化速度,其值等于动画开始时的实际速度除以动画属性改变值。 | -| mass | number | 是 | 质量。弹性系统的受力对象,会对弹性系统产生惯性影响。质量越大,震荡的幅度越大,恢复到平衡位置的速度越慢。 | -| stiffness | number | 是 | 刚度。表示物体抵抗施加的力而形变的程度。刚度越大,抵抗变形的能力越强,恢复到平衡位置的速度越快。 | -| damping | number | 是 | 阻尼。是一个纯数,无真实的物理意义,用于描述系统在受到扰动后震荡及衰减的情形。阻尼越大,弹性运动的震荡次数越少、震荡幅度越小。 | +| velocity | number | 是 | 初始速度。外部因素对弹性动效产生的影响参数,目的是保证对象从之前的运动状态平滑地过渡到弹性动效。该速度是归一化速度,其值等于动画开始时的实际速度除以动画属性改变值。
取值范围:(-∞, +∞) | +| mass | number | 是 | 质量。弹性系统的受力对象,会对弹性系统产生惯性影响。质量越大,震荡的幅度越大,恢复到平衡位置的速度越慢。
取值范围:(0, +∞)
**说明:**
设置的值小于0时,按1处理。 | +| stiffness | number | 是 | 刚度。表示物体抵抗施加的力而形变的程度。刚度越大,抵抗变形的能力越强,恢复到平衡位置的速度越快。
取值范围:(0, +∞)
**说明:**
设置的值小于0时,按1处理。 | +| damping | number | 是 | 阻尼。是一个纯数,无真实的物理意义,用于描述系统在受到扰动后震荡及衰减的情形。阻尼越大,弹性运动的震荡次数越少、震荡幅度越小。
取值范围:(0, +∞)
**说明:**
设置的值小于0时,按1处理。 | **返回值:** 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 cf36172ac70f9180f241988cbfd2ef3468d9f056..dedb6a0dcb8d5c590ca43c0e805be64156e851c1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @@ -1392,90 +1392,6 @@ getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback\10+ - -getThumbnail(uri: string, size: image.Size) : Promise<image.PixelMap> - -通过指定uri和尺寸获取媒体文件的Pixelmap对象,使用Promise异步回调。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**需要权限**:ohos.permission.FILE_ACCESS_MANAGER - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------------------- | ---- | ----------- | -| uri | string | 是 | 媒体文件uri | -| size | [image.Size](js-apis-image.md#size) | 是 | 缩略图尺寸 | - -**返回值:** - -| 类型 | 说明 | -| :---------------------------- | :----------------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | 返回的Pixelmap对象 | - -**示例:** - -```js -// 以媒体库uri为例 -// 示例代码targetUri表示Download目录下某个媒体文件(图片、音频、视频),该uri是对应的fileInfo中uri -// 开发者应根据自己实际获取的uri进行开发 -let targetUri = "file://media/image/100"; -let size = { width: 128, height: 128 }; -try { - // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 - let pixelMap = await fileAccessHelper.getThumbnail(targetUri, size); - let imageInfo = await pixelMap.getImageInfo(); - console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width); - console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height); -} catch (error) { - console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message); -}; -``` - -### getThumbnail10+ - - getThumbnail(uri: string, size: image.Size, callback: AsyncCallback<image.PixelMap>) : void - -通过指定uri和尺寸获取媒体文件的Pixelmap对象,使用callback异步回调。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**需要权限**:ohos.permission.FILE_ACCESS_MANAGER - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | ---- | ------------------ | -| uri | string | 是 | 媒体文件uri | -| size | [image.Size](js-apis-image.md#size) | 是 | 缩略图尺寸 | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 返回的Pixelmap对象 | - -**示例:** - -```js -// 以媒体库uri为例 -// 示例代码targetUri表示Download目录下某个媒体文件(图片、音频、视频),该uri是对应的fileInfo中uri -// 开发者应根据自己实际获取的uri进行开发 -let targetUri = "file://media/image/100"; -let size = { width: 128, height: 128 }; -try { - // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 - fileAccessHelper.getThumbnail(targetUri, size, async(err, pixelMap) => { - if (err) { - console.error("Failed to getThumbnail in async, errCode:" + err.code + ", errMessage:" + err.message); - return; - } - let imageInfo = await pixelMap.getImageInfo(); - console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width); - console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height); - }); -} catch (error) { - console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message); -}; -``` - ### query10+ query(uri:string, metaJson: string) : Promise<string> @@ -1771,6 +1687,3 @@ try { | DATE_MODIFIED | 'date_modified' | 文件的修改日期,例如1665310670 | | RELATIVE_PATH | 'relative_path' | 相对路径,例如Pictures/Screenshots/ | | FILE_SIZE | 'size' | 文件(夹)大小(单位:字节) | -| WIDTH | 'width' | 图像文件的宽度(单位:像素) | -| HEIGHT | 'height' | 图像文件的高度(单位:像素) | -| DURATION | 'duration' | 音频和视频文件的时长(单位:毫秒) | diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md index b2bd9467c2d1dd1754ad5b68160e055f3e00dd74..4c7aee35cdec1bfe58b1ac17ab55b07379f5c36d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -110,11 +110,11 @@ import geoLocationManager from '@ohos.geoLocationManager'; | 名称 | 类型 | 可读|可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。取值范围见[LocationRequestPriority](#locationrequestpriority)的定义。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。取值范围见[LocationRequestScenario](#locationrequestscenario)的定义。 | -| timeInterval | number | 是 | 是 | 表示上报位置信息的时间间隔,单位是秒。取值范围为大于0。 | -| distanceInterval | number | 是 | 是 | 表示上报位置信息的距离间隔。单位是米,取值范围为大于0。 | -| maxAccuracy | number | 是 | 是 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。取值范围为大于0。 | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 是 | 表示优先级信息。当scenario取值为UNSET时,priority参数生效,否则priority参数不生效;当scenario和priority均取值为UNSET时,无法发起定位请求。取值范围见[LocationRequestPriority](#locationrequestpriority)的定义。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 是 | 表示场景信息。当scenario取值为UNSET时,priority参数生效,否则priority参数不生效;当scenario和priority均取值为UNSET时,无法发起定位请求。取值范围见[LocationRequestScenario](#locationrequestscenario)的定义。 | +| timeInterval | number | 是 | 是 | 表示上报位置信息的时间间隔,单位是秒。默认值为1,取值范围为大于等于0。 | +| distanceInterval | number | 是 | 是 | 表示上报位置信息的距离间隔。单位是米,默认值为0,取值范围为大于等于0。 | +| maxAccuracy | number | 是 | 是 | 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。默认值为0,取值范围为大于等于0。 | ## CurrentLocationRequest @@ -426,7 +426,7 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0}; let locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; @@ -470,7 +470,7 @@ off(type: 'locationChange', callback?: Callback<Location>): void ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0}; let locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); }; @@ -1134,7 +1134,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0}; let locationChange = (err, location) => { if (err) { console.log('locationChanger: err=' + JSON.stringify(err)); @@ -1233,7 +1233,7 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> ```ts import geoLocationManager from '@ohos.geoLocationManager'; - let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0}; try { geoLocationManager.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md index 0a32b4464ab06f177c195a68b21b10fd3af841d5..beda73a15b7392155a2c505a5680bfc77ffa21b2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md @@ -175,23 +175,30 @@ getServiceDump(serviceid : number, fd : number, args : Array\) : void ```js import fs from '@ohos.file.fs' import hidebug from '@ohos.hidebug' -import featureAbility from '@ohos.ability.featureAbility' - -let context = featureAbility.getContext(); -context.getFilesDir().then((data) => { - var path = data + "/serviceInfo.txt"; - console.info("output path: " + path); - let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); - var serviceId = 10; - var args = new Array("allInfo"); - try { - hidebug.getServiceDump(serviceId, file.fd, args); - } catch (error) { - console.info(error.code); - console.info(error.message); - } - fs.closeSync(file); -}) +import common from '@ohos.app.ability.common' + +let applicationContext: common.Context; +try { + applicationContext = this.context.getApplicationContext(); +} catch (error) { + console.info(error.code); + console.info(error.message); +} + +var filesDir = applicationContext.filesDir; +var path = filesDir + "/serviceInfo.txt"; +console.info("output path: " + path); +let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); +var serviceId = 10; +var args = new Array("allInfo"); + +try { + hidebug.getServiceDump(serviceId, file.fd, args); +} catch (error) { + console.info(error.code); + console.info(error.message); +} +fs.closeSync(file); ``` ## hidebug.startJsCpuProfiling9+ 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 1df2c8b59fd810ddd23c22d9cbe606cd41d6635e..7a5570c7d1c7edebf7a48527915e63487f4acc64 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-image.md +++ b/zh-cn/application-dev/reference/apis/js-apis-image.md @@ -1698,7 +1698,7 @@ createPixelMapList(options?: DecodingOptions): Promise>; | 类型 | 说明 | | -------------------------------- | --------------------- | -| Promise> | 异步返回PixeMap数组。 | +| Promise> | 异步返回PixelMap数组。 | **示例:** @@ -2423,7 +2423,7 @@ dequeueImage(callback: AsyncCallback\): void ```js creator.dequeueImage((err, img) => { if (err) { - console.info('dequeueImage failded.'); + console.info('dequeueImage failed.'); } console.info('dequeueImage succeeded.'); }); @@ -2967,7 +2967,7 @@ PixelMap的初始化选项。 ## 补充说明 ### SVG标签说明 -从API verison 10开始支持SVG标签,使用版本为(SVG) 1.1,当前支持的标签列表有: +从API version 10开始支持SVG标签,使用版本为(SVG) 1.1,当前支持的标签列表有: - a - circla - clipPath diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index dc96dc3e100a414cc8122682bfc31b23b3981026..43790ea820446d8e932d3848e937907f81ff60f7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,6 +1,8 @@ # AbilityResult -定义Ability被拉起并退出后返回的结果码和数据,可以通过[startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7)获取被拉起Ability退出后返回的AbilityResult对象,被startAbilityForResult拉起的Ability对象可以通过[terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7)返回AbilityResult对象。 +定义Ability被拉起并退出后返回的结果码和数据。 +Stage模型下,可以通过[startAbilityForResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult)获取被拉起Ability退出后返回的AbilityResult对象,被startAbilityForResult拉起的Ability对象可以通过[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)返回AbilityResult对象。 +FA模型下,可以通过[startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7)获取被拉起Ability退出后返回的AbilityResult对象,被startAbilityForResult拉起的Ability对象可以通过[terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7)返回AbilityResult对象。 > **说明:** > @@ -8,6 +10,12 @@ ## 导入模块 +Stage模型下: +```ts +import common from '@ohos.app.ability.common'; +``` + +FA模型下: ```ts import ability from '@ohos.ability.ability'; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-MediaControlExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-MediaControlExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..1e97ece124ae2bd167ac935ae713403bed97660a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-MediaControlExtensionContext.md @@ -0,0 +1,11 @@ +# MediaControlExtensionContext (播控扩展能力上下文) + +MediaControlExtensionContext是[MediaControlExtensionAbility](js-apis-app-ability-MediaControlExtensionAbility.md)的上下文环境,继承自[UIExtensionContext](js-apis-inner-application-uiExtensionContext.md),提供MediaControlExtensionAbility的相关配置信息以及操作UIAbility的方法,如启动UIAbility等。 + +**系统能力:** SystemCapability.Multimedia.AVSession.Core + +> **说明:** +> +> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块接口仅可在Stage模型下使用。 +> - 本模块接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index bbaed20f5590d419c0fbe8c738799524f643e7e1..94730d5e4f6656d9b62e3ef7649c507f184c49f8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -292,7 +292,7 @@ on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback): ** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ---------------- | | type | string | 是 | 监听事件类型,必须为'applicationStateChange'。 | -| callback | [ApplicationStateChangeCallback](#js-apis-app-ability-applicationStateChangeCallback.md) | 是 | 对于该事件监听的回调方法,可以对应用从后台切换到前台,以及前台切换到后台分别定义回调。 | +| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | 是 | 对于该事件监听的回调方法,可以对应用从后台切换到前台,以及前台切换到后台分别定义回调。 | **示例:** @@ -370,7 +370,7 @@ off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------- | ---- | -------------------- | | type | string | 是 | 取消监听事件的类型,必须为'applicationStateChange'。 | -| callback | [ApplicationStateChangeCallback](#js-apis-app-ability-applicationStateChangeCallback.md) | 否 | 对于该事件监听的回调方法,可以对应用从后台切换到前台,以及前台切换到后台分别定义回调。 | +| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | 否 | 对于该事件监听的回调方法,可以对应用从后台切换到前台,以及前台切换到后台分别定义回调。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..f05ce2ccb14a8962de47e77b92af45b19c0bcacc --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiExtensionContext.md @@ -0,0 +1,290 @@ +# UIExtensionContext + +UIExtensionContext是[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)的上下文环境,继承自[ExtensionContext](js-apis-inner-application-extensionContext.md),提供UIExtensionAbility的相关配置信息以及操作UIAbility的方法,如启动UIAbility等。 + +> **说明:** +> +> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块接口仅可在Stage模型下使用。 + +## 导入模块 + +```ts +import common from '@ohos.app.ability.common'; +``` + +## UIExtensionContext.startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void; + +启动Ability(callback形式)。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContext.startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; + +启动Ability(callback形式)。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContext.startAbility + +startAbility(want: Want, options?: StartOptions): Promise<void>; + +启动Ability(promise形式)。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | Promise形式返回启动结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContext.startAbilityForResult + +startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; + +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 执行结果回调函数。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContext.startAbilityForResult + +startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; + +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方,异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方,其它调用方返回异常信息, 异常信息中resultCode为-1。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 执行结果回调函数。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + +## UIExtensionContext.startAbilityForResult + +startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; + +启动一个Ability。Ability被启动后,有如下情况(promise形式): + - 正常情况下可通过调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise形式返回执行结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md index f7fdc512d97872ebf1218007633937637dc7b784..51816f591c664cdb73d6a3c9bdf2fd88c543a857 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md @@ -10,45 +10,45 @@ **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification -| 名称 | 类型 | 必填 | 说明 | -| --------------------- | --------------------------------------------- | --- | -------------------------- | -| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | 是 | 通知内容。 | -| id | number | 否 | 通知ID。 | -| slotType | [SlotType](js-apis-notificationManager.md#slottype) | 否 | 通道类型。 | -| isOngoing | boolean | 否 | 是否进行时通知。 | -| isUnremovable | boolean | 否 | 是否可移除。 | -| deliveryTime | number | 否 | 通知发送时间。 | -| tapDismissed | boolean | 否 | 通知是否自动清除。 | -| autoDeletedTime | number | 否 | 自动清除的时间。 | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | -| extraInfo | {[key: string]: any} | 否 | 扩展参数。 | -| color | number | 否 | 通知背景颜色。预留能力,暂未支持。 | -| colorEnabled | boolean | 否 | 通知背景颜色是否使能。预留能力,暂未支持。 | -| isAlertOnce | boolean | 否 | 设置是否仅有一次此通知提醒。 | -| isStopwatch | boolean | 否 | 是否显示已用时间。 | -| isCountDown | boolean | 否 | 是否显示倒计时时间。 | -| isFloatingIcon | boolean | 否 | 是否显示状态栏图标。 | -| label | string | 否 | 通知标签。 | -| badgeIconStyle | number | 否 | 通知角标类型。预留能力,暂未支持。 | -| showDeliveryTime | boolean | 否 | 是否显示分发时间。 | -| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | 否 | 通知按钮,最多三个按钮。 | -| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知小图标。可选字段,大小不超过30KB。 | -| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知大图标。可选字段,大小不超过30KB。 | -| creatorBundleName | string | 否 | 创建通知的包名。 | -| creatorUid | number | 否 | 创建通知的UID。 | -| creatorPid | number | 否 | 创建通知的PID。 | -| creatorUserId8+ | number | 否 | 创建通知的UserId。 | -| hashCode | string | 否 | 通知唯一标识。 | -| classification | string | 否 | 通知分类。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| groupName8+ | string | 否 | 组通知名称。 | -| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 否 | 通知模板。 | -| isRemoveAllowed10+ | boolean | 否 | 通知是否能被移除。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| source8+ | number | 否 | 通知源。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| distributedOption8+ | [DistributedOptions](#distributedoptions) | 否 | 分布式通知的选项。 | -| deviceId8+ | string | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | -| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationFlags.md#notificationflags) | 否 | 获取NotificationFlags。 | -| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | 当移除通知时,通知将被重定向到的WantAgent实例。 | -| badgeNumber9+ | number | 否 | 应用程序图标上显示的通知数。 | +| 名称 | 类型 | 必填 | 说明 | +| --------------------- | --------------------------------------------- | --- |-----------------------------------------------------------------------| +| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | 是 | 通知内容。 | +| id | number | 否 | 通知ID。 | +| slotType | [SlotType](js-apis-notificationManager.md#slottype) | 否 | 通道类型。 | +| isOngoing | boolean | 否 | 是否进行时通知。 | +| isUnremovable | boolean | 否 | 是否可移除(应用于长时间通知任务上,比如地图、音乐播放;点击通知下方删除按钮无法删除,左滑点击单个删除按钮可删除)。 | +| deliveryTime | number | 否 | 通知发送时间。 | +| tapDismissed | boolean | 否 | 通知是否自动清除。 | +| autoDeletedTime | number | 否 | 自动清除的时间。 | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | +| extraInfo | {[key: string]: any} | 否 | 扩展参数。 | +| color | number | 否 | 通知背景颜色。预留能力,暂未支持。 | +| colorEnabled | boolean | 否 | 通知背景颜色是否使能。预留能力,暂未支持。 | +| isAlertOnce | boolean | 否 | 设置是否仅有一次此通知提醒。 | +| isStopwatch | boolean | 否 | 是否显示已用时间。 | +| isCountDown | boolean | 否 | 是否显示倒计时时间。 | +| isFloatingIcon | boolean | 否 | 是否显示状态栏图标。 | +| label | string | 否 | 通知标签。 | +| badgeIconStyle | number | 否 | 通知角标类型。预留能力,暂未支持。 | +| showDeliveryTime | boolean | 否 | 是否显示分发时间。 | +| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | 否 | 通知按钮,最多三个按钮。 | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知小图标。可选字段,大小不超过30KB。 | +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知大图标。可选字段,大小不超过30KB。 | +| creatorBundleName | string | 否 | 创建通知的包名。 | +| creatorUid | number | 否 | 创建通知的UID。 | +| creatorPid | number | 否 | 创建通知的PID。 | +| creatorUserId8+ | number | 否 | 创建通知的UserId。 | +| hashCode | string | 否 | 通知唯一标识。 | +| classification | string | 否 | 通知分类。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| groupName8+ | string | 否 | 组通知名称。 | +| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 否 | 通知模板。 | +| isRemoveAllowed10+ | boolean | 否 | 通知是否能被移除(点击通知下方删除按钮无法删除,左滑不出现删除按钮)。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| source8+ | number | 否 | 通知源。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| distributedOption8+ | [DistributedOptions](#distributedoptions) | 否 | 分布式通知的选项。 | +| deviceId8+ | string | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | +| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationFlags.md#notificationflags) | 否 | 获取NotificationFlags。 | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | 否 | 当移除通知时,通知将被重定向到的WantAgent实例。 | +| badgeNumber9+ | number | 否 | 应用程序图标上显示的通知数。 | ## DistributedOptions 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 5600a5521366ff4bb9bd2c578d8222e28d681d62..9cd9ee889ea6dd9f31f196fbe6ed37fb73e6320d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md +++ b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md @@ -150,6 +150,7 @@ import matrix4 from '@ohos.matrix4' @Component struct Test { private matrix1 = matrix4.identity().translate({ x: 100 }) + // 对matrix1的拷贝矩阵做scale操作,不影响到matrix1 private matrix2 = this.matrix1.copy().scale({ x: 2 }) build() { @@ -305,7 +306,7 @@ Matrix的坐标点转换函数,可以将当前的变换效果作用到一个 combine(options: Matrix4Transit): Matrix4Transit -Matrix的叠加函数,可以将两个矩阵的效果叠加起来生成一个新的矩阵对象。 +Matrix的叠加函数,可以将两个矩阵的效果叠加起来生成一个新的矩阵对象。会改变调用该函数的原始矩阵。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -330,8 +331,8 @@ import matrix4 from '@ohos.matrix4' @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({ x: 200 }).copy() - private matrix2 = matrix4.identity().scale({ x: 2 }).copy() + private matrix1 = matrix4.identity().translate({ x: 200 }) + private matrix2 = matrix4.identity().scale({ x: 2 }) build() { Column() { @@ -342,7 +343,7 @@ struct Test { .margin({ top: 50 }) // 先平移x轴200px,再缩放两倍x轴,得到矩阵变换后的效果图 Image($r("app.media.icon")) - .transform(this.matrix1.combine(this.matrix2)) + .transform(this.matrix1.copy().combine(this.matrix2)) .width("40%") .height(100) .margin({ top: 50 }) @@ -358,7 +359,7 @@ struct Test { invert(): Matrix4Transit -Matrix的逆函数,可以返回一个当前矩阵对象的逆矩阵,即效果正好相反。 +Matrix的逆函数,可以返回一个当前矩阵对象的逆矩阵,即效果正好相反。会改变调用该函数的原始矩阵。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -374,7 +375,7 @@ Matrix的逆函数,可以返回一个当前矩阵对象的逆矩阵,即效 import matrix4 from '@ohos.matrix4' // matrix1(宽放大2倍) 和 matrix2(宽缩小2倍) 效果相反 let matrix1 = matrix4.identity().scale({ x: 2 }) -let matrix2 = matrix1.invert() +let matrix2 = matrix1.copy().invert() @Entry @Component @@ -401,7 +402,7 @@ struct Tests { translate(options: TranslateOption): Matrix4Transit -Matrix的平移函数,可以为当前矩阵增加x轴/y轴/z轴平移效果。 +Matrix的平移函数,可以为当前矩阵增加x轴/y轴/z轴平移效果。会改变调用该函数的原始矩阵。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -446,7 +447,7 @@ struct Test { scale(options: ScaleOption): Matrix4Transit -Matrix的缩放函数,可以为当前矩阵增加x轴/y轴/z轴缩放效果。 +Matrix的缩放函数,可以为当前矩阵增加x轴/y轴/z轴缩放效果。会改变调用该函数的原始矩阵。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -490,7 +491,7 @@ struct Test { rotate(options: RotateOption): Matrix4Transit -Matrix的旋转函数,可以为当前矩阵增加x轴/y轴/z轴旋转效果。 +Matrix的旋转函数,可以为当前矩阵增加x轴/y轴/z轴旋转效果。会改变调用该函数的原始矩阵。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -604,9 +605,9 @@ struct Test { | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------------ | -| x | number | 否 | x轴的缩放倍数。x>1时以x轴方向放大,x<1时以x轴方向缩小。
默认值:1
取值范围 [0, +∞)
**说明:**
设置小于0的值时,按照默认值处理。 | -| y | number | 否 | y轴的缩放倍数。y>1时以y轴方向放大,y<1时以y轴方向缩小。
默认值:1
取值范围 [0, +∞)
**说明:**
设置小于0的值时,按照默认值处理。 | -| z | number | 否 | z轴的缩放倍数。z>1时以z轴方向放大,z<1时以z轴方向缩小。
默认值:1
取值范围 [0, +∞)
**说明:**
设置小于0的值时,按照默认值处理。 | +| x | number | 否 | x轴的缩放倍数。x>1时以x轴方向放大,0<x<1时以x轴方向缩小,x<0时沿x轴反向并缩放。
默认值:1
取值范围 (-∞, +∞) | +| y | number | 否 | y轴的缩放倍数。y>1时以y轴方向放大,0<y<1时以y轴方向缩小,y<0时沿y轴反向并缩放。
默认值:1
取值范围 (-∞, +∞) | +| z | number | 否 | z轴的缩放倍数。z>1时以z轴方向放大,0<z<1时以z轴方向缩小,z<0时沿z轴反向并缩放。
默认值:1
取值范围 (-∞, +∞) | | centerX | number | 否 | 变换中心点x轴坐标。
默认值:0。
取值范围 (-∞, +∞) | | centerY | number | 否 | 变换中心点y轴坐标。
默认值:0。
取值范围 (-∞, +∞) | @@ -616,9 +617,9 @@ struct Test { | 名称 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ------------------------------------------------------- | -| x | number | 否 | 旋转轴向量x坐标。
默认值:1。
取值范围 (-∞, +∞) | -| y | number | 否 | 旋转轴向量y坐标。
默认值:1。
取值范围 (-∞, +∞) | -| z | number | 否 | 旋转轴向量z坐标。
默认值:1。
取值范围 (-∞, +∞) | +| x | number | 否 | 旋转轴向量x坐标。
默认值:0。
取值范围 (-∞, +∞) | +| y | number | 否 | 旋转轴向量y坐标。
默认值:0。
取值范围 (-∞, +∞) | +| z | number | 否 | 旋转轴向量z坐标。
默认值:0。
取值范围 (-∞, +∞)。
**说明:** 旋转向量中x、y、z至少有一个不为0才有意义。 | | angle | number | 否 | 旋转角度。
默认值:0 | | centerX | number | 否 | 变换中心点x轴坐标。
默认值:0 | | centerY | number | 否 | 变换中心点y轴坐标。
默认值:0 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md index 48ac1c115d1f77fcf6ad18a4e42dae9ea7ecf3fb..f39fb30dbc853ff3cd36a4639be7f52bab612c2a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md @@ -89,9 +89,11 @@ setBackgroundAllowed(isAllowed: boolean): Promise\ **示例:** ```js -policy.setBackgroundAllowed(true).then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.setBackgroundAllowed(true).then(() => { + console.log("setBackgroundAllowed success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.isBackgroundAllowed10+ @@ -164,10 +166,11 @@ isBackgroundAllowed(): Promise\; **示例:** ```js -policy.isBackgroundAllowed().then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.isBackgroundAllowed().then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.setPolicyByUid10+ @@ -248,9 +251,11 @@ setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; **示例:** ```js -policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(() => { + console.log("setPolicyByUid success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.getPolicyByUid10+ @@ -329,10 +334,11 @@ getPolicyByUid(uid: number): Promise\; **示例:** ```js -policy.getPolicyByUid(11111).then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.getPolicyByUid(11111).then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.getUidsByPolicy10+ @@ -412,10 +418,11 @@ getUidsByPolicy(policy: NetUidPolicy): Promise\>; **示例:** ```js -policy.getUidsByPolicy(11111).then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.getUidsByPolicy(11111).then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.getNetQuotaPolicies10+ @@ -487,11 +494,11 @@ getNetQuotaPolicies(): Promise\>; **示例:** ```js -policy.getNetQuotaPolicies().then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) - +policy.getNetQuotaPolicies().then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.setNetQuotaPolicies10+ @@ -608,9 +615,11 @@ let netquotapolicy = { netQuotaPolicyList.push(netquotapolicy); -policy.setNetQuotaPolicies(netQuotaPolicyList).then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.setNetQuotaPolicies(netQuotaPolicyList).then(() => { + console.log("setNetQuotaPolicies success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.isUidNetAllowed10+ @@ -692,10 +701,11 @@ isUidNetAllowed(uid: number, isMetered: boolean): Promise\; **示例:** ```js -policy.isUidNetAllowed(11111, true).then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.isUidNetAllowed(11111, true).then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.isUidNetAllowed10+ @@ -777,10 +787,11 @@ isUidNetAllowed(uid: number, iface: string): Promise\; **示例:** ```js -policy.isUidNetAllowed(11111, 'wlan0').then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.isUidNetAllowed(11111, 'wlan0').then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.setDeviceIdleTrustlist10+ @@ -861,9 +872,11 @@ setDeviceIdleTrustlist(uids: Array\, isAllowed: boolean): Promise\ **示例:** ```js -policy.setDeviceIdleTrustlist([11111,22222], true).then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.setDeviceIdleTrustlist([11111,22222], true).then(() => { + console.log("setDeviceIdleTrustlist success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.getDeviceIdleTrustlist10+ @@ -934,10 +947,11 @@ getDeviceIdleTrustlist(): Promise\>; **示例:** ```js -policy.getDeviceIdleTrustlist().then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.getDeviceIdleTrustlist().then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.getBackgroundPolicyByUid10+ @@ -1017,10 +1031,11 @@ getBackgroundPolicyByUid(uid: number): Promise\; **示例:** ```js -policy.getBackgroundPolicyByUid(11111).then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.getBackgroundPolicyByUid(11111).then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.resetPolicies10+ @@ -1099,9 +1114,11 @@ resetPolicies(simId: string): Promise\; **示例:** ```js -policy.resetPolicies('1').then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.resetPolicies('1').then(() => { + console.log("resetPolicies success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.updateRemindPolicy10+ @@ -1186,9 +1203,11 @@ updateRemindPolicy(netType: NetBearType, simId: string, remindType: RemindType): ```js import connection from '@ohos.net.connection'; -policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(() => { + console.log("updateRemindPolicy success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.setPowerSaveTrustlist10+ @@ -1269,9 +1288,11 @@ setPowerSaveTrustlist(uids: Array\, isAllowed: boolean): Promise\; **示例:** ```js -policy.setPowerSaveTrustlist([11111,22222], true).then(function (error) { - console.log(JSON.stringify(error)) -}) +policy.setPowerSaveTrustlist([11111,22222], true).then(() => { + console.log("setPowerSaveTrustlist success"); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.getPowerSaveTrustlist10+ @@ -1343,10 +1364,11 @@ getPowerSaveTrustlist(): Promise\>; **示例:** ```js -policy.getPowerSaveTrustlist().then(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +policy.getPowerSaveTrustlist().then((data) => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); ``` ## policy.on 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 12d12966b90dbc4b7901324066251e1ecfd2152e..9a2ff46e0e53ce413961432256d26cb32e67dd91 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -4,7 +4,7 @@ > **说明:** > -> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。(从API version 9开始停止维护) > > 通知订阅和取消订阅仅对系统应用开放。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index b67a507232a28833888c843c9dbfcfadf33098ad..925b0da2db5c7bf2772d41af4df55bde8b23451b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -630,7 +630,7 @@ try { | CPU | 1 | CPU资源,申请后不被挂起。 | | COMMON_EVENT | 2 | 申请后挂起状态下不会代理公共事件。 | | TIMER | 4 | 计时器,申请后挂起状态不会代理SystemTimer。 | -| WORK_SCHEDULER | 8 | [WorkScheduler默认采用较宽松管控策略。(详见 延迟任务调度约束)](../../task-management/background-task-overview.md#延迟任务调度约束) | +| WORK_SCHEDULER | 8 | WorkScheduler默认采用较宽松管控策略。(详见[延迟任务调度约束](../../task-management/work-scheduler.md#约束与限制)) | | BLUETOOTH | 16 | 申请后挂起状态不会代理蓝牙。 | | GPS | 32 | 申请后挂起状态不会代理GPS。 | | AUDIO | 64 | 申请后挂起状态不会代理音频。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index d43f9649ab53b2e28e956c1c65d4a5635bdacaec..68d565745f5a216332ae999505be4a4330410739 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -8,7 +8,7 @@ > > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块接口仅可在Stage模型下使用。 -> - 延迟任务调度约束见[延迟任务调度约束](../../task-management/background-task-overview.md#延迟任务调度约束)。 +> - 延迟任务调度约束见[延迟任务调度约束](../../task-management/work-scheduler.md#约束与限制)。 ## 导入模块 @@ -411,7 +411,7 @@ isLastWorkTimeOut(workId: number): Promise\ ``` ## WorkInfo -提供工作的具体信息。WorkInfo设置参数约束见[延迟任务调度概述](../../task-management/background-task-overview.md#延迟任务调度约束) +提供工作的具体信息。WorkInfo设置参数约束见[延迟任务调度约束](../../task-management/work-scheduler.md#约束与限制) **系统能力**:SystemCapability.ResourceSchedule.WorkScheduler 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 d88f45cea824d220350e30674b41f994f6d44c9e..07773f706bd647c579992fdf9cbdb11b38bd0c5f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -409,7 +409,7 @@ pushNamedRoute(options: NamedRouterOptions): Promise<void> | 100003 | if the pages are pushed too much. | | 100004 | if the named route is not exist. | -**示例:** +**示例:** ```ts try { @@ -427,6 +427,8 @@ try { } ``` +详细示例请参考:[UI开发-页面路由](../../ui/arkts-routing.md#命名路由) + ## router.pushNamedRoute10+ pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-sms.md b/zh-cn/application-dev/reference/apis/js-apis-sms.md index e3377be097917dd1267707c6f0b130284556ecb6..a5e3f36cd6a4a390db28a3a474d056ae35cbceaa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sms.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sms.md @@ -135,10 +135,10 @@ sendMessage\(options: SendMessageOptions\): void **示例:** ```js -let sendCallback = function (err, data) { +let sendCallback = function (err, data) { console.log(`sendCallback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); } -let deliveryCallback = function (err, data) { +let deliveryCallback = function (err, data) { console.log(`deliveryCallback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); } let slotId = 0; diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index 693a90b9da75cbf820149b7b25325bc8a833b458..bca9cb71fb40ead44c0284d288d0df1f1e9ffb28 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -747,6 +747,9 @@ bind(address: NetAddress, callback: AsyncCallback\): void 绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方法作为异步方法。 +> **说明:** +> bind方法失败会由系统随机分配端口号。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -784,6 +787,9 @@ bind(address: NetAddress): Promise\ 绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方法作为异步方法。 +> **说明:** +> bind方法失败会由系统随机分配端口号。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -1686,7 +1692,7 @@ listen(address: NetAddress, callback: AsyncCallback\): void 绑定IP地址和端口,端口可以指定或由系统随机分配。监听并接受与此套接字建立的TCPSocket连接。该接口使用多线程并发处理客户端的数据。使用callback方法作为异步方法。 > **说明:** -> 服务端使用该方法完成bind,listen,accept操作。 +> 服务端使用该方法完成bind,listen,accept操作,bind方法失败会由系统随机分配端口号。 **需要权限**:ohos.permission.INTERNET @@ -1731,7 +1737,7 @@ listen(address: NetAddress): Promise\ 绑定IP地址和端口,端口可以指定或由系统随机分配。监听并接受与此套接字建立的TCPSocket连接。该接口使用多线程并发处理客户端的数据。使用Promise方法作为异步方法。 > **说明:** -> 服务端使用该方法完成bind,listen,accept操作。 +> 服务端使用该方法完成bind,listen,accept操作,bind方法失败会由系统随机分配端口号。 **需要权限**:ohos.permission.INTERNET @@ -1991,6 +1997,9 @@ on(type: 'connect', callback: Callback\): void 订阅TCPSocketServer的连接事件。使用callback方式作为异步方法。 +> **说明:** +> listen方法调用成功后,才可调用此方法。 + **系统能力**:SystemCapability.Communication.NetStack **参数:** @@ -2058,6 +2067,9 @@ on(type: 'error', callback: ErrorCallback): void 订阅TCPSocketServer连接的error事件。使用callback方式作为异步方法。 +> **说明:** +> listen方法调用成功后,才可调用此方法。 + **系统能力**:SystemCapability.Communication.NetStack **参数:** @@ -4534,7 +4546,7 @@ tlsServer.getProtocol().then(data => { }); ``` -### on('connect') +### on('connect')10+ on(type: 'connect', callback: Callback\): void @@ -4589,7 +4601,7 @@ tlsServer.on('connect', function(data) { }); ``` -### off('connect') +### off('connect')10+ off(type: 'connect', callback?: Callback\): void @@ -4650,7 +4662,7 @@ tlsServer.off('connect', callback); tlsServer.off('connect'); ``` -### on('error') +### on('error')10+ on(type: 'error', callback: ErrorCallback): void @@ -4705,7 +4717,7 @@ tlsServer.on('error', err => { }); ``` -### off('error') +### off('error')10+ off(type: 'error', callback?: ErrorCallback): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md b/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md index 3efeff8a95fd8528d3fdd5aed4836ebce8caa29c..2dbc883b097a77e04ec21083782b31cd2312e0bc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -3,7 +3,7 @@ > **说明:** > -> - 从API Version 7 开始,该接口不再维护,推荐使用新接口[`@ohos.bluetooth`](js-apis-bluetooth.md)。 +> - 从API Version 7 开始,该接口不再维护,推荐使用[`@ohos.bluetooth.ble`](js-apis-bluetooth-ble.md)等相关profile接口。 > > - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md index fe646cc007612c12a8e8ea36e7feb15b8b9e8de0..f529595b5b7acdc8c8febe1651f3d2f5ec58a556 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @@ -63,7 +63,7 @@ import wallpaper from '@ohos.wallpaper'; setVideo(source: string, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -将视频资源设置为桌面或锁屏的动态壁纸。 +将视频资源设置为桌面或锁屏的动态壁纸。使用callback异步回调。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -101,7 +101,7 @@ try { setVideo(source: string, wallpaperType: WallpaperType): Promise<void> -将视频资源设置为桌面或锁屏的动态壁纸。 +将视频资源设置为桌面或锁屏的动态壁纸。使用promise异步回调。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -370,7 +370,7 @@ let minWidth = wallpaper.getMinWidthSync(); restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -移除指定类型的壁纸,恢复为默认显示的壁纸。 +移除指定类型的壁纸,恢复为默认显示的壁纸。使用callback异步回调。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -401,7 +401,7 @@ wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { restore(wallpaperType: WallpaperType): Promise<void> -移除指定类型的壁纸,恢复为默认显示的壁纸。 +移除指定类型的壁纸,恢复为默认显示的壁纸。使用promise异步回调。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -435,7 +435,7 @@ wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -将指定资源设置为指定类型的壁纸。 +将指定资源设置为指定类型的壁纸。使用callback异步回调。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -490,7 +490,7 @@ imageSource.createPixelMap(opts).then((pixelMap) => { setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -将指定资源设置为指定类型的壁纸。 +将指定资源设置为指定类型的壁纸。使用promise异步回调。 **需要权限**:ohos.permission.SET_WALLPAPER @@ -546,7 +546,7 @@ imageSource.createPixelMap(opts).then((pixelMap) => { getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; -获取壁纸图片的像素图。 +获取壁纸图片的像素图。使用callback异步回调。 **需要权限**:ohos.permission.GET_WALLPAPER @@ -578,7 +578,7 @@ wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, da getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> -获取壁纸图片的像素图。 +获取壁纸图片的像素图。使用promise异步回调。 **需要权限**:ohos.permission.GET_WALLPAPER diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index e96ca170e6bad8a24e02897605ff9a2014ccf705..f4a45159e2b01cf245ee67fd869d4eae8708ec14 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -139,6 +139,7 @@ - [Swiper](ts-container-swiper.md) - [Tabs](ts-container-tabs.md) - [TabContent](ts-container-tabcontent.md) + - [UIExtensionComponent](ts-container-ui-extension-component.md) - [WaterFlow](ts-container-waterflow.md) - 媒体组件 - [Video](ts-media-components-video.md) @@ -189,5 +190,5 @@ - [类型定义](ts-types.md) - 已停止维护的组件 - [GridContainer](ts-container-gridcontainer.md) -- 已停止维护的接口 +- 已停止维护的接口 - [点击控制](ts-universal-attributes-click.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif b/zh-cn/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif new file mode 100644 index 0000000000000000000000000000000000000000..65daefb814d4f64f4e85f0d3ef8be14fa04998dc Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md b/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md index 0a7776d01bd030d9fcebd530b0636c80736b3150..0b1c6a67f96470e83ec9928c578b573e8ac5210b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -16,7 +16,7 @@ animation(value: {duration?: number, tempo?: number, curve?: string | Curve | IC | ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ | | duration | number | 否 | 设置动画时长。
默认值:1000
单位:毫秒
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
- 在ArkTS卡片上最大动画持续时间为1000毫秒。
- 设置小于0的值时按0处理。
- 设置浮点型类型的值时,向下取整。例如,设置值为1.2,按照1处理。 | | tempo | number | 否 | 动画播放速度。数值越大,动画播放速度越快,数值越小,播放速度越慢。
值为0时,表示不存在动画。
默认值:1
**说明:**
当设置小于0的值时按值为1处理。 | -| curve | string \| [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)9+ | 否 | 设置动画曲线。默认曲线为线性。
默认值:Curve.Linear
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| curve | string \| [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)9+ | 否 | 设置动画曲线。
默认值:Curve.EaseInOut
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | delay | number | 否 | 设置动画延迟执行的时长。单位为毫秒,默认不延时播放。
默认值:0
取值范围:[0, +∞)
**说明:**
- 当设置的值小于0时按0处理。
- 设置浮点型类型的值时,向下取整。例如,设置值为1.2,按照1处理。 | | iterations | number | 否 | 设置播放次数。
默认值:1
取值范围:[-1, +∞)
**说明:**
设置为-1时表示无限次播放。设置为0时表示无动画效果。 | | playMode | [PlayMode](ts-appendix-enums.md#playmode) | 否 | 设置动画播放模式,默认播放完成后重头开始播放。
默认值:PlayMode.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。
相关使用约束请参考PlayMode说明。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index 9eb6ea3b66e032f8a441b65e509759dda062a37f..1ef16e32d86c20e5846aaee774ba87680d1b15c3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -68,9 +68,10 @@ DatePicker(options?: {start?: Date, end?: Date, selected?: Date}) 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: -| 名称 | 功能描述 | -| ---------------------------------------- | ----------- | -| onChange(callback: (value: DatePickerResult) => void) | 选择日期时触发该事件。 | +| 名称 | 功能描述 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| onChange(callback: (value: DatePickerResult) => void)(deprecated) | 选择日期时触发该事件。
**说明:**
从API version 8 开始支持,从 API version 10 开始废弃,建议使用onDateChange(callback: (value: Date) => void)。 | +| onDateChange(callback: (value: Date) => void)10+ | 选择日期时触发该事件。 | ## DatePickerResult对象说明 @@ -108,9 +109,9 @@ struct DatePickerExample { .textStyle({color: '#ff182431', font: {size: '18fp', weight: FontWeight.Normal}}) .selectedTextStyle({color: '#ff0000FF', font: {size: '26fp', weight: FontWeight.Regular}}) .lunar(this.isLunar) - .onChange((value: DatePickerResult) => { - this.selectedDate.setFullYear(value.year, value.month, value.day) - console.info('select current date is: ' + JSON.stringify(value)) + .onDateChange((value: Date) => { + this.selectedDate = value + console.info('select current date is: ' + value.toString()) }) }.width('100%') 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 4e4158658ff7940b443f618a3bb944c8f048a791..9b433727bf4bc79ac6639fccc37423c2f28919d8 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 @@ -52,7 +52,7 @@ Image组件加载图片失败或图片尺寸为0时,图片组件大小自动 | syncLoad8+ | boolean | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
建议加载尺寸较小的本地图片时将syncLoad设为true,因为耗时较短,在主线程上执行即可。 | | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置图片是否可复制。
当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键'CTRL+C'等方式进行复制。
默认值:CopyOptions.None
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg图片不支持复制。 | | colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | 给图像设置颜色滤镜效果,入参为一个的4x5的RGBA转换矩阵。
矩阵第一行表示R(红色)的向量值,第二行表示G(绿色)的向量值,第三行表示B(蓝色)的向量值,第四行表示A(透明度)的向量值,4行分别代表不同的RGBA的向量值。
RGBA值分别是0和1之间的浮点数字,当矩阵对角线值为1时,保持图片原有色彩。
**计算规则:**
如果输入的滤镜矩阵为:
![image-matrix-1](figures/image-matrix-1.jpg)
像素点为[R, G, B, A]
则过滤后的颜色为 [R’, G’, B’, A’]
![image-matrix-2](figures/image-matrix-2.jpg)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| draggable(deprecated) | boolean | 设置组件默认拖拽效果,设置为true时,组件可拖拽。
不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用。
默认值:false
**说明:**
从 API version 9 开始支持,从 API version 10 开始废弃,建议使用通用属性[draggable](ts-universal-events-drag-drop.md)替代。 | +| draggable(deprecated) | boolean | 设置组件默认拖拽效果,设置为true时,组件可拖拽。
不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用。
默认值:false
**说明:**
从 API version 9 开始支持,从 API version 10 开始废弃,建议使用通用属性[draggable](ts-universal-attributes-drag-drop.md)替代。 | > **说明:** > diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index 3f82f6a0f5597d5ffc043f96fd38ff76042f47de..d90e154e8a774c87bc3066a8599ff0004c37eca1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -22,11 +22,17 @@ LoadingProgress() ## 属性 +除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: + | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | | color | [ResourceColor](ts-types.md#resourcecolor) | 设置加载进度条前景色。
默认值:'#99666666'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | enableLoading10+ | boolean | 设置LoadingProgress动画显示或者不显示。
默认值:true。
**说明:**
LoadingProgress动画不显示时,该组件依旧占位。
通用属性Visibility.Hidden隐藏的是包括border、padding等整个组件范围,而enableLoading=false只隐藏LoadingProgress本身动画内容,不包括border等。| +## 事件 + +支持[通用事件](ts-universal-events-click.md)。 + ## 示例 ```ts 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 99065afdcd9233733cb66d0d4bc08f4b8c74b4b8..79fdf9c09cefd4e110b507d2c002d69bba9f2bc8 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 @@ -26,13 +26,13 @@ PatternLock(controller?: PatternLockController) | 名称 | 参数类型 | 描述 | | --------------- | ------------------------------------- | ------------------------------------------------------------ | -| sideLength | [Length](ts-types.md#length) | 设置组件的宽度和高度(宽高相同)。设置为0或负数等非法值时组件不显示。
默认值:300vp | -| circleRadius | [Length](ts-types.md#length) | 设置宫格中圆点的半径。
默认值:14vp | +| sideLength | [Length](ts-types.md#length) | 设置组件的宽度和高度(宽高相同)。设置为0或负数时组件不显示。
默认值:288vp | +| circleRadius | [Length](ts-types.md#length) | 设置宫格中圆点的半径。设置为0或负数时取默认值。
默认值:6vp | | regularColor | [ResourceColor](ts-types.md#resourcecolor) | 设置宫格圆点在“未选中”状态的填充颜色。
默认值:Color.Black | | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置宫格圆点在“选中”状态的填充颜色。
默认值:Color.Black | | activeColor | [ResourceColor](ts-types.md#resourcecolor) | 设置宫格圆点在“激活”状态的填充颜色(“激活”状态为手指经过圆点但还未选中的状态)。
默认值:Color.Black | | pathColor | [ResourceColor](ts-types.md#resourcecolor) | 设置连线的颜色。
默认值:Color.Blue | -| pathStrokeWidth | number \| string | 设置连线的宽度。设置为0或负数等非法值时连线不显示。
默认值:34vp | +| pathStrokeWidth | number \| string | 设置连线的宽度。设置为0或负数时连线不显示。
默认值:12vp | | autoReset | boolean | 设置在完成密码输入后再次在组件区域按下时是否重置组件状态。设置为true,完成密码输入后再次在组件区域按下时会重置组件状态(即清除之前输入的密码);反之若设置为false,则不会重置组件状态。
默认值:true | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md index d731e8ca1ad125ccefcf9947b748d1062074e811..6c920619bc70bf2ef064f678c0bf3ef6e98e1c42 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -70,6 +70,7 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) | strokeWidth | [Length](ts-types.md#length) | 否 | 设置进度条宽度(不支持百分比设置)。
默认值:4.0vp | | scaleCount | number | 否 | 设置环形进度条总刻度数。
默认值:120 | | scaleWidth | [Length](ts-types.md#length) | 否 | 设置环形进度条刻度粗细(不支持百分比设置),刻度粗细大于进度条宽度时,为系统默认粗细。
默认值:2.0vp | +| enableSmoothEffect10+ | boolean | 否 | 进度平滑动效的开关。开启平滑动效后设置进度,进度会从当前值渐变至设定值,否则进度从当前值突变至设定值。
默认值:true | ## CapsuleStyleOptions10+ | 名称 | 参数类型 | 必填 | 描述 | @@ -81,6 +82,7 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) | fontColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 文本颜色。
默认值:'\#ff182431' | | enableScanEffect | boolean | 否 | 扫光效果的开关。
默认值:false | | showDefaultPercentage | boolean | 否 | 显示百分比文本的开关,开启后会在进度条上显示当前进度的百分比。设置了content属性时该属性不生效。
默认值:false | +| enableSmoothEffect | boolean | 否 | 进度平滑动效的开关。开启平滑动效后设置进度,进度会从当前值渐变至设定值,否则进度从当前值突变至设定值。
默认值:true | ## RingStyleOptions10+ | 名称 | 参数类型 | 必填 | 描述 | @@ -89,12 +91,14 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) | shadow | boolean | 否 | 进度条阴影开关。
默认值:false | | status | [ProgressStatus10+](#progressstatus10枚举说明) | 否 | 进度条状态,当设置为LOADING时会开启检查更新动效,此时设置进度值不生效。当从LOADING设置为PROGRESSING,检查更新动效会执行到终点再停止。
默认值: ProgressStatus.PROGRESSING | | enableScanEffect | boolean | 否 | 进度条扫光效果的开关。
默认值: false | +| enableSmoothEffect | boolean | 否 | 进度平滑动效的开关。开启平滑动效后设置进度,进度会从当前值渐变至设定值,否则进度从当前值突变至设定值。
默认值:true | ## LinearStyleOptions10+ | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | | strokeWidth | [Length](ts-types.md#length) | 否 | 设置进度条宽度(不支持百分比设置)。
默认值:4.0vp | | enableScanEffect | boolean | 否 | 进度条扫光效果的开关。
默认值: false | +| enableSmoothEffect | boolean | 否 | 进度平滑动效的开关。开启平滑动效后设置进度,进度会从当前值渐变至设定值,否则进度从当前值突变至设定值。
默认值:true | ## ScaleRingStyleOptions10+ | 名称 | 参数类型 | 必填 | 描述 | @@ -102,15 +106,18 @@ Progress(options: {value: number, total?: number, type?: ProgressType}) | strokeWidth | [Length](ts-types.md#length) | 否 | 设置进度条宽度(不支持百分比设置)。
默认值:4.0vp | | scaleCount | number | 否 | 设置环形进度条总刻度数。
默认值:120 | | scaleWidth | [Length](ts-types.md#length) | 否 | 设置环形进度条刻度粗细(不支持百分比设置),刻度粗细大于进度条宽度时,为系统默认粗细。
默认值:2.0vp | +| enableSmoothEffect | boolean | 否 | 进度平滑动效的开关。开启平滑动效后设置进度,进度会从当前值渐变至设定值,否则进度从当前值突变至设定值。
默认值:true | ## EclipseStyleOptions10+ -暂无参数。 +| 名称 | 参数类型 | 必填 | 描述 | +| ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| enableSmoothEffect | boolean | 否 | 进度平滑动效的开关。开启平滑动效后设置进度,进度会从当前值渐变至设定值,否则进度从当前值突变至设定值。
默认值:true | ## ProgressStatus10+枚举说明 | 名称 | 描述 | | ----------------------- | ---------------- | -| LOADING10+ | 加载中。 | -| PROGRESSING10+ | 进度更新中。 | +| LOADING | 加载中。 | +| PROGRESSING | 进度更新中。 | ## 事件 @@ -249,3 +256,38 @@ struct ProgressExample { } ``` ![capsuleProgressStyleEffect](figures/arkts-capsuleProgressStyleEffect.png) + +### 示例5 +进度平滑动效 +```ts +@Entry +@Component +struct Index { + @State value: number = 0 + + build() { + Column({space: 10}) { + Text('enableSmoothEffect: true').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(5) + .margin({top: 20}) + Progress({value: this.value, total: 100, type:ProgressType.Linear}) + .style({strokeWidth: 10, enableSmoothEffect: true}) + + Text('enableSmoothEffect: false').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(5) + Progress({value: this.value, total: 100, type:ProgressType.Linear}) + .style({strokeWidth: 10, enableSmoothEffect: false}) + + Button('value +10').onClick(() => { + this.value += 10 + }) + .width(75) + .height(15) + .fontSize(9) + } + .width('50%') + .height('100%') + .margin({left:20}) + } +} + +``` +![progressSmoothEffect](figures/arkts-progressSmoothEffect.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md index 16d0c313fe393f4a6c4674dbfa8acb78d6f51100..1c49339e8dd4360403ae19cad9ea9f51421add09 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md @@ -27,6 +27,10 @@ RichEditor(value: RichEditorOptions) 支持[通用属性](ts-universal-attributes-size.md)。 +> **说明:** +> +> 其中clip属性默认值为true。 + ## 事件 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: 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 5e7366aa0c08fcbd35d10b3f742439e7200ea908..66c61449bc1b05ea49b9320767b1e8551194b471 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 @@ -48,7 +48,7 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置滑轨的已滑动部分颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | showSteps | boolean | 设置当前是否显示步长刻度值。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。| | showTips | value: boolean,
content10+?: [ResourceStr](ts-types.md#resourcestr) | value:设置滑动时是否显示气泡提示。
默认值:false
content:设置气泡提示的文本内容,默认显示当前百分比。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
当direction的值为Axis.Horizontal时,tip显示在滑块正上方。值为Axis.Vertical时,tip显示在滑块正左边。
tip的绘制区域为Slider自身节点的overlay。
Slider不设置边距或者边距比较小时,tip会被截断。| -| trackThickness | [Length](ts-types.md#length) | 设置滑轨的粗细。
默认值:当参数style的值设置[SliderStyle](#sliderstyle枚举说明).OutSet 时为 4.0vp,[SliderStyle](#sliderstyle枚举说明).InSet时为20.0vp
从APIversion9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按默认值显示。 | +| trackThickness | [Length](ts-types.md#length) | 设置滑轨的粗细。
默认值:当参数style的值设置[SliderStyle](#sliderstyle枚举说明).OutSet 时为 4.0vp,[SliderStyle](#sliderstyle枚举说明).InSet时为20.0vp
从APIversion9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于等于0的值时,按默认值显示。 | | blockBorderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置滑块描边颜色。 | | blockBorderWidth10+ | [Length](ts-types.md#length) | 设置滑块描边粗细。 | | stepColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置刻度颜色。 | 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 62816195d70832835372f204356618f9cc477fb7..aeeff72281ceddfbd76bc590b2be2dd30fed5983 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 @@ -37,7 +37,7 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | caretColor | [ResourceColor](ts-types.md#resourcecolor) | 设置输入框光标颜色。
默认值:'#007DFF'。 | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | 通过正则表达式设置输入过滤器。匹配表达式的输入允许显示,不匹配的输入将被过滤。仅支持单个字符匹配,不支持字符串匹配。
- value:设置正则表达式。
- error:正则匹配失败时,返回被过滤的内容。 | | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置输入的文本是否可复制。
默认值:CopyOptions.LocalDevice,支持设备内复制。
设置CopyOptions.None时,当前TextArea中的文字无法被复制或剪切,仅支持粘贴。 | -| maxLength10+ | number | 设置文本的最大输入字符数。
默认不设置最大输入字符数限制。 | +| maxLength10+ | number | 设置文本的最大输入字符数。
默认不设置最大输入字符数限制。
到达文本最大字符限制,将无法继续输入字符,同时边框变为红色。 | | showCounter10+ | boolean | 设置文本最大输入字符数后,是否显示字数。
默认值:false | | style10+ | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | 设置文本框多态样式。
默认值:TextContentStyle.DEFAULT | | enableKeyboardOnFocus10+ | boolean | TextArea获焦时,是否绑定输入法
默认值:true。从API version 10开始,获焦默认绑定输入法。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md old mode 100644 new mode 100755 index d03b65792c3c407408870796225e0bbada42f951..2dc0d7f4e04d2dda802052cbb8d539d31bbcc19a --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md @@ -25,9 +25,43 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 名称 | 参数类型 | 描述 | -| ------ | --------------- | ------------------------------------------------------------ | -| format | string | 设置显示时间格式。
日期间隔符固定为"/",时间间隔符为":"。
如yyyyMMdd,yyyy-MM-dd显示为yyyy/MM/dd,
hhmmss显示为hh:mm:ss。
时间格式只用写一位即可,如"hhmmss"等同于"hms"。
支持的时间格式化字符串:
- YYYY/yyyy:完整年份。
- YY/yy:年份后两位。
- M:月份(若想使用01月则使用MM)。
- d:日期(若想使用01日则使用dd)。
- D:年中日(一年中的第几天)。
- H:24小时制。
- h:12小时制。
- m:分钟。
- s:秒。
- SSS:毫秒。
若格式未匹配,则使用默认值。
默认值: 'hms'| +| 名称 | 参数类型 | 描述 | +| ------ | -------- | ------------------------------------------------------------ | +| format | string | y:年
M:月
d:日
E:星期(星期默认应使用完整星期,例如:星期六;显示空间不足时才考虑使用简写星期,例如:周六)
H:小时(0~23) h:小时(1~12)
m:分钟
s:秒
SS:厘秒
SSS:毫秒
a:上午/下午(仅在12小时制中有效)
间隔符:"年月日"、“/”、"-"、"."(开发者也可以自定义间隔符样式)
允许开发者自行拼接组合显示格式,即:年、月、日、星期、时、分、秒、毫秒可拆分为子元素,开发者可自行排布组合。
| + +以下是format输入的格式样式及对应的显示效果: + +| 输入格式 | 显示效果 | +| ------------------------------------------------------------ | ------ | +| yyyy年M月d日 EEEE | 2023年2月4日 星期六 | +| yyyy年M月d日 | 2023年2月4日 | +| M月d日 EEEE | 2月4日 星期六 | +| M月d日 | 2月4日 | +| MM/dd/yyyy | 02/04/2023 | +| EEEE MM月dd日 | 星期六 02月04日 | +| yyyy(完整年份) | 2023年 | +| yy(年份后两位) | 23年 | +| MM(完整月份) | 02月 | +| M(月份) | 2月 | +| dd(完整日期) | 04日 | +| d(日期) | 4日 | +| EEEE(完整星期) | 星期六 | +| E、EE、EEE(简写星期) | 周六 | +| yyyy年M月d日 | 2023年2月4日 | +| yyyy/M/d | 2023/2/4 | +| yyyy-M-d | 2023-2-4 | +| yyyy.M.d | 2023.2.4 | +| HH:mm:ss(时:分:秒) | 17:00:04 | +| aa hh:mm:ss(时:分:秒) | 上午 5:00:04 | +| hh:mm:ss(时:分:秒) | 5:00:04 | +| HH:mm(时:分) | 17:00 | +| aa hh:mm(时:分) | 上午 5:00 | +| hh:mm(时:分) | 5:00 | +| mm:ss(分:秒) | 00:04 | +| mm:ss.SS(分:秒:厘秒) | 00:04.91 | +| mm:ss.SS(分:秒.毫秒) | 00:04.536 | +| hh:mm:ss aa | 5:00:04 上午 | +| HH | 17 | ## 事件 @@ -74,7 +108,7 @@ struct Second { .fontSize(20) // 以12小时制显示东八区的系统时间,精确到秒。 TextClock({ timeZoneOffset: -8, controller: this.controller }) - .format('hms') + .format('aa hh:mm:ss') .onDateChange((value: number) => { this.accumulateTime = 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 4b0c12ecf5e6fa934154ae4f9fc4d651e5e021ad..0eb644b0a1d4636e3c275fed02c979c1719e2929 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -40,9 +40,9 @@ RenderingContextSettings(antialias?: boolean) | 名称 | 类型 | 描述 | | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为number时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 | -| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为number时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
默认值:'black'
- 类型为number时,表示设置填充区域的颜色。
默认值:'#000000'
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。
默认值:1(px) | +| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
默认值:'black'
- 类型为number时,表示设置描边使用的颜色。
默认值:'#000000'
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10
从API version 9开始,该接口支持在ArkTS卡片中使用。 | 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 7fe21a0d935662f4bba21710a553216f5b7df001..d6c5d6129d38b8694652115f0ac3688a81ca826d 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 @@ -24,8 +24,8 @@ ImageBitmap(src: string) | 属性 | 类型 | 描述 | | -------- | -------- | -------- | -| width | number | ImageBitmap的像素宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| height | number | ImageBitmap的像素高度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| width | number | ImageBitmap的像素宽度,当前值为0。。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| height | number | ImageBitmap的像素高度,当前值为0。。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **示例:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md index cb28b74e70fdd9ccb2df68548a07b1fcbf65ba6f..f16a41bafda788ca4e1d719bb0dfd9c175fb6583 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md @@ -272,39 +272,39 @@ - [ScrollBar](ts-basic-components-scrollbar.md) 滚动条组件,用于配合可滚动组件使用,如List、Grid、Scroll等。 - + - [Badge](ts-container-badge.md) 可以附加在单个组件上用于信息标记的容器组件。 - + - [AlphabetIndexer](ts-container-alphabet-indexer.md) 可以与容器组件联动用于按逻辑结构快速定位容器显示区域的索引条组件。 - + - [Panel](ts-container-panel.md) 可滑动面板,提供一种轻量的内容展示窗口,方便在不同尺寸中切换。 - + - [Refresh](ts-container-refresh.md) 可以进行页面下拉操作并显示刷新动效的容器组件。 - + - [AbilityComponent](ts-container-ability-component.md) 独立显示Ability的容器组件。 - + - [RemoteWindow](ts-basic-components-remotewindow.md) 远程控制窗口组件,可以通过此组件控制应用窗口,提供启动退出过程中控件动画和应用窗口联动动画的能力。 - + - [FormComponent](ts-basic-components-formcomponent.md) 提供卡片组件,实现卡片的显示功能。 - + - [FormLink](ts-container-formlink.md) 提供静态卡片事件交互功能。 - + - [Hyperlink](ts-container-hyperlink.md) 超链接组件,组件宽高范围内点击实现跳转。 @@ -312,11 +312,15 @@ - [Menu](ts-basic-components-menu.md) 以垂直列表形式显示的菜单。 - + - [MenuItem](ts-basic-components-menuitem.md) 用来展示菜单Menu中具体的item菜单项。 - + - [MenuItemGroup](ts-basic-components-menuitemgroup.md) 用来展示菜单MenuItem的分组。 + +- [UIExtensionComponent](ts-container-ui-extension-component.md) + + 在页面中嵌入显示带UI界面的Ability扩展的容器组件。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md index 5ef2d3622ec875996e9fd224339b8a27d346608e..7702bf2fd524ddf4e6000ab0749640c78016354a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -97,9 +97,10 @@ List垂直布局,ListItem向右滑动,item左边的长距离滑动删除选 | -------- | -------- | | onSelect(event: (isSelected: boolean) => void)8+ | ListItem元素被鼠标框选的状态改变时触发回调。
isSelected:进入鼠标框选范围即被选中返回true, 移出鼠标框选范围即未被选中返回false。 | - ## 示例 +### 示例1 + ```ts // xxx.ets @Entry @@ -126,6 +127,8 @@ struct ListItemExample { ![zh-cn_image_0000001219864159](figures/zh-cn_image_0000001219864159.gif) +### 示例2 + ```ts // xxx.ets @@ -192,7 +195,8 @@ struct ListItemExample2 { ``` ![deleteListItem](figures/deleteListItem.gif) -## 示例3 +### 示例3 + ```ts // xxx.ets @Entry diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md index 3735108a93820e37f711e00e867a5bdbe7b00934..5db42c5d42ca0cb43e5b8f93735110f5f92980c9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -134,11 +134,11 @@ finishAnimation(callback?: () => void): void | 参数名 | 参数类型 | 必填项 | 参数描述 | | ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| isShowBackground | boolean | 否 | 设置箭头底板是否显示。
默认值:false | +| showBackground | boolean | 否 | 设置箭头底板是否显示。
默认值:false | | isSidebarMiddle | boolean | 否 | 设置箭头显示位置。
默认值:false
默认显示在导航点指示器两侧。 | | backgroundSize | [Length](ts-types.md#length) | 否 | 设置底板大小。
在导航点两侧显示:
默认值:24vp
在组件两侧显示:
默认值:32vp
不支持设置百分比。 | | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置底板颜色。
在导航点两侧显示:
默认值:\#19182431
在组件两侧显示:
默认值:\#00000000 | -| arrowSize | [Length](ts-types.md#length) | 否 | 设置箭头大小。
在导航点两侧显示时:
默认值:18vp
在组件两侧显示时:
默认值:24vp
**说明:**
isShowBackground为true时,arrowSize为backgroundSize的3/4。
不支持设置百分比。 | +| arrowSize | [Length](ts-types.md#length) | 否 | 设置箭头大小。
在导航点两侧显示时:
默认值:18vp
在组件两侧显示时:
默认值:24vp
**说明:**
showBackground为true时,arrowSize为backgroundSize的3/4。
不支持设置百分比。 | | arrowColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置箭头颜色。
默认值:\#182431 | ## SwiperAutoFill10+ @@ -219,7 +219,7 @@ struct SwiperExample { .duration(1000) .itemSpace(0) .displayArrow({ - isShowBackground:true, + showBackground:true, isSidebarMiddle:true, backgroundSize:24, backgroundColor:Color.White, diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md index 9cfb9370daadf9a476edd194670a93a6bfa9b9fd..7993af8e18546dc9228fa1918cdfeeda631e9426 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -140,7 +140,7 @@ BottomTabBarStyle的静态构造函数。 ## 示例 -示例1: +### 示例1 ```ts // xxx.ets @@ -246,7 +246,7 @@ struct TabContentExample { ![tabContent](figures/tabContent1.gif) -示例2: +### 示例2 ```ts // xxx.ets @@ -302,7 +302,7 @@ struct TabContentExample { ![tabContent](figures/tabContent2.gif) -示例3: +### 示例3 ```ts // xxx.ets @@ -400,7 +400,7 @@ struct TabBarStyleExample { ![tabbarStyle](figures/TabBarStyle.jpeg) -示例4: +### 示例4 ```ts // xxx.ets @@ -627,7 +627,7 @@ struct TabsAttr { ![tabContent3](figures/tabContent3.gif) -示例5: +### 示例5 ```ts // xxx.ets diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-ui-extension-component.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-ui-extension-component.md new file mode 100644 index 0000000000000000000000000000000000000000..7528e56e4bee5d273ecdd19c7fdfdd084c378eac --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-ui-extension-component.md @@ -0,0 +1,260 @@ +# UIExtensionComponent + +UIExtensionComponent用于支持在本页面内嵌入其他应用提供的UI。展示的内容在另外一个进程中运行,本应用并不参与其中的布局和渲染。 + +通常用于有进程隔离诉求的模块化开发场景。 + +> **说明:** +> +> 该组件从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 本组件为系统接口。 + +## 使用约束 + +本组件不支持预览。 + +被拉起的Ability必须是带UI的Ability扩展,如何实现带UI的Ability扩展请参考[实现带UI的Ability扩展](../apis/js-apis-app-ability-uiExtensionAbility.md)。 + +必须显示设置组件宽高为非0有效值。 + +## 子组件 + +无 + +## 接口 + +UIExtensionComponent(want: Want) + +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ---- | ---------------------------------------- | ---- | --------------- | +| want | [Want](../apis/js-apis-app-ability-want.md) | 是 | 要加载的Ability。 | + +## UIExtensionProxy + +用于在双方建立连接成功后,组件使用方向被拉起的Ability发送数据的场景,提供send方法。 + +### send + +send(data: { [key: string]: Object }): void + +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ---- | ---------------------------------------- | ---- | --------------- | +| data | { [key: string]: Object } | 是 | 发送给被拉起的扩展Ability的数据。 | + +## 属性 + +支持[通用属性](ts-universal-attributes-size.md)。 + +## 事件 + +不支持[通用事件](ts-universal-events-click.md)。 + +将事件经过坐标转换后传递给对端Ability处理。 + +支持以下事件: + +### onRemoteReady + +onRemoteReady(callback: [Callback](../apis/js-apis-base.md#callback)\) + +UIExtensionAbility连接完成时的回调,之后可使用proxy向被拉起的Ability发送数据。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------------------------- | ------ | ------------------------------------------------------------ | +| proxy | UIExtensionProxy | 用于向对端Ability发送数据。 | + +### onReceive + +onReceive(callback: [Callback](../apis/js-apis-base.md#callback)\<{ [key: string]: Object }>) + +收到被拉起的Ability发送的数据时触发的回调。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------------------------- | ------ | ------------------------------------------------------------ | +| data | { [key: string]: Object } | 收到来自对端Ability的数据。 | + +### onResult + +onResult(callback: [Callback](../apis/js-apis-base.md#callback)\<{code: number; want?: Want}>) + +被拉起的Ability扩展调用terminateSelfWithResult时会先触发本回调函数,再触发OnRelease。 + +本回调内可处理对端Ability的结果数据,可参考[AbilityResult](../apis/js-apis-inner-ability-abilityResult.md)。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------------------------- | ------ | ------------------------------------------------------------ | +| code | number | 收到来自对端Ability的处理結果code。 | +| want | Want | 收到来自对端Ability的处理結果[Want](../apis/js-apis-app-ability-want.md)。 | + +### onRelease + +onRelease(callback: [Callback](../apis/js-apis-base.md#callback)\) + +用于处理被拉起的Ability销毁时的回调。 + +被拉起的Ability扩展调用terminateSelfWithResult或者terminateSelf时会触发本回调,此时releaseCode为0,即正常销毁。 + +被拉起的Ability扩展意外Crash或被kill时,触发本回调,此时releaseCode为1。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------------------------- | ------ | ------------------------------------------------------------ | +| releaseCode | number | 对端Ability销毁时的code,0为正常销毁,1为异常销毁。 | + +### onError + +onError(callback:[ErrorCallback](../apis/js-apis-base.md#errorcallback)) + +被拉起的Ability扩展在运行过程中发生异常时触发本回调。可通过回调参数中的code、name和message获取错误信息并做处理。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------------------------- | ------ | ------------------------------------------------------------ | +| err | [BusinessError](../apis/js-apis-base.md#businesserror) | 报错信息。 | + +## 示例 + +本示例仅展示组件使用的方法和扩展的Ability,实际运行需在设备中安装bundleName为"com.example.uiextensionprovider",abilityName为"UIExtensionProvider"的Ability扩展。 + +```ts +// 组件使用示例: +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + private myProxy: UIExtensionProxy + build() { + Row() { + Column() { + Text(this.message).fontColor(Color.Red) + UIExtensionComponent( + { + bundleName: "com.example.uiextensionprovider", + abilityName: "UIExtensionProvider", + parameters: { "x": 12345, "y": "data" } + } + ) + .size({ width: "100%", height:"100%" }) + .onRemoteReady((proxy) => { + this.message = "remote ready" + this.myProxy = proxy + }) + .onReceive((data) => { + this.message = JSON.stringify(data) + }) + .onRelease((releaseCode) => { + this.message = "Release: " + releaseCode + }) + .onResult((data) => { + this.message = JSON.stringify(data) + }) + .onError((error) => { + this.message = "onError: " + error["code"] + ", name: " + error.name + ", message: " + error.message + }) + Button("sendData").onClick(() => { + this.myProxy.send({ "x": 5678910 }) + }) + } + .width("100%") + } + .height('100%') + } +} +``` + +```ts +// 扩展入口文件UIExtensionProvider.ts +import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility' +const TAG: string = '[UIExtAbility]' +export default class UIExtAbility extends UIExtensionAbility { + onCreate() { + console.log(TAG, `UIExtAbility onCreate`) + } + + onForeground() { + console.log(TAG, `UIExtAbility onForeground`) + } + + onBackground() { + console.log(TAG, `UIExtAbility onBackground`) + } + + onDestroy() { + console.log(TAG, `UIExtAbility onDestroy`) + } + + onSessionCreate(want, session) { + console.log(TAG, `UIExtAbility onSessionCreate, want: ${JSON.stringify(want)}`) + let storage: LocalStorage = new LocalStorage({ + 'session': session + }); + session.loadContent('pages/extension', storage); + } + + onSessionDestroy(session) { + console.log(TAG, `UIExtAbility onSessionDestroy`) + } +} +``` + +```ts +// 扩展Ability入口页面文件extension.ets +import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession' +let storage = LocalStorage.GetShared() +@Entry(storage) +@Component +struct Index { + @State message: string = 'UIExtension' + @State message2:string = 'message from comp' + private session: UIExtensionContentSession = storage.get('session'); + controller: TextInputController = new TextInputController() + onPageShow() { + this.session.setReceiveDataCallback((data)=> { + this.message2 = "data come from comp" + this.message = JSON.stringify(data) + }) + } + build() { + Row() { + Column() { + Text(this.message2) + Text(this.message) + Button("sendData") + .onClick(()=>{ + this.session.sendData({"xxx": "data from extension"}) + }) + Button("terminateSelf") + .onClick(()=>{ + this.session.terminateSelf(); + storage.clear(); + }).margin(5) + Button("TerminateSelfWithResult") + .onClick(()=>{ + this.session.terminateSelfWithResult({ + "resultCode": 0, + "want": { + "bundleName": "myName" + } + }); + storage.clear(); + }).margin(5) + } + .width('100%') + } + .height('100%') + } +} +``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md index 79155e03375271324c332f438feb385a7eec7a28..eb891e4848d5c25aace39a40ec56b2f0308569bf 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -25,7 +25,7 @@ animateTo(value: AnimateParam, event: () => void): void | -------- | -------- | -------- | | duration | number | 动画持续时间,单位为毫秒。
默认值:1000
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
- 在ArkTS卡片上最大动画持续时间为1000毫秒,若超出则固定为1000毫秒。
- 设置小于0的值时按0处理。
- 设置浮点型类型的值时,向下取整。例如,设置值为1.2,按照1处理。 | | tempo | number | 动画的播放速度,值越大动画播放越快,值越小播放越慢,为0时无动画效果。
默认值:1.0
**说明:**
当设置小于0的值时按值为1处理。 | -| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | 动画曲线。
默认值:Curve.Linear
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | 动画曲线。
默认值:Curve.EaseInOut
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | delay | number | 单位为ms(毫秒),默认不延时播放。
默认值:0
**说明:**
- 当设置的值小于0时按0处理。
- 设置浮点型类型的值时,向下取整。例如,设置值为1.2,按照1处理。 | | iterations | number | 默认播放一次,设置为-1时表示无限次播放。
默认值:1 | | playMode | [PlayMode](ts-appendix-enums.md#playmode) | 设置动画播放模式,默认播放完成后重头开始播放。
默认值:PlayMode.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。
相关使用约束请参考PlayMode说明。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 5fa377760f5659035aca6ad1aa8f2ced4841a889..115bafbc70ed614e1a14d4a77ee27b4771d44e92 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -29,9 +29,11 @@ show(options?: DatePickerDialogOptions) | disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 否 | 设置所有选项中最上和最下两个选项的文本颜色、字号、字体粗细。
默认值:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | | textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 否 | 设置所有选项中除了最上、最下及选中项以外的文本颜色、字号、字体粗细。
默认值:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | | selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 否 | 设置选中项的文本颜色、字号、字体粗细。
默认值:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | -| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | +| onAccept(deprecated) | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。
**说明:**
从API version 8 开始支持,从 API version 10 开始废弃,建议使用onDateAccept。 | | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | -| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。 | +| onChange(deprecated) | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。
**说明:**
从API version 8 开始支持,从 API version 10 开始废弃,建议使用onDateChange。 | +| onDateAccept10+ | (value: Date) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。
**说明:**
当showTime设置为true时,回调接口返回值value中时和分为选择器选择的时和分。否则,返回值value中时和分为系统时间的时和分。 | +| onDateChange10+ | (value: Date) => void | 否 | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。
**说明:**
当showTime设置为true时,回调接口返回值value中时和分为选择器选择的时和分。否则,返回值value中时和分为系统时间的时和分。 | **异常情形说明:** @@ -76,16 +78,16 @@ struct DatePickerDialogExample { disappearTextStyle: {color: Color.Pink, font: {size: '22fp', weight: FontWeight.Bold}}, textStyle: {color: '#ff00ff00', font: {size: '18fp', weight: FontWeight.Normal}}, selectedTextStyle: {color: '#ff182431', font: {size: '14fp', weight: FontWeight.Regular}}, - onAccept: (value: DatePickerResult) => { + onDateAccept: (value: Date) => { // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 - this.selectedDate.setFullYear(value.year, value.month, value.day) - console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) + this.selectedDate = value + console.info("DatePickerDialog:onDateAccept()" + value.toString()) }, onCancel: () => { console.info("DatePickerDialog:onCancel()") }, - onChange: (value: DatePickerResult) => { - console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) + onDateChange: (value: Date) => { + console.info("DatePickerDialog:onDateChange()" + value.toString()) } }) }) @@ -101,15 +103,15 @@ struct DatePickerDialogExample { disappearTextStyle: {color: Color.Pink, font: {size: '22fp', weight: FontWeight.Bold}}, textStyle: {color: '#ff00ff00', font: {size: '18fp', weight: FontWeight.Normal}}, selectedTextStyle: {color: '#ff182431', font: {size: '14fp', weight: FontWeight.Regular}}, - onAccept: (value: DatePickerResult) => { - this.selectedDate.setFullYear(value.year, value.month, value.day) - console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) + onDateAccept: (value: Date) => { + this.selectedDate = value + console.info("DatePickerDialog:onDateAccept()" + value.toString()) }, onCancel: () => { console.info("DatePickerDialog:onCancel()") }, - onChange: (value: DatePickerResult) => { - console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) + onDateChange: (value: Date) => { + console.info("DatePickerDialog:onDateChange()" + value.toString()) } }) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md index 7b7bbcf002c7b6c351e3ef1e0d21f809d1383b14..8a778e5a327c60f402c585f301904a877895a14d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-motion-path-animation.md @@ -9,9 +9,9 @@ ## 属性 -| 名称 | 参数类型 | 默认值 | 描述 | -| -------- | -------- | -------- | -------- | -| motionPath | {
path: string,
from?: number,
to?: number,
rotatable?: boolean
}
**说明:**
path中支持使用start和end进行起点和终点的替代,如:
'Mstart.x start.y L50 50 Lend.x end.y Z',更多说明请参考[绘制路径](../../ui/ui-js-components-svg-path.md)。 | {
'',
0.0,
1.0,
false
} | 设置组件的运动路径,入参说明如下:
- path:位移动画的运动路径,使用svg路径字符串。
- from:运动路径的起点。
默认值:0.0
取值范围:[0, 1]
设置小于0的值时,按值为0处理。设置大于1的值时,按值为1处理。
- to:运动路径的终点。
默认值:1.0
取值范围:[0, 1]
设置小于0的值时,按值为0处理。设置大于1的值时,按值为1处理。
- rotatable:是否跟随路径进行旋转。 | +| 名称 | 参数类型 | 描述 | +| -------- | -------- | -------- | +| motionPath | {
path: string,
from?: number,
to?: number,
rotatable?: boolean
} | 设置组件的运动路径,入参说明如下:
- path:位移动画的运动路径,使用svg路径字符串。path中支持使用start和end进行起点和终点的替代,如:'Mstart.x start.y L50 50 Lend.x end.y Z',更多说明请参考[绘制路径](../../ui/ui-js-components-svg-path.md)。
设置为空字符串时相当于不设置路径动画。
- from:运动路径的起点。
默认值:0.0
取值范围:[0, 1]
设置小于0或大于1的值时,按默认值0处理。
- to:运动路径的终点。
默认值:1.0
取值范围:[0, 1]
设置小于0或大于1的值时,按默认值1处理,且满足to值 >= 异常值处理后的from值。
- rotatable:是否跟随路径进行旋转。
默认值:false | ## 示例 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 abdecdbb2ca35499df938b03c7170ac8565203b2..748be0477b86159155efb8ce1861d2f6baaca3ab 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 @@ -6,9 +6,13 @@ > > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > -> 已实现默认拖拽效果组件:[Image](../arkui-ts/ts-basic-components-image.md)、[Text](../arkui-ts/ts-basic-components-text.md)、[TextArea](../arkui-ts/ts-basic-components-textarea.md)、[Search](../arkui-ts/ts-basic-components-search.md)。 +> 默认支持拖拽(拖入和拖出)的组件:Search、TextInput、TextArea > -> 应用中的预置资源文件不支持拖拽(即应用在安装前的HAP包中已经存在的资源文件)。 +> 默认支持拖入的组件:Video +> +> 默认支持拖出的组件:Text、List、Grid、FormComponent、Image、Hyperlink +> +> 应用本身预置的资源文件(即应用在安装前的HAP包中已经存在的资源文件)仅支持本地应用内拖拽。 ## 事件 | 名称 | 支持冒泡 | 功能描述 | @@ -88,12 +92,16 @@ struct Index { getDataFromUdmfRetry(event: DragEvent, callback: (data: DragEvent)=>void) { - let records: Array = event.getData().getRecords(); - if (records.length !== 0) { - callback(event); - return true; + let data = event.getData(); + if (!data) { + return false; + } + let records: Array = data.getRecords(); + if (!records || records.length <= 0) { + return false; } - return false; + callback(event); + return true; } getDataFromUdmf(event: DragEvent, callback: (data: DragEvent)=>void) diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md b/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md index ed93aeb58b8fcb1129f96fa23a6bdde2b9caaaab..6d760af024cc973dba8d19715cc192183ceb14e9 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md @@ -8,7 +8,7 @@ **错误信息** -Unspported para value. +param value not valid **错误描述** @@ -17,25 +17,7 @@ Unspported para value. **可能原因** 该错误码表示参数错误,可能原因是传入参数的类型错误。 - + **处理步骤** 检查参数的类型是否正确。 - -## 890002 配置项参数错误 - -**错误信息** - -param value not valid - -**错误描述** - -当接口的option配置参数中包含不合法的配置项时,系统会产生此错误码。 - -**可能原因** - -该错误码表示配置项参数错误,可能原因是option参数中使用了不支持的配置项。 - -**处理步骤** - -检查option参数中是否使用了不合法的配置项。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-api-intro.md b/zh-cn/application-dev/reference/native-api-intro.md index fb4ce51fe1779fd976bfe049e2c5a1bd2b09599c..2aeaa4b0bc16f7c03384267c0967300dac6074c7 100644 --- a/zh-cn/application-dev/reference/native-api-intro.md +++ b/zh-cn/application-dev/reference/native-api-intro.md @@ -49,7 +49,7 @@ Native API在SDK包的位置为$(SDK_ROOT)/native目录,主要有以下几个 * [Native API参考](native-apis/_o_h___native_x_component.md),介绍各个API参考手册 * [Native API中支持的标准库](../reference/native-lib/third_party_libc/musl.md),介绍Native API支持的开源标准库 * [Native API开发指南](../napi/napi-guidelines.md),结合具体的例子,场景介绍各类接口的使用 -* [使用NDK编译一个Cmake C/C++工程文档](../faqs/howto-migrate-cmake-with-ohosndk.md),介绍如何使用使用Native API开发一个Cmake工程 +* [如何在Cmake工程中使用NDK](../faqs/cmake-with-ndk.md),介绍如何使用使用NDK开发一个CMake工程 * [Node-API在应用工程中的使用指导](../napi/napi-guidelines.md), 如何使用Node-API接口 ## 使用建议 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_audio.md b/zh-cn/application-dev/reference/native-apis/_o_h_audio.md index a968f45c4b706c99e2ff0a74d8e7e3a718c5af50..e66f12de0407d9718ea2708dbc032cd68ff3a643 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h_audio.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h_audio.md @@ -53,7 +53,7 @@ | [OH_AudioStream_SampleFormat](#oh_audiostream_sampleformat) { AUDIOSTREAM_SAMPLE_U8 = 0, AUDIOSTREAM_SAMPLE_S16LE = 1, AUDIOSTREAM_SAMPLE_S24LE = 2, AUDIOSTREAM_SAMPLE_S32LE = 3 } | 定义音频流采样格式。 | | [OH_AudioStream_EncodingType](#oh_audiostream_encodingtype) { **AUDIOSTREAM_ENCODING_TYPE_RAW** = 0 } | 定义音频流编码类型。 | | [OH_AudioStream_Usage](#oh_audiostream_usage) { **AUDIOSTREAM_USAGE_UNKNOWN** = 0, **AUDIOSTREAM_USAGE_MUSIC** = 1, **AUDIOSTREAM_USAGE_COMMUNICATION** = 2, **AUDIOSTREAM_USAGE_GAME** = 11 } | 定义音频流使用场景。 | -| [OH_AudioStream_LatencyMode](#oh_audiostream_latencymode) { AUDIOSTREAM_LATENCY_MODE_NORMAL } | 定义音频时延模式。 | +| [OH_AudioStream_LatencyMode](#oh_audiostream_latencymode) { AUDIOSTREAM_LATENCY_MODE_NORMAL = 0, AUDIOSTREAM_LATENCY_MODE_FAST = 1} | 定义音频时延模式。 | | [OH_AudioStream_State](#oh_audiostream_state) {
AUDIOSTREAM_STATE_INVALID = -1, AUDIOSTREAM_STATE_PREPARED = 1, AUDIOSTREAM_STATE_RUNNING = 2, AUDIOSTREAM_STATE_STOPPED = 3,
AUDIOSTREAM_STATE_RELEASED = 4, AUDIOSTREAM_STATE_PAUSED = 5
} | 定义音频流的状态。 | | [OH_AudioStream_SourceType](#oh_audiostream_sourcetype) { **AUDIOSTREAM_SOURCE_TYPE_INVALID** = -1, **AUDIOSTREAM_SOURCE_TYPE_MIC**, **AUDIOSTREAM_SOURCE_TYPE_VOICE_RECOGNITION** = 1, **AUDIOSTREAM_SOURCE_TYPE_VOICE_COMMUNICATION** = 7 } | 定义音频流使用场景。 | @@ -255,6 +255,7 @@ enum OH_AudioStream_LatencyMode | 枚举值 | 描述 | | -------- | -------- | | AUDIOSTREAM_LATENCY_MODE_NORMAL | 该模式代表一个普通时延的音频流。 | +| AUDIOSTREAM_LATENCY_MODE_FAST | 该模式代表一个低时延的音频流。 | ### OH_AudioStream_Result diff --git a/zh-cn/application-dev/reference/native-apis/native__audiostream__base_8h.md b/zh-cn/application-dev/reference/native-apis/native__audiostream__base_8h.md index abd1a4ea6dd8f4fbb32a50caaf4d34fe97654017..6b69f430e63495eec050147506cd0889504f7bb7 100644 --- a/zh-cn/application-dev/reference/native-apis/native__audiostream__base_8h.md +++ b/zh-cn/application-dev/reference/native-apis/native__audiostream__base_8h.md @@ -47,6 +47,6 @@ | [OH_AudioStream_SampleFormat](_o_h_audio.md#oh_audiostream_sampleformat) { [AUDIOSTREAM_SAMPLE_U8](_o_h_audio.md) = 0, [AUDIOSTREAM_SAMPLE_S16LE](_o_h_audio.md) = 1, [AUDIOSTREAM_SAMPLE_S24LE](_o_h_audio.md) = 2, [AUDIOSTREAM_SAMPLE_S32LE](_o_h_audio.md) = 3 } | 定义音频流采样格式。 | | [OH_AudioStream_EncodingType](_o_h_audio.md#oh_audiostream_encodingtype) { **AUDIOSTREAM_ENCODING_TYPE_RAW** = 0 } | 定义音频流编码类型。 | | [OH_AudioStream_Usage](_o_h_audio.md#oh_audiostream_usage) { **AUDIOSTREAM_USAGE_UNKNOWN** = 0, **AUDIOSTREAM_USAGE_MUSIC** = 1, **AUDIOSTREAM_USAGE_COMMUNICATION** = 2, **AUDIOSTREAM_USAGE_GAME** = 11 } | 定义音频流使用场景。 | -| [OH_AudioStream_LatencyMode](_o_h_audio.md#oh_audiostream_latencymode) { [AUDIOSTREAM_LATENCY_MODE_NORMAL](_o_h_audio.md) } | 定义音频时延模式。 | +| [OH_AudioStream_LatencyMode](_o_h_audio.md#oh_audiostream_latencymode) { [AUDIOSTREAM_LATENCY_MODE_NORMAL](_o_h_audio.md) = 0, [AUDIOSTREAM_LATENCY_MODE_FAST](_o_h_audio.md) = 1 } | 定义音频时延模式。 | | [OH_AudioStream_State](_o_h_audio.md#oh_audiostream_state) {
[AUDIOSTREAM_STATE_INVALID](_o_h_audio.md) = -1, [AUDIOSTREAM_STATE_PREPARED](_o_h_audio.md) = 1, [AUDIOSTREAM_STATE_RUNNING](_o_h_audio.md) = 2, [AUDIOSTREAM_STATE_STOPPED](_o_h_audio.md) = 3,
[AUDIOSTREAM_STATE_RELEASED](_o_h_audio.md) = 4, [AUDIOSTREAM_STATE_PAUSED](_o_h_audio.md) = 5
} | 定义音频流的状态。 | | [OH_AudioStream_SourceType](_o_h_audio.md#oh_audiostream_sourcetype) { **AUDIOSTREAM_SOURCE_TYPE_INVALID** = -1, **AUDIOSTREAM_SOURCE_TYPE_MIC**, **AUDIOSTREAM_SOURCE_TYPE_VOICE_RECOGNITION** = 1, **AUDIOSTREAM_SOURCE_TYPE_VOICE_COMMUNICATION** = 7 } | 定义音频流使用场景。 | diff --git a/zh-cn/application-dev/reference/native-lib/third_party_libc/musl.md b/zh-cn/application-dev/reference/native-lib/third_party_libc/musl.md index 156462a966d6225f579b0b2b3617217a6ec8a142..5982b692cab7b7d1d7289fec15b430301e0a4679 100644 --- a/zh-cn/application-dev/reference/native-lib/third_party_libc/musl.md +++ b/zh-cn/application-dev/reference/native-lib/third_party_libc/musl.md @@ -35,33 +35,35 @@ libdl:dlopen等动态链接器接口,当前在OpenHarmony中是一个链接 4. dlopen支持直接加载zip包中未压缩的文件。 ### 调试能力 -提供了基础的log调试能力,方便开发者需要查看libc库内部异常。维测log的提供动态开关功能,不需要重新编译。在正式发布版本中,不建议使用,会影响运行性能。 +libc提供了动态使能维测log功能(默认关闭),供开发者需要的时候查看libc库异常。使用libc提供的动态使能维测log功能,不需要重新编译libc库,只需设置param属性即可。在正式发布版本中,不建议使能,会影响运行性能。 #### 1. musl.log功能 -设置musl.log.enable属性为true,打开musl的log打印。打印其他日志,需要先打开此开关。 +设置musl.log.enable属性为true,打开musl维测log打印。打印其他日志,需先打开此开关。 ``` -setparam musl.log.enable true +param set musl.log.enable true ``` #### 2. 加载器log功能 -调试程序引导,dlopen,dlclose等加载器接口,需要打开加载器log。用法如下: -* 使能全部应用的加载器log,谨慎使用 +加载器是libc中负责程序引导,dlopen,dlclose等动态链接程序,如需要查看动态加载过程异常,可以打开加载器log。用法如下: +* 使能全部应用的加载器log,log量比较大,请谨慎使用。 ``` -setparam musl.log.ld.app true +param set musl.log.ld.app true ``` -* 使能指定应用的加载器log,{app_name}需要替换成真实需要打印log的应用名字 +* 使能指定应用的加载器log,{app_name}需要替换成真实需要打印log的应用名字。 ``` -setparam musl.log.ld.all false -setparam musl.log.ld.app.{app_name} true +param set musl.log.ld.all false +param set musl.log.ld.app.{app_name} true ``` -* 打印全部应用除指定名字应用外的加载器日志 +* 打印全部应用除指定名字应用外的加载器日志。 ``` -setparam musl.log.ld.all true -setparam musl.log.ld.app.{app_name} false +param set musl.log.ld.all true +param set musl.log.ld.app.{app_name} false ``` -## musl不支持接口列表 +## musl不支持接口列表。 + [native api中没有导出的符号列表](musl-peculiar-symbol.md) + [native api由于权限管控可能调用失败的符号列表](musl-permission-control-symbol.md) diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index dc9f7c02d611087837948e2dea424e1f38c7f807..91f51fc3ef1734fe50eb0da158b4115fb8ebcd5b 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -2698,7 +2698,7 @@ ## ohos.permission.MANAGE_DEVICE_AUTH_CRED -允许应用调用设备认证华为帐号凭据管理应用接口。 +允许应用调用设备认证分布式帐号凭据管理应用接口。 **权限级别**:system_basic @@ -2707,3 +2707,27 @@ **ACL使能**:FALSE **起始版本**:10 + +## ohos.permission.UNINSTALL_BUNDLE + +允许应用卸载应用。 + +**权限级别**:system_core + +**授权方式**:system_grant + +**ACL使能**:TRUE + +**起始版本**:10 + +## ohos.permission.RECOVER_BUNDLE + +允许应用恢复预置应用。 + +**权限级别**:system_core + +**授权方式**:system_grant + +**ACL使能**:TRUE + +**起始版本**:10 diff --git a/zh-cn/application-dev/task-management/efficiency-resource-request.md b/zh-cn/application-dev/task-management/efficiency-resource-request.md index 0f011ed531a754852126a54bff5c536ff471f35b..3dbdaf18646b9197ea4c7ed5b299ecff3404ada9 100644 --- a/zh-cn/application-dev/task-management/efficiency-resource-request.md +++ b/zh-cn/application-dev/task-management/efficiency-resource-request.md @@ -33,10 +33,10 @@ | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | resourceTypes | number | 是 | 申请的资源类型 | -| isApply | boolean | 是 | 申请或释放资源
- ture表示申请资源
- false表示释放部分资源 | +| isApply | boolean | 是 | 申请或释放资源
- true表示申请资源
- false表示释放部分资源 | | timeOut | number | 是 | 资源使用时间(ms) | -| isPersist | boolean | 否 | 是否为永久持有资源,默认为false
- ture表示永久持有
- false表示有限时间内持有 | -| isProcess | boolean | 否 | 进程或应用申请,默认为false
- ture表示进程申请
- false表示应用申请 | +| isPersist | boolean | 否 | 是否为永久持有资源,默认为false
- true表示永久持有
- false表示有限时间内持有 | +| isProcess | boolean | 否 | 进程或应用申请,默认为false
- true表示进程申请
- false表示应用申请 | | reason | string | 是 | 申请资源原因 | **表3** 能效资源类型 @@ -67,7 +67,7 @@ // 应用需要在后台保持活动状态,不被挂起。 let request = { resourceTypes: backgroundTaskManager.ResourceType.CPU, // 资源类型是CPU资源,保证应用进程不被挂起 - isApply: true, // 释放资源 + isApply: true, // 申请资源 timeOut: 0, // 超时时间,超过超时时间后资源自动释放 reason: "apply", // 申请原因 isPersist: true, // 永久持有资源 diff --git a/zh-cn/application-dev/ui/arkts-routing.md b/zh-cn/application-dev/ui/arkts-routing.md index d2942ee01f323ab8184b863f14eebde15141135f..ae258c15c816e3c19df7f79131274551045344b0 100644 --- a/zh-cn/application-dev/ui/arkts-routing.md +++ b/zh-cn/application-dev/ui/arkts-routing.md @@ -323,3 +323,64 @@ function onBackClick() { ``` 当用户点击“返回”按钮时,会弹出自定义的询问框,询问用户是否确认返回。选择“取消”将停留在当前页目标页面;选择“确认”将触发router.back()方法,并根据参数决定如何执行跳转。 + +## 命名路由 + +在开发中为了跳转到[共享包中的页面](../quick-start/shared-guide.md)(即共享包中路由跳转),可以使用[router.pushNamedRoute()](../reference/apis/js-apis-router.md#routerpushnamedroute)来实现。 + +在使用页面路由Router相关功能之前,需要在代码中先导入Router模块。 + + +```ts +import router from '@ohos.router'; +``` + +在想要跳转到的[共享包](../quick-start/shared-guide.md)页面里,给[@Entry修饰的自定义组件](../quick-start/arkts-create-custom-components.md#entryoptions10)命名: + +```ts +// library/src/main/ets/pages/Index.ets +@Entry({ routeName : 'myPage' }) +@Component +struct MyComponent { +} +``` + +配置成功后需要在需要跳转的页面中引入命名路由的页面: + +```ts +// entry/src/main/ets/pages/Index.ets +import router from '@ohos.router'; +import '@ohos/library/src/main/ets/Index.ets' // 引入共享包library中的命名路由页面 + +@Entry +@Component +struct Index { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello World') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { // 点击跳转到其他共享包中的页面 + try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } + } + }) + } catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); + } + }) + } + .width('100%') + .height('100%') + } +} +``` + diff --git a/zh-cn/application-dev/ui/arkui-overview.md b/zh-cn/application-dev/ui/arkui-overview.md index c638196d60e87bba137c8e9bf6aa9923c707d6af..e1b1a3dc2500f6316adc895aaa558a2505e2bcf3 100644 --- a/zh-cn/application-dev/ui/arkui-overview.md +++ b/zh-cn/application-dev/ui/arkui-overview.md @@ -13,7 +13,7 @@ ## 两种开发范式 -针对不用的应用场景及技术背景,方舟开发框架提供了两种开发范式,分别是[基于ArkTS的声明式开发范式](arkts-ui-development-overview.md)(简称“声明式开发范式”)和[兼容JS的类Web开发范式](../ui/ui-js-overview.md)(简称“类Web开发范式”)。 +针对不同的应用场景及技术背景,方舟开发框架提供了两种开发范式,分别是[基于ArkTS的声明式开发范式](arkts-ui-development-overview.md)(简称“声明式开发范式”)和[兼容JS的类Web开发范式](../ui/ui-js-overview.md)(简称“类Web开发范式”)。 - **声明式开发范式**:采用基于TypeScript声明式UI语法扩展而来的[ArkTS语言](../quick-start/arkts-get-started.md),从组件、动画和状态管理三个维度提供UI绘制能力。 diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index c796d38d101485ff737ff0e020d20ed2f29ac7bc..34da0486fb94b7e71848b85a6dd2feb5f7f27eb5 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -402,6 +402,7 @@ - [异步并发概述](arkts-utils/async-concurrency-overview.md) - [单次I/O任务开发指导](arkts-utils/single-io-development.md) - 使用多线程并发能力进行开发 + - [多线程并发概述](arkts-utils/multi-thread-concurrency-overview.md) - [TaskPool和Worker的对比](arkts-utils/taskpool-vs-worker.md) - [CPU密集型任务开发指导](arkts-utils/cpu-intensive-task-development.md) - [I/O密集型任务开发指导](arkts-utils/io-intensive-task-development.md) @@ -510,6 +511,7 @@ - 相机最佳实践 - [拍照实现方案](media/camera-shooting-case.md) - [录像实现方案](media/camera-recording-case.md) + - [性能提升方案(仅对系统应用开放)](media/camera-preformance-imporvement.md) - 图片 - [图片开发概述](media/image-overview.md) - [图片解码](media/image-decoding.md) @@ -545,9 +547,9 @@ - [Hap包签名工具指导](security/hapsigntool-guidelines.md) - [HarmonyAppProvision配置文件](security/app-provision-structure.md) - AI - - [AI开发概述](./ai/ai-overview.md) - - [使用MindSpore Lite JS API开发AI应用](./ai/mindspore-guidelines-based-js.md) - - [使用MindSpore Lite Native API开发AI应用](./ai/mindspore-guidelines-based-native.md) + - [AI开发概述](ai/ai-overview.md) + - [使用MindSpore Lite JS API开发AI应用](ai/mindspore-guidelines-based-js.md) + - [使用MindSpore Lite Native API开发AI应用](ai/mindspore-guidelines-based-native.md) - 网络与连接 - 网络管理 - [网络管理开发概述](connectivity/net-mgmt-overview.md) @@ -559,6 +561,7 @@ - [网络连接管理](connectivity/net-connection-manager.md) - [MDNS管理](connectivity/net-mdns.md) - [流量管理](connectivity/net-statistics.md) + - [VPN管理](connectivity/net-vpn.md) - IPC与RPC通信 - [IPC与RPC通信概述](connectivity/ipc-rpc-overview.md) - [IPC与RPC通信开发指导](connectivity/ipc-rpc-development-guideline.md) @@ -625,12 +628,12 @@ - [设置分布式文件数据等级](file-management/set-security-label.md) - [跨设备文件访问](file-management/file-access-across-devices.md) - 后台任务(Background Task)管理 - - [后台任务概述](task-management/background-task-overview.md) - - [短时任务](task-management/transient-task.md) - - [长时任务](task-management/continuous-task.md) - - [延迟任务](task-management/work-scheduler.md) - - [代理提醒](task-management/agent-powered-reminder.md) - - [能效资源申请(仅对系统特权应用开放)](task-management/efficiency-resource-request.md) + - [后台任务总体概述](task-management/background-task-overview.md) + - [短时任务](task-management/transient-task.md) + - [长时任务](task-management/continuous-task.md) + - [延迟任务](task-management/work-scheduler.md) + - [代理提醒](task-management/agent-powered-reminder.md) + - [能效资源申请(仅对系统特权应用开放)](task-management/efficiency-resource-request.md) - 设备管理 - USB服务 - [USB服务开发概述](device/usb-overview.md) @@ -743,6 +746,8 @@ - [Neural Network Runtime对接AI推理框架开发指导](napi/neural-network-runtime-guidelines.md) - 内存管理 - [Purgeable memory开发指导](napi/purgeable-memory-guidelines.md) + - 设备管理 + - [USB DDK开发指导](napi/usb-ddk-guidelines.md) - 工具 - [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md) - 调试工具 @@ -958,20 +963,21 @@ - UI界面 - [@ohos.animator (动画)](reference/apis/js-apis-animator.md) - [@ohos.arkui.componentSnapshot (组件截图)](reference/apis/js-apis-arkui-componentSnapshot.md) + - [@ohos.arkui.componentUtils (componentUtils)](reference/apis/js-apis-arkui-componentUtils.md) + - [@ohos.arkui.dragController (DragController)](reference/apis/js-apis-arkui-dragController.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.inspector (布局回调)](reference/apis/js-apis-arkui-inspector.md) + - [ @ohos.arkui.performanceMonitor (性能监测)](reference/apis/js-apis-arkui-performancemonitor.md) - [@ohos.arkui.UIContext (UIContext)](reference/apis/js-apis-arkui-UIContext.md) - - [@ohos.arkui.componentUtils (componentUtils)](reference/apis/js-apis-arkui-componentUtils.md) - [@ohos.curves (插值计算)](reference/apis/js-apis-curve.md) - [@ohos.font (注册自定义字体)](reference/apis/js-apis-font.md) - [@ohos.matrix4 (矩阵变换)](reference/apis/js-apis-matrix4.md) + - [@ohos.measure (文本计算)](reference/apis/js-apis-measure.md) - [@ohos.mediaquery (媒体查询)](reference/apis/js-apis-mediaquery.md) - [@ohos.pluginComponent (PluginComponentManager)](reference/apis/js-apis-plugincomponent.md) - [@ohos.promptAction (弹窗)](reference/apis/js-apis-promptAction.md) - [@ohos.router (页面路由)](reference/apis/js-apis-router.md) - - [@ohos.measure (文本计算)](reference/apis/js-apis-measure.md) - [@ohos.uiAppearance (用户界面外观)](reference/apis/js-apis-uiappearance.md) - - [ @ohos.arkui.performanceMonitor (性能监测)](reference/apis/js-apis-arkui-performancemonitor.md) - 图形图像 - [@ohos.animation.windowAnimationManager (窗口动画管理)](reference/apis/js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (窗口扩展能力)](reference/apis/js-apis-application-windowExtensionAbility.md) @@ -985,12 +991,15 @@ - [webgl (WebGL)](reference/apis/js-apis-webgl.md) - [webgl2 (WebGL2)](reference/apis/js-apis-webgl2.md) - 媒体 + - [@ohos.app.ability.MediaControlExtensionAbility (播控扩展能力)](reference/apis/js-apis-app-ability-MediaControlExtensionAbility.md) - [@ohos.multimedia.audio (音频管理)](reference/apis/js-apis-audio.md) - [@ohos.multimedia.avsession (媒体会话管理)](reference/apis/js-apis-avsession.md) - [@ohos.multimedia.camera (相机管理)](reference/apis/js-apis-camera.md) - [@ohos.multimedia.image (图片处理)](reference/apis/js-apis-image.md) - [@ohos.multimedia.media (媒体服务)](reference/apis/js-apis-media.md) - [@ohos.multimedia.systemSoundManager (系统声音管理)](reference/apis/js-apis-systemSoundManager.md) + - application + - [MediaControlExtensionContext (播控扩展能力上下文)](reference/apis/js-apis-inner-application-MediaControlExtensionContext.md) - multimedia - [ringtonePlayer (铃声播放器)](reference/apis/js-apis-inner-multimedia-ringtonePlayer.md) - 资源管理 @@ -1038,8 +1047,8 @@ - [@ohos.file.fileuri (文件URI)](reference/apis/js-apis-file-fileuri.md) - [@ohos.file.fs (文件管理)](reference/apis/js-apis-file-fs.md) - [@ohos.file.hash (文件哈希处理)](reference/apis/js-apis-file-hash.md) - - [@ohos.file.picker (选择器)](reference/apis/js-apis-file-picker.md) - [@ohos.file.photoAccessHelper (相册管理模块)](reference/apis/js-apis-photoAccessHelper.md) + - [@ohos.file.picker (选择器)](reference/apis/js-apis-file-picker.md) - [@ohos.file.securityLabel (数据标签)](reference/apis/js-apis-file-securityLabel.md) - [@ohos.file.statvfs (文件系统空间统计)](reference/apis/js-apis-file-statvfs.md) - [@ohos.file.storageStatistics (应用空间统计)](reference/apis/js-apis-file-storage-statistics.md) @@ -1065,11 +1074,22 @@ - [@ohos.net.sharing (网络共享管理)](reference/apis/js-apis-net-sharing.md) - [@ohos.net.socket (Socket连接)](reference/apis/js-apis-socket.md) - [@ohos.net.statistics (流量管理)](reference/apis/js-apis-net-statistics.md) + - [@ohos.net.vpn (VPN管理)](reference/apis/js-apis-net-vpn.md) - [@ohos.net.webSocket (WebSocket连接)](reference/apis/js-apis-webSocket.md) - [@ohos.request (上传下载)](reference/apis/js-apis-request.md) - 通信与连接 + - [@ohos.bluetooth.a2dp(蓝牙a2dp模块)(推荐)](reference/apis/js-apis-bluetooth-a2dp.md) + - [@ohos.bluetooth.access(蓝牙access模块)(推荐)](reference/apis/js-apis-bluetooth-access.md) + - [@ohos.bluetooth.baseProfile(蓝牙baseProfile模块)(推荐)](reference/apis/js-apis-bluetooth-baseProfile.md) + - [@ohos.bluetooth.ble(蓝牙ble模块)(推荐)](reference/apis/js-apis-bluetooth-ble.md) + - [@ohos.bluetooth.connection(蓝牙connection模块)(推荐)](reference/apis/js-apis-bluetooth-connection.md) + - [@ohos.bluetooth.constant(蓝牙constant模块)(推荐)](reference/apis/js-apis-bluetooth-constant.md) + - [@ohos.bluetooth.hfp(蓝牙hfp模块)(推荐)](reference/apis/js-apis-bluetooth-hfp.md) + - [@ohos.bluetooth.hid(蓝牙hid模块)(推荐)](reference/apis/js-apis-bluetooth-hid.md) + - [@ohos.bluetooth.pan(蓝牙pan模块)(推荐)](reference/apis/js-apis-bluetooth-pan.md) + - [@ohos.bluetooth.socket(蓝牙socket模块)(推荐)](reference/apis/js-apis-bluetooth-socket.md) - [@ohos.bluetooth (蓝牙)(待停用)](reference/apis/js-apis-bluetooth.md) - - [@ohos.bluetoothManager (蓝牙)(推荐)](reference/apis/js-apis-bluetoothManager.md) + - [@ohos.bluetoothManager (蓝牙)(待停用)](reference/apis/js-apis-bluetoothManager.md) - [@ohos.connectedTag (有源标签)](reference/apis/js-apis-connectedTag.md) - [@ohos.nfc.cardEmulation (标准NFC-cardEmulation)](reference/apis/js-apis-cardEmulation.md) - [@ohos.nfc.controller (标准NFC)](reference/apis/js-apis-nfcController.md) @@ -1145,7 +1165,6 @@ - [@ohos.multimodalInput.touchEvent (触摸输入事件)](reference/apis/js-apis-touchevent.md) - [@ohos.multimodalInput.shortKey(快捷键)](reference/apis/js-apis-shortKey.md) - [@ohos.power (系统电源管理)](reference/apis/js-apis-power.md) - - [@ohos.resourceschedule.deviceStandby (设备待机模块)](reference/apis/js-apis-resourceschedule-deviceStandby.md) - [@ohos.runningLock (Runninglock锁)](reference/apis/js-apis-runninglock.md) - [@ohos.sensor (传感器)](reference/apis/js-apis-sensor.md) - [@ohos.settings (设置数据项名称)](reference/apis/js-apis-settings.md) @@ -1179,7 +1198,6 @@ - [@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.networkManager (网络管理)](reference/apis/js-apis-enterprise-networkManager.md) - [@ohos.enterprise.restrictions (限制类策略)](reference/apis/js-apis-enterprise-restrictions.md) - - [@ohos.enterprise.usbManager (USB管理)](reference/apis/js-apis-enterprise-usbManager.md) - [@ohos.enterprise.wifiManager (WiFi管理)](reference/apis/js-apis-enterprise-wifiManager.md) - 语言基础类库 - [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md) @@ -1389,6 +1407,7 @@ - [GridRow](reference/arkui-ts/ts-container-gridrow.md) - [Grid](reference/arkui-ts/ts-container-grid.md) - [GridItem](reference/arkui-ts/ts-container-griditem.md) + - [Hyperlink](reference/arkui-ts/ts-container-hyperlink.md) - [List](reference/arkui-ts/ts-container-list.md) - [ListItem](reference/arkui-ts/ts-container-listitem.md) - [ListItemGroup](reference/arkui-ts/ts-container-listitemgroup.md) @@ -1404,6 +1423,7 @@ - [Swiper](reference/arkui-ts/ts-container-swiper.md) - [Tabs](reference/arkui-ts/ts-container-tabs.md) - [TabContent](reference/arkui-ts/ts-container-tabcontent.md) + - [UIExtensionComponent](reference/arkui-ts/ts-container-ui-extension-component.md) - [WaterFlow](reference/arkui-ts/ts-container-waterflow.md) - 媒体组件 - [Video](reference/arkui-ts/ts-media-components-video.md) @@ -1437,6 +1457,7 @@ - [组件内转场](reference/arkui-ts/ts-transition-animation-component.md) - [共享元素转场](reference/arkui-ts/ts-transition-animation-shared-elements.md) - [组件内隐式共享元素转场](reference/arkui-ts/ts-transition-animation-geometrytransition.md) + - [路径动画](reference/arkui-ts/ts-motion-path-animation.md) - 全局UI方法 - 弹窗 - [警告弹窗](reference/arkui-ts/ts-methods-alert-dialog-box.md) @@ -1454,7 +1475,7 @@ - 已停止维护的组件 - [GridContainer](reference/arkui-ts/ts-container-gridcontainer.md) - 已停止维护的接口 - - [点击控制](reference/arkui-ts/ts-universal-attributes-click.md) + - [点击控制](reference/arkui-ts/ts-universal-attributes-click.md) - 组件参考(兼容JS的类Web开发范式-ArkUI.Full) - 组件通用信息 - [通用属性](reference/arkui-js/js-components-common-attributes.md) @@ -1689,6 +1710,7 @@ - [策略管理错误码](reference/errorcodes/errorcode-net-policy.md) - [MDNS错误码](reference/errorcodes/errorcode-net-mdns.md) - [流量管理错误码](reference/errorcodes/errorcode-net-statistics.md) + - [VPN错误码](reference/errorcodes/errorcode-net-vpn.md) - 通信与连接 - [Bluetooth错误码](reference/errorcodes/errorcode-bluetoothManager.md) - [WIFI错误码](reference/errorcodes/errorcode-wifi.md) @@ -1756,11 +1778,13 @@ - [AVDemuxer](reference/native-apis/_a_v_demuxer.md) - [AVSource](reference/native-apis/_a_v_source.md) - [OHAudio](reference/native-apis/_o_h_audio.md) + - [AVScreenCapture](reference/native-apis/_a_v_screen_capture.md) - [HuksKeyApi](reference/native-apis/_huks_key_api.md) - [HuksParamSetApi](reference/native-apis/_huks_param_set_api.md) - [HuksTypeApi](reference/native-apis/_huks_type_api.md) - [Init](reference/native-apis/init.md) - [Memory](reference/native-apis/memory.md) + - [UsbDdk](reference/native-apis/_usb_ddk.md) - [Hitrace](reference/native-apis/_hitrace.md) - [Vulkan](reference/native-apis/_vulkan.md) - 头文件 @@ -1816,6 +1840,9 @@ - [native_audiorenderer.h](reference/native-apis/native__audiorenderer_8h.md) - [native_audiostream_base.h](reference/native-apis/native__audiostream__base_8h.md) - [native_audiostreambuilder.h](reference/native-apis/native__audiostreambuilder_8h.md) + - [native_avscreen_capture.h](reference/native-apis/native__avscreen__capture_8h.md) + - [native_avscreen_capture_base.h](reference/native-apis/native__avscreen__capture__base_8h.md) + - [native_avscreen_capture_errors.h](reference/native-apis/native__avscreen__capture__errors_8h.md) - [native_huks_api.h](reference/native-apis/native__huks__api_8h.md) - [native_huks_param.h](reference/native-apis/native__huks__param_8h.md) - [native_huks_type.h](reference/native-apis/native__huks__type_8h.md) @@ -1827,6 +1854,8 @@ - [relational_store.h](reference/native-apis/relational__store_8h.md) - [syscap_ndk.h](reference/native-apis/syscap__ndk_8h.md) - [purgeable_memory.h](reference/native-apis/purgeable__memory_8h.md) + - [usb_ddk_api.h](reference/native-apis/usb__ddk__api_8h.md) + - [usb_ddk_types.h](reference/native-apis/usb__ddk__types_8h.md) - [trace.h](reference/native-apis/trace_8h.md) - [vulkan_ohos.h](reference/native-apis/vulkan__ohos_8h.md) - 结构体 @@ -1871,6 +1900,17 @@ - [OH_AVRange](reference/native-apis/_o_h___a_v_range.md) - [OH_AudioCapturer_Callbacks_Struct](reference/native-apis/_o_h___audio_capturer___callbacks___struct.md) - [OH_AudioRenderer_Callbacks_Struct](reference/native-apis/_o_h___audio_renderer___callbacks___struct.md) + - [OH_AudioBuffer](reference/native-apis/_o_h___audio_buffer.md) + - [OH_AudioCaptureInfo](reference/native-apis/_o_h___audio_capture_info.md) + - [OH_AudioEncInfo](reference/native-apis/_o_h___audio_enc_info.md) + - [OH_AudioInfo](reference/native-apis/_o_h___audio_info.md) + - [OH_AVScreenCaptureCallback](reference/native-apis/_o_h___a_v_screen_capture_callback.md) + - [OH_AVScreenCaptureConfig](reference/native-apis/_o_h___a_v_screen_capture_config.md) + - [OH_RecorderInfo](reference/native-apis/_o_h___recorder_info.md) + - [OH_Rect](reference/native-apis/_o_h___rect.md) + - [OH_VideoCaptureInfo](reference/native-apis/_o_h___video_capture_info.md) + - [OH_VideoEncInfo](reference/native-apis/_o_h___video_enc_info.md) + - [OH_VideoInfo](reference/native-apis/_o_h___video_info.md) - [OH_Huks_Blob](reference/native-apis/_o_h___huks___blob.md) - [OH_Huks_CertChain](reference/native-apis/_o_h___huks___cert_chain.md) - [OH_Huks_KeyInfo](reference/native-apis/_o_h___huks___key_info.md) @@ -1889,6 +1929,17 @@ - [OH_Rdb_Store](reference/native-apis/_o_h___rdb___store.md) - [OH_VBucket](reference/native-apis/_o_h___v_bucket.md) - [OH_VObject](reference/native-apis/_o_h___v_object.md) + - [UsbConfigDescriptor](reference/native-apis/_usb_config_descriptor.md) + - [UsbControlRequestSetup](reference/native-apis/_usb_control_request_setup.md) + - [UsbDdkConfigDescriptor](reference/native-apis/_usb_ddk_config_descriptor.md) + - [UsbDdkEndpointDescriptor](reference/native-apis/_usb_ddk_endpoint_descriptor.md) + - [UsbDdkInterface](reference/native-apis/_usb_ddk_interface.md) + - [UsbDdkInterfaceDescriptor](reference/native-apis/_usb_ddk_interface_descriptor.md) + - [UsbDeviceDescriptor](reference/native-apis/_usb_device_descriptor.md) + - [UsbDeviceMemMap](reference/native-apis/_usb_device_mem_map.md) + - [UsbEndpointDescriptor](reference/native-apis/_usb_endpoint_descriptor.md) + - [UsbInterfaceDescriptor](reference/native-apis/_usb_interface_descriptor.md) + - [UsbRequestPipe](reference/native-apis/_usb_request_pipe.md) - [VkExternalFormatOHOS](reference/native-apis/_vk_external_format_o_h_o_s.md) - [VkImportNativeBufferInfoOHOS](reference/native-apis/_vk_import_native_buffer_info_o_h_o_s.md) - [VkMemoryGetNativeBufferInfoOHOS](reference/native-apis/_vk_memory_get_native_buffer_info_o_h_o_s.md) @@ -1915,7 +1966,7 @@ - 常见问题 - [如何编译full-SDK](faqs/full-sdk-compile-guide.md) - [如何替换full-SDK](faqs/full-sdk-switch-guide.md) - - [如何在CMake工程中使用OpenHarmony SDK的Native API(NDK)](faqs/howto-migrate-cmake-with-ohosndk.md) + - [如何在CMake工程中使用NDK](faqs/cmake-with-ndk.md) - [应用模型常见问题](faqs/faqs-ability.md) - ArkUI框架开发常见问题(ArkTS) - [ArkTS语法使用常见问题](faqs/faqs-arkui-arkts.md) diff --git a/zh-cn/contribute/template/js-template.md b/zh-cn/contribute/template/js-template.md index f6e70d3a5ddad3fd49ad8f0bd06f93adde428618..0f566ba3a7cc51351fc09a46fd20c56a5bb94b39 100644 --- a/zh-cn/contribute/template/js-template.md +++ b/zh-cn/contribute/template/js-template.md @@ -7,7 +7,7 @@ | | 说明项 | 细则 | | ---- | --------------------------------- | ------------------------------------------------------------ | | 1 | 客户化写作基本要求 | **写作中,请变身开发者,对于开发者使用该API时所需的使用场景、参数选取原则、开发建议/经验、示例等信息进行清晰描述,达到指导开发者顺利使用本API进行开发的目标。** | -| 2 | 上传路径 | markdown文件:docs/zh-cn/application-dev/reference/apis
图片路径:docs/zh-cn/application-dev/reference/apis/figures,并在markdown文件中通过路径`![](figures/xxx.jpg)`或`![](figures/xxx.png)`引用。 | +| 2 | 上传路径 | markdown文件:docs/zh-cn/application-dev/reference/apis
图片路径:docs/zh-cn/application-dev/reference/apis/figures,并在markdown文件中通过路径\![]\(figures/xxx.jpg)或\![]\(figures/xxx.png)引用。 | | 3 | 文件命名 | 一个d.ts对应一个js api文档,文件名称应与模块名称保持一致,格式为:**js-apis-模块名.md**。
示例:
媒体@ohos.multimedia.audio,文件命名为:js-apis-audio.md
电话@ohos.telephony.sms,文件命名为:js-apis-sms.md | | 4 | 目录修改 | 新增文件,需要修改对应的Readme,即`docs/zh-cn/application-dev/reference/apis/Readme-CN.md`。
目录按字母顺序排列。 | | 5 | 文档结构 | - 模块说明
- 起始版本说明
- 导入模块/使用说明
- 接口(属性、常量、方法、枚举、自定义类型)
描述顺序和代码保持一致,如果某些接口具有逻辑顺序,请注意排列。 | diff --git a/zh-cn/contribute/template/ts-template.md b/zh-cn/contribute/template/ts-template.md index bd2076bc45b2f23fc98729df97c4a9415099ddc4..d64b416bca993bdb6808a22cf5a82d7311cbf34c 100644 --- a/zh-cn/contribute/template/ts-template.md +++ b/zh-cn/contribute/template/ts-template.md @@ -6,7 +6,7 @@ | ---- | ----------- | ---------------------------------------- | | 1 | 客户化写作基本要求 | **写作中,请变身开发者,对于开发者使用该组件时所需的使用场景、参数选取原则、开发建议/经验、示例等信息进行清晰描述,达到指导开发者顺利使用本组件进行开发的目标。** | | 2 | | **所有的写作说明,在完成写作后,都要删除。** | -| 3 | 上传路径 | markdown文件:docs/zh-cn/application-dev/reference/arkui-ts
图片路径:docs/zh-cn/application-dev/reference/arkui-ts/figures,并在markdown文件中通过路径`![](figures/xxx.jpg)`或`![](figures/xxx.png)`引用。 | +| 3 | 上传路径 | markdown文件:docs/zh-cn/application-dev/reference/arkui-ts
图片路径:docs/zh-cn/application-dev/reference/arkui-ts/figures,并在markdown文件中通过路径\![]\(figures/xxx.jpg)或\![]\(figures/xxx.png)引用。 | | 4 | 文件命名 | 一个d.ts对应一个组件文档,文件名称需包含组件所属类和组件名,格式为:**ts-组件所属类名-组件名.md**。
示例:
基础组件text,文件命名为:ts-basic-component-text.md
容器组件list,文件命名为:js-container-component-list.md | | 5 | 目录修改 | 新增文件,需要修改对应的Readme,即`docs/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md`。 | | 6 | 文档结构 | - 模块说明
- 起始版本说明
- 导入模块/使用说明
- 权限说明
- 接口、属性、事件、对象、枚举、自定义类型
描述顺序和代码保持一致,如果某些接口具有逻辑顺序,请注意排列。 | diff --git "a/zh-cn/design/ux-design/figures/OpenHarmony\345\272\224\347\224\250\345\233\276\346\240\207\346\250\241\347\211\210.zip" "b/zh-cn/design/ux-design/figures/OpenHarmony\345\272\224\347\224\250\345\233\276\346\240\207\346\250\241\347\211\210.zip" index 0d602f61f6835802452e124de56692d265e5f386..b115633098fa5c8170a65665859eaa697a3c6706 100644 --- "a/zh-cn/design/ux-design/figures/OpenHarmony\345\272\224\347\224\250\345\233\276\346\240\207\346\250\241\347\211\210.zip" +++ "b/zh-cn/design/ux-design/figures/OpenHarmony\345\272\224\347\224\250\345\233\276\346\240\207\346\250\241\347\211\210.zip" @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d29115dec3138599c50b9a1c5fd69b337ed90c57539f140d6896f9e464db7f7c -size 20190 +oid sha256:2a79d4a6541f2502fecf2741eb5a8a89d3b9ae69e216b19845e591b114e7e0d7 +size 7743 diff --git a/zh-cn/device-dev/device-test/developer_test.md b/zh-cn/device-dev/device-test/developer_test.md index 030b8209cb7a62755e518065b923737fd2f80377..76f3cc374931bd7af63bb29643a8153b50c1bb0b 100644 --- a/zh-cn/device-dev/device-test/developer_test.md +++ b/zh-cn/device-dev/device-test/developer_test.md @@ -95,7 +95,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 6. 如果设备仅支持串口输出测试结果,则需要安装NFS Server - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 此操作针对小型或轻量设备,不针对标准设备。 @@ -656,7 +656,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ``` module_output_path = "developertest/calculator" ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 此处输出路径为部件/模块名。 @@ -669,7 +669,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 include_dirs = [ "../../../include" ] } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 一般在此处对相关配置进行设置,在测试用例编译脚本中可直接引用。 @@ -694,7 +694,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 根据测试类型的不同,在具体编写过程中可选择不同的测试类型。 > - ohos_unittest:单元测试 @@ -715,7 +715,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 deps = [":CalculatorSubTest"] } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 进行条件分组的目的在于执行用例时可以选择性地执行某一种特定类型的用例。 @@ -760,7 +760,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ``` module_output_path = "developertest/app_info" ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 此处输出路径为部件/模块名。 @@ -770,7 +770,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ohos_js_unittest("GetAppInfoJsTest") { } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > - 使用模板ohos_js_unittest定义js测试套,注意与C++用例区分。 > - js测试套编译输出文件为hap类型,hap名为此处定义的测试套名,测试套名称必须以JsTest结尾。 @@ -857,7 +857,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 deps = [ ":GetAppInfoJsTest" ] } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 进行条件分组的目的在于执行用例时可以选择性地执行某一种特定类型的用例。 @@ -920,7 +920,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ``` want_output_path = "developertest/stage_test" ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 此处输出路径为部件/模块名。 @@ -930,7 +930,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ohos_js_stage_unittest("ActsBundleMgrStageEtsTest") { } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 使用模板ohos_js_stage_unittest定义stage模型的ArkTs测试套。 @@ -975,7 +975,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 deps = [ ":GetAppInfoJsTest" ] } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 进行条件分组的目的在于执行用例时可以选择性地执行某一种特定类型的用例。 @@ -1006,7 +1006,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 "//test/testfwk/developer_test/examples/calculator/test:fuzztest" } ``` -> ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** +> **说明:** > > test_list中配置的是对应模块的测试用例。 @@ -1039,7 +1039,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" } ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > >- target_name: 测试套的名称,定义在测试目录的BUILD.gn中。preparer: 表示该测试套执行前执行的动作。 >- src="res": 表示测试资源位于test目录下的resource目录下,src="out":表示位于out/release/$(部件)目录下。 @@ -1099,7 +1099,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ``` -> ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** +> **说明:** > > 在执行测试用例之前,若使用HDC连接设备,用例仅需配置设备IP和端口号即可,其余信息均默认不修改。 @@ -1111,7 +1111,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ./build.sh --product-name {product_name} --build-target make_test ``` -> ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** +> **说明:** > >- product-name:指定编译产品名称。 >- build-target:指定所需编译用例,make_test表示指定全部用例,实际开发中可指定特定用例。 @@ -1123,7 +1123,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 2. 从Linux环境拷贝测试框架developertest和xdevice到创建的Test目录下,拷贝编译好的测试用例到testcase目录下。 - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 将测试框架及测试用例从Linux环境移植到Windows环境,以便后续执行。 @@ -1138,7 +1138,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 D:\Test\testcase\tests ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > ``标签表示是否需要编译用例;``标签表示测试用例查找路径。 @@ -1202,7 +1202,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 hdc_std kill hdc_std -m -s 0.0.0.0:8710 ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > IP和端口号为默认值。 @@ -1210,7 +1210,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ``` hdc_std -s xx.xx.xx.xx:8710 list targets ``` - > ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** + > **说明:** > > 此处IP填写设备侧IP地址。 @@ -1343,7 +1343,7 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ``` test/developertest/reports/xxxx_xx_xx_xx_xx_xx ``` -> ![icon-note.gif](/zh-cn/device-dev/driver/public_sys-resources/icon-note.gif) **说明:** +> **说明:** > > 测试报告文件目录将自动生成。 diff --git a/zh-cn/device-dev/subsystems/subsys-build-component.md b/zh-cn/device-dev/subsystems/subsys-build-component.md index 25211ea1daa6840f87137057a965deaef144dae7..3945679dc39c3ef13a630fa1a6dfe795fbc967ad 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-component.md +++ b/zh-cn/device-dev/subsystems/subsys-build-component.md @@ -34,7 +34,8 @@ ], "third_party": [ # 部件依赖的三方开源软件 "bounds_checking_function" - ] + ], + "hisysevent_config": [] # 部件HiSysEvent打点配置文件编译入口 } "build": { # 编译相关配置 "sub_component": [ @@ -61,6 +62,8 @@ component 部件配置中需要配置部件的名称、源码路径、功能简介、是否必选、编译目标、RAM、ROM、编译输出、已适配的内核、可配置的特性和依赖等属性定义。 +> **注意**:部件配置中HiSysEvent打点配置文件使用说明,请参考文档[HiSysEvent打点配置](subsys-dfx-hisysevent-logging-config.md)。 + 新增部件时需要在对应子系统json文件中添加相应的部件定义。产品所配置的部件必须在某个子系统中被定义过,否则会校验失败。 ### 新增并编译部件 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md index 175b49816ea59a74ed28651cdca2b607fc8f1c7d..7f94d9ac9fa80ddbee3e1aa5ec3c5944a235c8e8 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md @@ -33,10 +33,11 @@ | 字段名称 | 描述 | | -------- | -------- | - | type | 字段说明:必选字段,用来标识该事件名称的类型。
取值范围:
- FAULT:错误类型。
- STATISTIC:统计类型。
- SECURITY:安全性。
- BEHAVIOR:用户行为。 | + | type | 字段说明:必选字段,用来标识该事件名称的类型。
取值范围:
- FAULT:故障类型。
- STATISTIC:统计类型。
- SECURITY:安全类型。
- BEHAVIOR:行为类型。 | | level | 字段说明:必选字段,用来标识该事件名称的级别。
取值范围:
- CRITICAL:严重。
- MINOR:一般。 | - | tag | 字段说明:可选字段,用来标识该事件名称的标签。
定义规则:
- 最多可同时定义5个标签,标签之间使用空格来分隔。
- 单个标签最多包含16个字符,字符范围[a-zA-Z0-9] | - | desc | 字段说明:必选字段,用来对该事件名称进行描述。
定义规则:
- 至少包含3个字符,最多包含128个字符,字符范围[a-zA-Z0-9 _] | + | tag | 字段说明:可选字段,用来标识该事件名称的标签。
定义规则:
- 最多可同时定义5个标签,标签之间使用空格来分隔。
- 单个标签最多包含16个字符,字符范围[a-zA-Z0-9]。 | + | desc | 字段说明:必选字段,用来对该事件名称进行描述。
定义规则:
- 至少包含3个字符,最多包含128个字符。 | + | preserve | 字段说明:可选字段,用来标识事件是否需要落盘,默认值为true。
取值范围:
- true:事件需要落盘。
- false:事件不需要落盘。 | **表2** 自定义参数字段说明 @@ -44,7 +45,7 @@ | -------- | -------- | | type | 字段说明:必选字段,用来标识该参数的类型。
取值范围:
- BOOL
- INT8
- UINT8
- INT16
- UINT16
- INT32
- UINT32
- INT64
- UINT64
- FLOAT
- DOUBLE
- STRING | | arrsize | 字段作用:可选字段,用来标识数组类型参数的长度。
取值范围:
- 1~100 | - | desc | 字段作用:必选字段,用来对该参数进行描述。
定义规则:
- 至少包含3个字符,最多包含128个字符,字符范围[a-zA-Z0-9 _] | + | desc | 字段作用:必选字段,用来对该参数进行描述。
定义规则:
- 至少包含3个字符,最多包含128个字符。 | ## 开发步骤 diff --git a/zh-cn/readme/figures/build_framework_ZN.png.PNG b/zh-cn/readme/figures/build_framework_ZN.png similarity index 100% rename from zh-cn/readme/figures/build_framework_ZN.png.PNG rename to zh-cn/readme/figures/build_framework_ZN.png diff --git a/zh-cn/release-notes/OpenHarmony-v4.0-beta2.md b/zh-cn/release-notes/OpenHarmony-v4.0-beta2.md new file mode 100644 index 0000000000000000000000000000000000000000..0f9712fcc55a77b68794ddc3e89079a00d4866d0 --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v4.0-beta2.md @@ -0,0 +1,450 @@ +# OpenHarmony 4.0 Beta2 + +## 版本概述 + +OpenHarmony 4.0版本标准系统能力持续完善:ArkUI进一步增强基础组件能力,应用框架支持ArkTS卡片代理刷新,应用包支持应用、支持原子化服务数据共享、支持企业应用的安装管理,分布式软总线支持会话级的传输能力协商,分布式数据管理UDMF(统一数据管理框架)支持跨设备拖拽场景下对分布式目录的文件临时授权、文件管理支持公共图片文件在设备端和云端进行同步,媒体进一步增强音频/媒体播放/音视频编解码能力,图形渲染库升级至Skia 0310新版本,窗口控件化能力继续增强,事件通知支持选定通知并批量删除通知,安全基础提供DSA数字签名算法能力,ArkCompiler方舟运行时支持JSContext功能、支持动态PGO功能,DFX提供统一的采集框架能力,方便开发者对应用的调试调测。 + +## 特性说明 + + +### 应用框架 + +- 更新ArkTS卡片刷新方式,支持通过数据代理的方式刷新内容。 + +- ArkTS卡片支持静态卡片配置、静态图展示。 + + +### ArkUI + +- Xcomponent组件支持Texture模式绘制、popup支持位置自定义、弹框支持通过键盘ESC键逐层退出、ListItem支持长距离左滑删除手势、ArkTS/JS卡片支持渲染完成回调、Image/Text组件支持隐私遮罩、ContextMenu支持分段显示能力。 + +- 动画效果增强,包括:布局属性、背景图片大小位置属性、显隐属性支持隐式动效,list支持scrollToIndex动效、Tabs模糊动效、popup出现/消失动效,支持自定义动画,满足开发者多种多样动画诉求。 + +- 开发效率增强:支持命名路由的能力,借助此能力可针对不同页面设置不同的切换动效;轻量级ArkUI框架支持定义全局数据对象,可进行应用内页面间的数据共享。 + +- 全局API支持Stage模型多实例场景。 + + +### 应用包管理 + +- 支持对应用分发类型和附件信息的设置和查询。 + +- 支持通过文件扩展名列出支持打开该文件的应用列表,实现了文件扩展名与应用的匹配关系。 + +- 支持企业应用的安装管理,对于证书类型为“enterprise”的应用,安装需要申请“ohos.permission.INSTALL_ENTERPRISE_BUNDLE”。 + + +### 分布式数据管理 + +- UDMF(统一数据管理框架)支持跨设备拖拽场景下对分布式目录的文件临时授权。 + +- 提供RDBstore NDK接口 :包含增/删/改/查/事务、数据加密、数据分级保护、备份/恢复能力。 + +- Key-Value和分布式数据对象支持根据数据量自动选择数据同步的通道。系统会根据数据量大小自动选择蓝牙通道或基于WiFi的P2P通道进行数据的同步。 + + +### 分布式软总线 + +- 支持对基于软总线连接的link信息进行管理。 + +- 支持会话级的传输能力协商,可通过协商确定设备间传输的能力。 + + +### 分布式硬件 + +- 分布式场景下的音频录制时延性能得到优化。 + +- 分布式文件系统支持在以蓝牙引导的P2P连接环境下进行文件互访。 + +- 支持组网设备名称变化的监听。 + + +### 文件管理 + +- 支持公共图片文件在设备端和云端进行同步(设备登录的帐号需开通云端服务),支持通过picker选择云端的图片。 + +- 支持应用定制备份恢复的目录。 + +- 支持公共图片的分类管理,用户可以在图库中通过相册对用户图片进行组织分类。 + +- 支持应用监听沙箱内的文件的增改删。 + +- 支持应用跨设备分享沙箱内的文件。 + + +### 图形显示及窗口 + +**图形** + +- 支持对选定区域取色,可选定区域后获得该区域的主色值、平均色值等参数并按需使用。 + +- 支持设置旋转中心在Z轴锚点的偏移,允许在旋转过程中修改渲染的锚点。 + +- 图形处理依赖的渲染库升级至Skia 0310新版本,提升了显示性能。 + +**窗口** + +- 优化了display模块的参数值获取方式,从原先软件方式优化为从硬件直接获取真实值。 + +- 窗口控件化能力增强:窗口以控件化的方式支持窗口属性、子窗口、模态窗口、窗口效果、窗口装饰、亮灭屏流程、截屏录屏。 + + +### 媒体 + +**音频** + +- 支持音效框架:设备厂商可配置音效策略和加载自定义音效;应用可查询音频输出的音效模式,切换或关闭音效模式。 + +- 支持系统内录音能力:可根据音频场景属性筛选,录制系统内播放的音频数据。 + +- 支持获取音频设备显示名:播放对象详细信息内可获取当前播放输出归属的设备名。 + +**媒体播放** + +支持音效参数配置,可以在音频框架支持音效的能力基础上进一步配置音效。 + +**音视频编解码** + +- 支持通过Native API查询系统的音视频编解码能力。 + +- 支持通过Native API完成音视频封装,即将音频、视频等编码后的媒体数据,按一定的格式存储到文件里。 + +- 支持通过Native API完成音视频解封装,即从比特流数据中取出音频、视频等媒体帧数据。 + + +### 事件通知 + +- 支持选定通知并批量删除通知。 + +- emitter支持取消按条件指定订阅回调能力。 + + +### 基础通信 + +- WiFi支持后台扫描的能力。 + +- WiFi支持STA模式下的随机MAC能力。 + + +### 网络与通信 + +- 支持与服务器端通过TCP Socket进行通信。 + +- 支持用户将数据传送到远程服务器。 + +- 支持HTTPS证书的管理适配。 + +- 支持网卡代理。 + + +### 系统服务管理 + +- 支持系统服务按需启动,例如外部调用、事件触发,同时支持在设备空闲时自动退出系统服务。 + +- 系统服务配置格式优化,使用JSON格式替代XML格式。 + + +### 电源 + +- 新增接口,支持设置系统立即进入睡眠状态。 + +- 新增休眠源定制能力,支持根据不同的休眠源定制事件及行为。 + +- 新增唤醒源定制能力,支持根据不同的唤醒源定制唤醒事件。 + + +### 多模输入 + +- 支持将键盘输入设备的原始事件映射为归一化交互的意图事件,使开发者在开发应用时无需关注输入行为是来自触控还是键盘。 + +- 支持用户根据个人习惯设置触控板功能的个性化配置: + - 支持两种触发模式映射鼠标左键功能: 按压、轻点。 + - 支持两种触发模式映射鼠标右键功能:点按左/右下角、双指点按或轻点。 + - 跟踪速度:支持10档速度调节。 + - 支持两种交互模式映射鼠标滚轮功能:内容随手指移动方向、内容随手指反向移动。 + + +### 主题框架 + +- 锁屏管理服务支持锁屏事件回调机制、静态/动态壁纸、查询锁屏时的业务状态。 + +- 壁纸管理服务支持自定义壁纸、锁屏/解锁操作、重置壁纸。 + + +### 上传下载 + +支持查询上传和下载的任务、任务状态信息同步和任务记录持久化、任务状态查询和异常的恢复。 + + +### 安全 + +**加解密算法库框架** + +- 提供DSA数字签名算法能力。 + +- 提供DSA、ECC、RSA密钥解析和密钥参数的获取能力。 + +- 提供安全随机数生成算法类型的获取能力。 + +- 提供SM4密钥的随机生成与转换,以及加密解密能力。 + +- 提供SM3密钥的HMAC和HASH的能力。 + +- 提供SM2密钥的随机生成与转换、签名及验签、以及加密解密能力。 + +**密钥管理** + +- 支持HUKS密钥加密保护。 + +- 支持KeyAttestation公钥证书中增加对密钥所属业务身份字段。 + +- 支持标准HDI南向接口。 + +**设备互信认证** + +支持在以下两种场景的设备间互信认证流程中生成假名,支持识别及和标识设备的假名化名称。 + +- 对使用同帐号登录的多个设备进行互信认证。 + +- 对非同帐号的点对点互联的两个设备进行互信认证。 + + +### 程序访问控制 + +- 优化权限管理的菜单呈现,拆分媒体和文件的权限组,相应权限的授权粒度更加精细化。 + +- 支持treble架构下对SELinux的兼容能力。 + + +### 帐号 + +- 支持帐号授权能力扩展和三方应用使用帐号授权能力。 + +- 支持对域帐号插件的管理,从而支持域帐号管理和认证能力。 + + +### WebView + +- W3C能力补充完善:补充Web Camera能力,以及bindContextMenu、Select、date类型input等H5标签能力。 + +- 支持多渲染进程的进程拆分。 + +- 支持文字、图片基础拖拽能力。 + +- 支持WebRTC的视频会议能力(不含摄像头共享)。 + +- 支持渲染进程独立SELinux标签,增强安全基础能力。 + + +### ArkCompiler + +- 方舟运行时支持JSContext功能;支持动态PGO功能,可采集运行期的类型和函数热点信息,并生成AP文件;支持动态import加载NAPI库。 + +- 方舟编译器type编译模式下前端编译工具链切换到es2abc。 + +- NAPI buffer、object、arraybuffer、object type接口功能补齐。 + +- Taskpool支持任务中断和取消,支持定义任务组(TaskGroup),支持对任务的状态和调度信息进行打点,支持超长等待的任务进行识别和恢复。 + +- 编译构建能力提供OpenHarmony系统user和root不同权限版本的构建,user版本能力同步支持Wukong测试工具和XTS测试能力。 + +- 编译工具链支持预览器上的调试能力。 + + +### DFX + +- 提供统一的采集框架能力,方便开发者对应用的调试调测。 + +- 提供统一的trace采集能力。 + +- 提供Native的HiTraceMeter打点接口。 + +- 性能雷达提供工具类,方便各业务模块(子系统)在业务流程上传递性能埋点记录及结算性能数据。 + + +### 内核 + +代码执行权限管控能力增强,新增了以下能力: + +- 支持安全内存机制。 + +- 提供满足不同场景的代码执行权限管控策略。 + +- 提供代码执行权限管控的全生命周期管理能力。 + +- 支持解析可执行文件获取代码段信息。 + +- 支持代码页的完整性保护能力。 + + +### 驱动 + +- 扩展设备驱动框架提供以下能力: + - 扩展设备驱动框架基于“驱动扩展Ability(DriverExtensionAbility)”的能力,构建应用态扩展驱动包的开发、部署、安装、更新、卸载、运行能力,开放全流程生命周期管理能力。 + - 支持三方设备厂商开发的非标准协议的可插拔USB设备扩展驱动包,正常安装到OpenHarmony系统。插入USB设备后,能正常识别USB设备并与扩展驱动包匹配。 + - 支持三方应用通过扩展外部设备管理框架查询并绑定USB设备扩展驱动包,完成对扩展驱动包定制功能的操作。 + +- 相机驱动提供以下能力: + - 提供USB相机热插拔识别能力,支持开机启动检查识别和启动后热插拔识别。 + - 支持USB相机的预览、拍照、录像能力,提供相机格式、分辨率查询和配置能力。 + +- 编解码驱动提供JPEG图片硬件解码加速能力,包括获取硬件解码信息,初始化/去初始化,解码,申请/释放buffer,提升用户浏览图片流畅度体验。 + +- 传感器驱动提供温湿度传感器设备驱动能力,支持小型设备温湿度器件查询,器件使能/去使能,数据查询能力,丰富智能设备传感器能力。 + + +## 配套关系 + +**表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 4.0 Beta2 | NA | +| Public SDK | Ohos_sdk_public 4.0.9.6 (API Version 10 Beta2) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。通过DevEco Studio默认获取的SDK为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 4.0 Beta2 | OpenHarmony应用开发推荐使用。获取方式:
[Windows(64-bit)](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_package_901_9/9b/v3/2g1w9tlbQPevu9IkTNRhNw/devecostudio-windows-4.0.0.400.zip?HW-CC-KV=V1&HW-CC-Date=20230804T022932Z&HW-CC-Expire=315360000&HW-CC-Sign=23242113800451447FF87450B938F6B3A3B27A7360C10FBF7BCAB10B24473326)
SHA256校验码:ae9b228fb1f79e99441e10bdcf347ebfc42266be8b170bbce3c9764ba32d82a4
[Mac(X86)](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_package_901_9/38/v3/RTDABg5YQt69xo6_WHnI3Q/devecostudio-mac-4.0.0.400.zip?HW-CC-KV=V1&HW-CC-Date=20230804T022845Z&HW-CC-Expire=315360000&HW-CC-Sign=4229D218C19968570755D8853840C8E2128E871EE895BCA45160743352191975)
SHA256校验码:5c9afc5b1262868b58376155f1e8576d33c1ade8b01091edc4d7d397cd34026c
[Mac(ARM)](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_package_901_9/5d/v3/d1TVEw9GTLaps_3giDK4NQ/devecostudio-mac-arm-4.0.0.400.zip?HW-CC-KV=V1&HW-CC-Date=20230804T023035Z&HW-CC-Expire=315360000&HW-CC-Sign=B088BE6D5E2A28E21512F8396D09DDD4C6C41E75E03DFF32830ECC8E7B467D42)
SHA256校验码:ea6c98cafd5036e4a6fd46b0b1cde3a306953b1eef423d5940f1af7c632205d6 | +| HUAWEI DevEco Device Tool(可选) | 4.0 Beta1 | OpenHarmony智能设备集成开发环境推荐使用。获取方式:
[点击跳转至下载页面](https://device.harmonyos.com/cn/develop/ide#download) | + + +## 源码获取 + + +### 前提条件 + +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 OpenHarmony-4.0-Beta2 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- 从版本发布Tag节点获取源码。可获取与版本发布时完全一致的源码。 + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v4.0-Beta2 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +**方式二** + +通过repo + https 下载。 + +- 从版本分支获取源码。可获取该版本分支的最新源码,包括版本发布后在该分支的合入。 + ``` + repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony-4.0-Beta2 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- 从版本发布Tag节点获取源码。可获取与版本发布时完全一致的源码。 + ``` + repo init -u https://gitee.com/openharmony/manifest -b refs/tags/OpenHarmony-v4.0-Beta2 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + + +### 从镜像站点获取 + + **表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | **软件包容量** | +| --------------------------------------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -------- | +| 全量代码(标准、轻量和小型系统) | 4.0 Beta2 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/code-v4.0-Beta2.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/code-v4.0-Beta2.tar.gz.sha256) | 27.7 GB | +| Hi3861解决方案(二进制) | 4.0 Beta2 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/hispark_pegasus.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/hispark_pegasus.tar.gz.sha256) | 27.5 MB | +| Hi3516解决方案-LiteOS(二进制) | 4.0 Beta2 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/hispark_taurus_LiteOS.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/hispark_taurus_LiteOS.tar.gz.sha256) | 300.9 MB | +| Hi3516解决方案-Linux(二进制) | 4.0 Beta2 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/hispark_taurus_Linux.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/hispark_taurus_Linux.tar.gz.sha256) | 192.4 MB | +| RK3568标准系统解决方案(二进制) | 4.0 Beta2 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/dayu200_standard_arm32.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/dayu200_standard_arm32.tar.gz.sha256) | 5.2 GB | +| 标准系统Public SDK包(Mac) | 4.0.9.6 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/ohos-sdk-mac-public.tar.gz.sha256) | 832.3 MB | +| 标准系统Public SDK包(Mac-M1) | 4.0.9.6 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/L2-SDK-MAC-M1-PUBLIC.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/L2-SDK-MAC-M1-PUBLIC.tar.gz.sha256) | 788.4 MB | +| 标准系统Public SDK包(Windows/Linux) | 4.0.9.6 | [站点](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/ohos-sdk-windows_linux-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/4.0-Beta2/ohos-sdk-windows_linux-public.tar.gz.sha256) | 2.0 GB | + + +## 更新说明 + +本版本在OpenHarmony 4.0 Beta1的基础上有如下变更: + +### API + +OpenHarmony 4.0 Beta2的API范围相比4.0 Beta1,API变更的清单请参见“[API差异报告](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/zh-cn/release-notes/api-diff/v4.0-beta2/Readme-CN.md)”。极少量接口的变更可能影响到已开发的应用(使用API 9或更早版本API开发的应用),变更影响的说明和接口的适配指导请参见“[changelogs](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/zh-cn/release-notes/changelogs/v4.0-beta2/Readme-CN.md)”。 + + +### 特性变更 + +详见[版本概述](#版本概述)。 + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 + + +### Samples + +**表3** 新增Samples + +| 子系统 | 名称 | 简介 | 开发语言 | +| -------- | -------- | -------- | -------- | +| 网络与连接 | [上传和下载](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/BasicFeature/Connectivity/UploadAndDownLoad) | 本示例使用\@ohos.request接口创建上传和下载任务,实现上传、下载功能,hfs作为服务器,实现了文件的上传和下载和任务的查询功能。 | ArkTS | +| 文件管理 | [应用接入数据备份恢复](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/BasicFeature/FileManagement/FileBackupExtension)
(Full SDK) | 应用接入数据备份恢复需要通过配置BackupExtensionAbility实现。
BackupExtensionAbility,是Stage模型中扩展组件ExtensionAbility的派生类。开发者可以通过修改配置文件定制备份恢复框架的行为,包括是否允许备份恢复,备份哪些文件等。
本sample主要给备份流程提供应用,用于生成数据和显示数据。 | ArkTS | +| 事件通知 | [自定义通知角标](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/BasicFeature/Notification/CustomNotificationBadge) | 本示例主要展示了设定应用的桌面图标角标的功能,使用\@ohos.notificationManager 接口,进行桌面角标的设置,通知的发送,获取等。 | ArkTS | +| 事件通知 | [自定义通知推送](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/BasicFeature/Notification/CustomNotificationPush)
(Full SDK) | 本示例主要展示了通知过滤回调管理的功能,使用\@ohos.notificationManager 接口,进行通知监听回调,决定应用通知是否发送。 | ArkTS | +| NDK | [Native Xcomponent](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Native/NdkXComponent)
(Native SDK) | 本示例中主要介绍开发者如何使用Native XComponent接口来获取NativeWindow实例、获取布局/事件信息、注册事件回调并通过OpenGL/EGL实现在页面上绘制形状。功能主要包括点击按钮绘制一个五角星,并可以通过点击XComponent区域改变五角星的颜色。 | Native C++ | +| 应用模型 | [数据代理卡片-数据库刷新](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SystemFeature/ApplicationModels/PersistentProxyForm)
(Full SDK) | 本示例主要展示了数据代理卡片的功能,使用\@ohos.application.DataShareExtensionAbility、\@ohos.data.dataShare、\@ohos.data.dataSharePredicates等接口,实现了修改卡片订阅信息后,当rdb数据库中的数据发生变化时,卡片中对应信息也发生相应变化的功能。 | ArkTS | +| 应用模型 | [数据代理卡片-仿push应用刷新](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SystemFeature/ApplicationModels/ProcessProxyForm)
(Full SDK) | 本示例主要展示了使用push应用形式的数据代理卡片功能,使用\@ohos.data.dataShare等接口,实现了数据代理卡片的修改订阅条件功能及卡片的发布数据功能。 | ArkTS | +| 应用模型 | [编辑应用](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SystemFeature/ApplicationModels/Receiver) | 本示例主要实现了基于UIExtension实现简单的分享功能。支持取消分享,点击“返回Share”按钮,返回调用方应用;支持完成分享,点击“留在编辑应用”按钮,留在当前接收分享结果应用。 | ArkTS | +| 应用模型 | [发起分享应用](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SystemFeature/ApplicationModels/Share)
(Full SDK) | 本示例主要实现了点击“分享”按钮发起分享,显示出分享文本应用图标和分享编辑应用图标,点击相对应应用图标可以发起分享并跳转到其对应应用显示。 | ArkTS | +| 应用模型 | [文本应用](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Beta2/code/SystemFeature/ApplicationModels/Template)
(Full SDK) | 本示例主要实现了基于UIExtension实现简单的分享功能。支持取消分享,点击“返回Share”按钮,返回调用方应用;支持完成分享,点击“留在文本应用”按钮,留在当前文本应用。 | ArkTS | + +请访问[Samples](https://gitee.com/openharmony/applications_app_samples)仓了解更多信息。 + + +## 修复缺陷列表 + +**表4** 修复缺陷ISSUE列表 + +| ISSUE单 | 问题描述 | +| -------- | -------- | +| I6U4ZT | 拍照后立刻断电源,图库的第一张图片点击打不开。 | +| I79752 | 中概率由进程com.ohos.smartperf下的.ohos.smartperf线程导致libark_jsruntime.so出现cppcrash。 | +| I79P3K | 低概率由进程com.ohos.callui导致jscrash,栈名:onDestroy。 | +| I79TCB | 低概率由进程com.ohos.note下的VizCompositorTh线程导致libweb_engine.soTh出现cppcrash。 | +| I78CBC | 反复进入某相册的图片宫格浏览界面,导致libace.z.so出现内存泄露。 | +| I78CH7 | 反复在dock栏添加/移除应用,导致libace.z.so出现内存泄露。 | + + +## 遗留缺陷列表 + +**表5** 遗留缺陷列表 + +| ISSUE | 问题描述 | 影响 | 计划解决日期 | +| -------- | -------- | -------- | -------- | +| I78C9W | 反复进入大图浏览界面后返回,导致libace.z.so出现内存泄露。 | 非常用场景,应用重启后泄露问题消失,影响可控。 | 2023年8月30日 | +| I7BF3M | 长时间运行测试,launcher进程概率性出现appfreeze,原因是STRINGID:APPLICATION_BLOCK_INPUT卡在libeventhandler.z.so。 | 该问题不会引起系统重启,整体影响可控。 | 2023年8月30日 | +| I7M51R | 低概率出现进程com.ohos.systemui下的线程render_service出现cppcrash。 | 低概率问题,且render_service进程出现cppcrash后,系统会自动重新启动render_service进程,对业务影响可控。 | 2023年8月30日 | +| I7NWF3 | 因兼容性问题,使用3.2.x版本的设备和4.0.x版本的设备通过Wi-Fi引导P2P连接时开启会话失败。 | 在使用4.0.x版本的设备间此问题不存在,影响可控。 | 2023年8月30日 | +| I7BOAO | 三方仓GLES3多个测试用例执行失败。 | 三方仓问题,厂商正在适配修改。 | 2023年8月30日 | \ No newline at end of file diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/Readme-CN.md b/zh-cn/release-notes/api-diff/v4.0-beta2/Readme-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..0615e586b47d2deeb3332ac50259e31a9709adcc --- /dev/null +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/Readme-CN.md @@ -0,0 +1,34 @@ +# Readme + +- [元能力](js-apidiff-ability.md) +- [帐号](js-apidiff-account.md) +- [AI](js-apidiff-ai.md) +- [应用](js-apidiff-application.md) +- [ArkUI](js-apidiff-arkui.md) +- [电源管理](js-apidiff-battery.md) +- [包管理](js-apidiff-bundle.md) +- [网络与通信](js-apidiff-communication.md) +- [语言编译器运行时](js-apidiff-compiler-and-runtime.md) +- [定制](js-apidiff-customization.md) +- [DFX](js-apidiff-dfx.md) +- [分布式数据管理](js-apidiff-distributed-data.md) +- [分布式硬件](js-apidiff-distributed-hardware.md) +- [上传下载](js-apidiff-download-upload.md) +- [驱动](js-apidiff-driver.md) +- [文件管理](js-apidiff-file-management.md) +- [位置服务](js-apidiff-geolocation.md) +- [全球化](js-apidiff-global.md) +- [Misc软件](js-apidiff-misc.md) +- [MSDP](js-apidiff-msdp.md) +- [多模输入](js-apidiff-multi-modal-input.md) +- [媒体](js-apidiff-multimedia.md) +- [事件通知](js-apidiff-notification.md) +- [资源调度](js-apidiff-resource-scheduler.md) +- [安全](js-apidiff-security.md) +- [泛Sensor](js-apidiff-sensor.md) +- [启动](js-apidiff-start-up.md) +- [电话服务](js-apidiff-telephony.md) +- [测试框架](js-apidiff-unitest.md) +- [USB](js-apidiff-usb.md) +- [Web](js-apidiff-web.md) +- [窗口](js-apidiff-window.md) diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-ability.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-ability.md index b09793d8a9a29aa8f0bba48e307bf3008888f30f..9c30bf21e5cd172e7190072c7dd8d4063b80b40a 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-ability.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-ability.md @@ -744,69 +744,3 @@ |type有变化|类名:WantAgentInfo;
方法or属性:requestCode: number;
旧版本信息:|类名:WantAgentInfo;
方法or属性:requestCode: number;
新版本信息:number|wantAgentInfo.d.ts| |type有变化|类名:WantAgentInfo;
方法or属性:wantAgentFlags?: Array\;
旧版本信息:|类名:WantAgentInfo;
方法or属性:wantAgentFlags?: Array\;
新版本信息:?Array\|wantAgentInfo.d.ts| |type有变化|类名:WantAgentInfo;
方法or属性:extraInfo?: { [key: string]: any };
旧版本信息:|类名:WantAgentInfo;
方法or属性:extraInfo?: { [key: string]: any };
新版本信息:?object|wantAgentInfo.d.ts| -|跨平台能力有变化|类名:abilityDelegatorRegistry;
方法or属性:declare abilityDelegatorRegistry
旧版本信息:|类名:abilityDelegatorRegistry;
方法or属性:declare abilityDelegatorRegistry
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:abilityDelegatorRegistry;
方法or属性:function getAbilityDelegator(): AbilityDelegator;
旧版本信息:|类名:abilityDelegatorRegistry;
方法or属性:function getAbilityDelegator(): AbilityDelegator;
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:abilityDelegatorRegistry;
方法or属性:function getArguments(): AbilityDelegatorArgs;
旧版本信息:|类名:abilityDelegatorRegistry;
方法or属性:function getArguments(): AbilityDelegatorArgs;
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:abilityDelegatorRegistry;
方法or属性:export type AbilityDelegator = _AbilityDelegator;
旧版本信息:|类名:abilityDelegatorRegistry;
方法or属性:export type AbilityDelegator = _AbilityDelegator;
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:abilityDelegatorRegistry;
方法or属性:export type AbilityDelegatorArgs = _AbilityDelegatorArgs;
旧版本信息:|类名:abilityDelegatorRegistry;
方法or属性:export type AbilityDelegatorArgs = _AbilityDelegatorArgs;
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:abilityDelegatorRegistry;
方法or属性:export type AbilityMonitor = _AbilityMonitor;
旧版本信息:|类名:abilityDelegatorRegistry;
方法or属性:export type AbilityMonitor = _AbilityMonitor;
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:AbilityLifecycleState;
方法or属性:export enum AbilityLifecycleState
旧版本信息:|类名:AbilityLifecycleState;
方法or属性:export enum AbilityLifecycleState
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:AbilityLifecycleState;
方法or属性:UNINITIALIZED
旧版本信息:|类名:AbilityLifecycleState;
方法or属性:UNINITIALIZED
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:AbilityLifecycleState;
方法or属性:CREATE
旧版本信息:|类名:AbilityLifecycleState;
方法or属性:CREATE
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:AbilityLifecycleState;
方法or属性:FOREGROUND
旧版本信息:|类名:AbilityLifecycleState;
方法or属性:FOREGROUND
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:AbilityLifecycleState;
方法or属性:BACKGROUND
旧版本信息:|类名:AbilityLifecycleState;
方法or属性:BACKGROUND
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:AbilityLifecycleState;
方法or属性:DESTROY
旧版本信息:|类名:AbilityLifecycleState;
方法or属性:DESTROY
新版本信息:crossplatform|@ohos.app.ability.abilityDelegatorRegistry.d.ts| -|跨平台能力有变化|类名:ColorMode;
方法or属性:COLOR_MODE_NOT_SET = -1
旧版本信息:|类名:ColorMode;
方法or属性:COLOR_MODE_NOT_SET = -1
新版本信息:crossplatform|@ohos.app.ability.ConfigurationConstant.d.ts| -|跨平台能力有变化|类名:ColorMode;
方法or属性:COLOR_MODE_DARK = 0
旧版本信息:|类名:ColorMode;
方法or属性:COLOR_MODE_DARK = 0
新版本信息:crossplatform|@ohos.app.ability.ConfigurationConstant.d.ts| -|跨平台能力有变化|类名:ColorMode;
方法or属性:COLOR_MODE_LIGHT = 1
旧版本信息:|类名:ColorMode;
方法or属性:COLOR_MODE_LIGHT = 1
新版本信息:crossplatform|@ohos.app.ability.ConfigurationConstant.d.ts| -|跨平台能力有变化|类名:Direction;
方法or属性:DIRECTION_NOT_SET = -1
旧版本信息:|类名:Direction;
方法or属性:DIRECTION_NOT_SET = -1
新版本信息:crossplatform|@ohos.app.ability.ConfigurationConstant.d.ts| -|跨平台能力有变化|类名:Direction;
方法or属性:DIRECTION_VERTICAL = 0
旧版本信息:|类名:Direction;
方法or属性:DIRECTION_VERTICAL = 0
新版本信息:crossplatform|@ohos.app.ability.ConfigurationConstant.d.ts| -|跨平台能力有变化|类名:Direction;
方法or属性:DIRECTION_HORIZONTAL = 1
旧版本信息:|类名:Direction;
方法or属性:DIRECTION_HORIZONTAL = 1
新版本信息:crossplatform|@ohos.app.ability.ConfigurationConstant.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:export interface AbilityDelegator
旧版本信息:|类名:AbilityDelegator;
方法or属性:export interface AbilityDelegator
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:addAbilityMonitor(monitor: AbilityMonitor): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:addAbilityMonitor(monitor: AbilityMonitor): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:removeAbilityMonitor(monitor: AbilityMonitor): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:removeAbilityMonitor(monitor: AbilityMonitor): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:getAppContext(): Context;
旧版本信息:|类名:AbilityDelegator;
方法or属性:getAppContext(): Context;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:getAbilityState(ability: UIAbility): number;
旧版本信息:|类名:AbilityDelegator;
方法or属性:getAbilityState(ability: UIAbility): number;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:getCurrentTopAbility(callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:getCurrentTopAbility(callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:getCurrentTopAbility(): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:getCurrentTopAbility(): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:startAbility(want: Want, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:startAbility(want: Want, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:startAbility(want: Want): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:startAbility(want: Want): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:doAbilityForeground(ability: UIAbility): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:doAbilityForeground(ability: UIAbility): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:doAbilityBackground(ability: UIAbility): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:doAbilityBackground(ability: UIAbility): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:print(msg: string, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:print(msg: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:print(msg: string): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:print(msg: string): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:printSync(msg: string): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:printSync(msg: string): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:finishTest(msg: string, code: number, callback: AsyncCallback\): void;
旧版本信息:|类名:AbilityDelegator;
方法or属性:finishTest(msg: string, code: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegator;
方法or属性:finishTest(msg: string, code: number): Promise\;
旧版本信息:|类名:AbilityDelegator;
方法or属性:finishTest(msg: string, code: number): Promise\;
新版本信息:crossplatform|AbilityDelegator.d.ts| -|跨平台能力有变化|类名:AbilityDelegatorArgs;
方法or属性:export interface AbilityDelegatorArgs
旧版本信息:|类名:AbilityDelegatorArgs;
方法or属性:export interface AbilityDelegatorArgs
新版本信息:crossplatform|abilityDelegatorArgs.d.ts| -|跨平台能力有变化|类名:AbilityDelegatorArgs;
方法or属性:bundleName: string;
旧版本信息:|类名:AbilityDelegatorArgs;
方法or属性:bundleName: string;
新版本信息:crossplatform|abilityDelegatorArgs.d.ts| -|跨平台能力有变化|类名:AbilityDelegatorArgs;
方法or属性:parameters: { [key: string]: string };
旧版本信息:|类名:AbilityDelegatorArgs;
方法or属性:parameters: { [key: string]: string };
新版本信息:crossplatform|abilityDelegatorArgs.d.ts| -|跨平台能力有变化|类名:AbilityDelegatorArgs;
方法or属性:testCaseNames: string;
旧版本信息:|类名:AbilityDelegatorArgs;
方法or属性:testCaseNames: string;
新版本信息:crossplatform|abilityDelegatorArgs.d.ts| -|跨平台能力有变化|类名:AbilityDelegatorArgs;
方法or属性:testRunnerClassName: string;
旧版本信息:|类名:AbilityDelegatorArgs;
方法or属性:testRunnerClassName: string;
新版本信息:crossplatform|abilityDelegatorArgs.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:export interface AbilityMonitor
旧版本信息:|类名:AbilityMonitor;
方法or属性:export interface AbilityMonitor
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:abilityName: string;
旧版本信息:|类名:AbilityMonitor;
方法or属性:abilityName: string;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:moduleName?: string;
旧版本信息:|类名:AbilityMonitor;
方法or属性:moduleName?: string;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:onAbilityCreate?: (ability: UIAbility) => void;
旧版本信息:|类名:AbilityMonitor;
方法or属性:onAbilityCreate?: (ability: UIAbility) => void;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:onAbilityForeground?: (ability: UIAbility) => void;
旧版本信息:|类名:AbilityMonitor;
方法or属性:onAbilityForeground?: (ability: UIAbility) => void;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:onAbilityBackground?: (ability: UIAbility) => void;
旧版本信息:|类名:AbilityMonitor;
方法or属性:onAbilityBackground?: (ability: UIAbility) => void;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:onAbilityDestroy?: (ability: UIAbility) => void;
旧版本信息:|类名:AbilityMonitor;
方法or属性:onAbilityDestroy?: (ability: UIAbility) => void;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:onWindowStageCreate?: (ability: UIAbility) => void;
旧版本信息:|类名:AbilityMonitor;
方法or属性:onWindowStageCreate?: (ability: UIAbility) => void;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityMonitor;
方法or属性:onWindowStageDestroy?: (ability: UIAbility) => void;
旧版本信息:|类名:AbilityMonitor;
方法or属性:onWindowStageDestroy?: (ability: UIAbility) => void;
新版本信息:crossplatform|AbilityMonitor.d.ts| -|跨平台能力有变化|类名:AbilityStageMonitor;
方法or属性:export interface AbilityStageMonitor
旧版本信息:|类名:AbilityStageMonitor;
方法or属性:export interface AbilityStageMonitor
新版本信息:crossplatform|AbilityStageMonitor.d.ts| -|跨平台能力有变化|类名:AbilityStageMonitor;
方法or属性:moduleName: string;
旧版本信息:|类名:AbilityStageMonitor;
方法or属性:moduleName: string;
新版本信息:crossplatform|AbilityStageMonitor.d.ts| -|跨平台能力有变化|类名:AbilityStageMonitor;
方法or属性:srcEntrance: string;
旧版本信息:|类名:AbilityStageMonitor;
方法or属性:srcEntrance: string;
新版本信息:crossplatform|AbilityStageMonitor.d.ts| -|跨平台能力有变化|类名:UIAbilityContext;
方法or属性:config: Configuration;
旧版本信息:|类名:UIAbilityContext;
方法or属性:config: Configuration;
新版本信息:crossplatform|UIAbilityContext.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-arkui.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-arkui.md index 8f3a23c3e1e35d05332ae00ba4a90899490dc4a4..ef29755ca928791e091909e0034b02c4592a28ab 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-arkui.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-arkui.md @@ -831,51 +831,3 @@ |卡片应用支持性有变化|类名:ClickEvent;
方法or属性:screenX: number;
旧版本信息:form|类名:ClickEvent;
方法or属性:screenX: number;
新版本信息:|common.d.ts| |卡片应用支持性有变化|类名:ClickEvent;
方法or属性:screenY: number;
旧版本信息:form|类名:ClickEvent;
方法or属性:screenY: number;
新版本信息:|common.d.ts| |卡片应用支持性有变化|类名:TextAttribute;
方法or属性:textShadow(value: ShadowOptions): TextAttribute;
旧版本信息:|类名:TextAttribute;
方法or属性:textShadow(value: ShadowOptions): TextAttribute;
新版本信息:form|text.d.ts| -|跨平台能力有变化|类名:componentSnapshot;
方法or属性:declare componentSnapshot
旧版本信息:|类名:componentSnapshot;
方法or属性:declare componentSnapshot
新版本信息:crossplatform|@ohos.arkui.componentSnapshot.d.ts| -|跨平台能力有变化|类名:componentSnapshot;
方法or属性:function get(id: string, callback: AsyncCallback\): void;
旧版本信息:|类名:componentSnapshot;
方法or属性:function get(id: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.arkui.componentSnapshot.d.ts| -|跨平台能力有变化|类名:componentSnapshot;
方法or属性:function get(id: string): Promise\;
旧版本信息:|类名:componentSnapshot;
方法or属性:function get(id: string): Promise\;
新版本信息:crossplatform|@ohos.arkui.componentSnapshot.d.ts| -|跨平台能力有变化|类名:componentSnapshot;
方法or属性:function createFromBuilder(builder: CustomBuilder, callback: AsyncCallback\): void;
旧版本信息:|类名:componentSnapshot;
方法or属性:function createFromBuilder(builder: CustomBuilder, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.arkui.componentSnapshot.d.ts| -|跨平台能力有变化|类名:componentSnapshot;
方法or属性:function createFromBuilder(builder: CustomBuilder): Promise\;
旧版本信息:|类名:componentSnapshot;
方法or属性:function createFromBuilder(builder: CustomBuilder): Promise\;
新版本信息:crossplatform|@ohos.arkui.componentSnapshot.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function copy(): Matrix4Transit;
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function copy(): Matrix4Transit;
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function invert(): Matrix4Transit;
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function invert(): Matrix4Transit;
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function combine(options: Matrix4Transit): Matrix4Transit;
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function combine(options: Matrix4Transit): Matrix4Transit;
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function translate(options: TranslateOption): Matrix4Transit;
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function translate(options: TranslateOption): Matrix4Transit;
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function scale(options: ScaleOption): Matrix4Transit;
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function scale(options: ScaleOption): Matrix4Transit;
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function rotate(options: RotateOption): Matrix4Transit;
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function rotate(options: RotateOption): Matrix4Transit;
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:matrix4;
方法or属性:function transformPoint(options: [number, number]): [number, number];
旧版本信息:crossplatform|类名:matrix4;
方法or属性:function transformPoint(options: [number, number]): [number, number];
新版本信息:|@ohos.matrix4.d.ts| -|跨平台能力有变化|类名:CanvasRenderer;
方法or属性:getTransform(): Matrix2D;
旧版本信息:|类名:CanvasRenderer;
方法or属性:getTransform(): Matrix2D;
新版本信息:crossplatform|canvas.d.ts| -|跨平台能力有变化|类名:CanvasRenderer;
方法or属性:setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
旧版本信息:|类名:CanvasRenderer;
方法or属性:setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
新版本信息:crossplatform|canvas.d.ts| -|跨平台能力有变化|类名:CanvasRenderer;
方法or属性:setTransform(transform?: Matrix2D): void;
旧版本信息:|类名:CanvasRenderer;
方法or属性:setTransform(transform?: Matrix2D): void;
新版本信息:crossplatform|canvas.d.ts| -|跨平台能力有变化|类名:AlignRuleOption;
方法or属性:bottom?: { anchor: string, align: VerticalAlign };
旧版本信息:crossplatform|类名:AlignRuleOption;
方法or属性:bottom?: { anchor: string, align: VerticalAlign };
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:ClickEvent;
方法or属性:screenX: number;
旧版本信息:crossplatform|类名:ClickEvent;
方法or属性:screenX: number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:MouseEvent;
方法or属性:screenX: number;
旧版本信息:crossplatform|类名:MouseEvent;
方法or属性:screenX: number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:TouchObject;
方法or属性:screenX: number;
旧版本信息:crossplatform|类名:TouchObject;
方法or属性:screenX: number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:ClickEvent;
方法or属性:screenY: number;
旧版本信息:crossplatform|类名:ClickEvent;
方法or属性:screenY: number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:MouseEvent;
方法or属性:screenY: number;
旧版本信息:crossplatform|类名:MouseEvent;
方法or属性:screenY: number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:TouchObject;
方法or属性:screenY: number;
旧版本信息:crossplatform|类名:TouchObject;
方法or属性:screenY: number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:DragEvent;
方法or属性:getX(): number;
旧版本信息:crossplatform|类名:DragEvent;
方法or属性:getX(): number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:DragEvent;
方法or属性:getY(): number;
旧版本信息:crossplatform|类名:DragEvent;
方法or属性:getY(): number;
新版本信息:|common.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Link(propName: string): any;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Link(propName: string): any;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static SetAndLink\(propName: string, defaultValue: T): SubscribedAbstractProperty\;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static SetAndLink\(propName: string, defaultValue: T): SubscribedAbstractProperty\;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Prop(propName: string): any;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Prop(propName: string): any;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static SetAndProp\(propName: string, defaultValue: S): SubscribedAbstractProperty\;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static SetAndProp\(propName: string, defaultValue: S): SubscribedAbstractProperty\;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Has(propName: string): boolean;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Has(propName: string): boolean;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Get\(propName: string): T \| undefined;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Get\(propName: string): T \| undefined;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Set\(propName: string, newValue: T): boolean;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Set\(propName: string, newValue: T): boolean;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static SetOrCreate\(propName: string, newValue: T): void;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static SetOrCreate\(propName: string, newValue: T): void;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Delete(propName: string): boolean;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Delete(propName: string): boolean;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Keys(): IterableIterator\;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Keys(): IterableIterator\;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Clear(): boolean;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Clear(): boolean;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static IsMutable(propName: string): boolean;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static IsMutable(propName: string): boolean;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:AppStorage;
方法or属性:static Size(): number;
旧版本信息:crossplatform|类名:AppStorage;
方法or属性:static Size(): number;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:Environment;
方法or属性:static EnvProp\(key: string, value: S): boolean;
旧版本信息:crossplatform|类名:Environment;
方法or属性:static EnvProp\(key: string, value: S): boolean;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:Environment;
方法or属性:static EnvProps(
props: {
key: string;
defaultValue: any;
}[],
): void;
旧版本信息:crossplatform|类名:Environment;
方法or属性:static EnvProps(
props: {
key: string;
defaultValue: any;
}[],
): void;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:Environment;
方法or属性:static Keys(): Array\;
旧版本信息:crossplatform|类名:Environment;
方法or属性:static Keys(): Array\;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:PersistentStorage;
方法or属性:static Keys(): Array\;
旧版本信息:crossplatform|类名:PersistentStorage;
方法or属性:static Keys(): Array\;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:PersistentStorage;
方法or属性:static PersistProp\(key: string, defaultValue: T): void;
旧版本信息:crossplatform|类名:PersistentStorage;
方法or属性:static PersistProp\(key: string, defaultValue: T): void;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:PersistentStorage;
方法or属性:static DeleteProp(key: string): void;
旧版本信息:crossplatform|类名:PersistentStorage;
方法or属性:static DeleteProp(key: string): void;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:PersistentStorage;
方法or属性:static PersistProps(
properties: {
key: string;
defaultValue: any;
}[],
): void;
旧版本信息:crossplatform|类名:PersistentStorage;
方法or属性:static PersistProps(
properties: {
key: string;
defaultValue: any;
}[],
): void;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:LocalStorage;
方法or属性:static GetShared(): LocalStorage;
旧版本信息:crossplatform|类名:LocalStorage;
方法or属性:static GetShared(): LocalStorage;
新版本信息:|common_ts_ets_api.d.ts| -|跨平台能力有变化|类名:ListItemInterface;
方法or属性:(value?: string): ListItemAttribute;
旧版本信息:crossplatform|类名:ListItemInterface;
方法or属性:(value?: string): ListItemAttribute;
新版本信息:|list_item.d.ts| -|跨平台能力有变化|类名:NavigationAttribute;
方法or属性:toolBar(value: object \| CustomBuilder): NavigationAttribute;
旧版本信息:crossplatform|类名:NavigationAttribute;
方法or属性:toolBar(value: object \| CustomBuilder): NavigationAttribute;
新版本信息:|navigation.d.ts| -|跨平台能力有变化|类名:Scroller;
方法or属性:scrollToIndex(value: number, smooth?:boolean, align?: ScrollAlign);
旧版本信息:|类名:Scroller;
方法or属性:scrollToIndex(value: number, smooth?:boolean, align?: ScrollAlign);
新版本信息:crossplatform|scroll.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-bundle.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-bundle.md index d2adc46d1d07299c107deadd2a90b14e7b9ba67c..5cd82fa61b1a6f5e68bb5ab2d8498e3b184a924a 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-bundle.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-bundle.md @@ -36,7 +36,3 @@ |model有变化|类名:AbilityType;
方法or属性:PAGE = 1
旧版本信息:|类名:AbilityType;
方法or属性:PAGE = 1
新版本信息:FAModelOnly|@ohos.bundle.bundleManager.d.ts| |model有变化|类名:AbilityType;
方法or属性:SERVICE = 2
旧版本信息:|类名:AbilityType;
方法or属性:SERVICE = 2
新版本信息:FAModelOnly|@ohos.bundle.bundleManager.d.ts| |model有变化|类名:AbilityType;
方法or属性:DATA = 3
旧版本信息:|类名:AbilityType;
方法or属性:DATA = 3
新版本信息:FAModelOnly|@ohos.bundle.bundleManager.d.ts| -|跨平台能力有变化|类名:Metadata;
方法or属性:export interface Metadata
旧版本信息:|类名:Metadata;
方法or属性:export interface Metadata
新版本信息:crossplatform|Metadata.d.ts| -|跨平台能力有变化|类名:Metadata;
方法or属性:name: string;
旧版本信息:|类名:Metadata;
方法or属性:name: string;
新版本信息:crossplatform|Metadata.d.ts| -|跨平台能力有变化|类名:Metadata;
方法or属性:value: string;
旧版本信息:|类名:Metadata;
方法or属性:value: string;
新版本信息:crossplatform|Metadata.d.ts| -|跨平台能力有变化|类名:Metadata;
方法or属性:resource: string;
旧版本信息:|类名:Metadata;
方法or属性:resource: string;
新版本信息:crossplatform|Metadata.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-communication.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-communication.md index 3b0abda9841d860becc92f28794115130d553d79..fb0d1874ffba73fc92357da2d4a8032c61c47146 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-communication.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-communication.md @@ -603,106 +603,3 @@ |type有变化|类名:NetworkResponse;
方法or属性:type: string;
旧版本信息:|类名:NetworkResponse;
方法or属性:type: string;
新版本信息:string|@system.network.d.ts| |type有变化|类名:NetworkResponse;
方法or属性:metered: boolean;
旧版本信息:|类名:NetworkResponse;
方法or属性:metered: boolean;
新版本信息:boolean|@system.network.d.ts| |函数有变化|类名:HotspotConfig;
方法or属性:channel: number;|类名:HotspotConfig;
方法or属性:channel?: number;|@ohos.wifiManager.d.ts| -|跨平台能力有变化|类名:connection;
方法or属性:function hasDefaultNet(): Promise\;
旧版本信息:|类名:connection;
方法or属性:function hasDefaultNet(): Promise\;
新版本信息:crossplatform|@ohos.net.connection.d.ts| -|跨平台能力有变化|类名:NetConnection;
方法or属性:export interface NetConnection
旧版本信息:|类名:NetConnection;
方法or属性:export interface NetConnection
新版本信息:crossplatform|@ohos.net.connection.d.ts| -|跨平台能力有变化|类名:http;
方法or属性:declare http
旧版本信息:|类名:http;
方法or属性:declare http
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpRequestOptions;
方法or属性:export interface HttpRequestOptions
旧版本信息:|类名:HttpRequestOptions;
方法or属性:export interface HttpRequestOptions
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpRequest;
方法or属性:export interface HttpRequest
旧版本信息:|类名:HttpRequest;
方法or属性:export interface HttpRequest
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpRequest;
方法or属性:request(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void;
旧版本信息:|类名:HttpRequest;
方法or属性:request(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpRequest;
方法or属性:request(url: string, options?: HttpRequestOptions): Promise\;
旧版本信息:|类名:HttpRequest;
方法or属性:request(url: string, options?: HttpRequestOptions): Promise\;
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:OPTIONS = "OPTIONS"
旧版本信息:|类名:RequestMethod;
方法or属性:OPTIONS = "OPTIONS"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:GET = "GET"
旧版本信息:|类名:RequestMethod;
方法or属性:GET = "GET"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:HEAD = "HEAD"
旧版本信息:|类名:RequestMethod;
方法or属性:HEAD = "HEAD"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:POST = "POST"
旧版本信息:|类名:RequestMethod;
方法or属性:POST = "POST"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:PUT = "PUT"
旧版本信息:|类名:RequestMethod;
方法or属性:PUT = "PUT"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:DELETE = "DELETE"
旧版本信息:|类名:RequestMethod;
方法or属性:DELETE = "DELETE"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:TRACE = "TRACE"
旧版本信息:|类名:RequestMethod;
方法or属性:TRACE = "TRACE"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:RequestMethod;
方法or属性:CONNECT = "CONNECT"
旧版本信息:|类名:RequestMethod;
方法or属性:CONNECT = "CONNECT"
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:OK = 200
旧版本信息:|类名:ResponseCode;
方法or属性:OK = 200
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:CREATED
旧版本信息:|类名:ResponseCode;
方法or属性:CREATED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:ACCEPTED
旧版本信息:|类名:ResponseCode;
方法or属性:ACCEPTED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:NOT_AUTHORITATIVE
旧版本信息:|类名:ResponseCode;
方法or属性:NOT_AUTHORITATIVE
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:NO_CONTENT
旧版本信息:|类名:ResponseCode;
方法or属性:NO_CONTENT
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:RESET
旧版本信息:|类名:ResponseCode;
方法or属性:RESET
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:PARTIAL
旧版本信息:|类名:ResponseCode;
方法or属性:PARTIAL
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:MULT_CHOICE = 300
旧版本信息:|类名:ResponseCode;
方法or属性:MULT_CHOICE = 300
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:MOVED_PERM
旧版本信息:|类名:ResponseCode;
方法or属性:MOVED_PERM
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:MOVED_TEMP
旧版本信息:|类名:ResponseCode;
方法or属性:MOVED_TEMP
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:SEE_OTHER
旧版本信息:|类名:ResponseCode;
方法or属性:SEE_OTHER
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:NOT_MODIFIED
旧版本信息:|类名:ResponseCode;
方法or属性:NOT_MODIFIED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:USE_PROXY
旧版本信息:|类名:ResponseCode;
方法or属性:USE_PROXY
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:BAD_REQUEST = 400
旧版本信息:|类名:ResponseCode;
方法or属性:BAD_REQUEST = 400
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:UNAUTHORIZED
旧版本信息:|类名:ResponseCode;
方法or属性:UNAUTHORIZED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:PAYMENT_REQUIRED
旧版本信息:|类名:ResponseCode;
方法or属性:PAYMENT_REQUIRED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:FORBIDDEN
旧版本信息:|类名:ResponseCode;
方法or属性:FORBIDDEN
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:NOT_FOUND
旧版本信息:|类名:ResponseCode;
方法or属性:NOT_FOUND
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:BAD_METHOD
旧版本信息:|类名:ResponseCode;
方法or属性:BAD_METHOD
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:NOT_ACCEPTABLE
旧版本信息:|类名:ResponseCode;
方法or属性:NOT_ACCEPTABLE
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:PROXY_AUTH
旧版本信息:|类名:ResponseCode;
方法or属性:PROXY_AUTH
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:CLIENT_TIMEOUT
旧版本信息:|类名:ResponseCode;
方法or属性:CLIENT_TIMEOUT
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:CONFLICT
旧版本信息:|类名:ResponseCode;
方法or属性:CONFLICT
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:GONE
旧版本信息:|类名:ResponseCode;
方法or属性:GONE
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:LENGTH_REQUIRED
旧版本信息:|类名:ResponseCode;
方法or属性:LENGTH_REQUIRED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:PRECON_FAILED
旧版本信息:|类名:ResponseCode;
方法or属性:PRECON_FAILED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:ENTITY_TOO_LARGE
旧版本信息:|类名:ResponseCode;
方法or属性:ENTITY_TOO_LARGE
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:REQ_TOO_LONG
旧版本信息:|类名:ResponseCode;
方法or属性:REQ_TOO_LONG
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:UNSUPPORTED_TYPE
旧版本信息:|类名:ResponseCode;
方法or属性:UNSUPPORTED_TYPE
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:INTERNAL_ERROR = 500
旧版本信息:|类名:ResponseCode;
方法or属性:INTERNAL_ERROR = 500
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:NOT_IMPLEMENTED
旧版本信息:|类名:ResponseCode;
方法or属性:NOT_IMPLEMENTED
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:BAD_GATEWAY
旧版本信息:|类名:ResponseCode;
方法or属性:BAD_GATEWAY
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:UNAVAILABLE
旧版本信息:|类名:ResponseCode;
方法or属性:UNAVAILABLE
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:GATEWAY_TIMEOUT
旧版本信息:|类名:ResponseCode;
方法or属性:GATEWAY_TIMEOUT
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:ResponseCode;
方法or属性:VERSION
旧版本信息:|类名:ResponseCode;
方法or属性:VERSION
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpProtocol;
方法or属性:HTTP1_1
旧版本信息:|类名:HttpProtocol;
方法or属性:HTTP1_1
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpProtocol;
方法or属性:HTTP2
旧版本信息:|类名:HttpProtocol;
方法or属性:HTTP2
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpResponse;
方法or属性:export interface HttpResponse
旧版本信息:|类名:HttpResponse;
方法or属性:export interface HttpResponse
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpResponseCache;
方法or属性:flush(): Promise\;
旧版本信息:|类名:HttpResponseCache;
方法or属性:flush(): Promise\;
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:HttpResponseCache;
方法or属性:delete(): Promise\;
旧版本信息:|类名:HttpResponseCache;
方法or属性:delete(): Promise\;
新版本信息:crossplatform|@ohos.net.http.d.ts| -|跨平台能力有变化|类名:socket;
方法or属性:declare socket
旧版本信息:|类名:socket;
方法or属性:declare socket
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSendOptions;
方法or属性:export interface UDPSendOptions
旧版本信息:|类名:UDPSendOptions;
方法or属性:export interface UDPSendOptions
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSConnectOptions;
方法or属性:address: NetAddress;
旧版本信息:|类名:TLSConnectOptions;
方法or属性:address: NetAddress;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:ExtraOptionsBase;
方法or属性:export interface ExtraOptionsBase
旧版本信息:|类名:ExtraOptionsBase;
方法or属性:export interface ExtraOptionsBase
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPExtraOptions;
方法or属性:export interface UDPExtraOptions
旧版本信息:|类名:UDPExtraOptions;
方法or属性:export interface UDPExtraOptions
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:SocketStateBase;
方法or属性:export interface SocketStateBase
旧版本信息:|类名:SocketStateBase;
方法or属性:export interface SocketStateBase
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:SocketRemoteInfo;
方法or属性:export interface SocketRemoteInfo
旧版本信息:|类名:SocketRemoteInfo;
方法or属性:export interface SocketRemoteInfo
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSocket;
方法or属性:export interface UDPSocket
旧版本信息:|类名:UDPSocket;
方法or属性:export interface UDPSocket
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSocket;
方法or属性:bind(address: NetAddress): Promise\;
旧版本信息:|类名:UDPSocket;
方法or属性:bind(address: NetAddress): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:bind(address: NetAddress): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:bind(address: NetAddress): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:bind(address: NetAddress): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:bind(address: NetAddress): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSocket;
方法or属性:send(options: UDPSendOptions): Promise\;
旧版本信息:|类名:UDPSocket;
方法or属性:send(options: UDPSendOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSocket;
方法or属性:close(): Promise\;
旧版本信息:|类名:UDPSocket;
方法or属性:close(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:close(): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:close(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:close(): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:close(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSocket;
方法or属性:getState(): Promise\;
旧版本信息:|类名:UDPSocket;
方法or属性:getState(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:getState(): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:getState(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getState(): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:getState(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:UDPSocket;
方法or属性:setExtraOptions(options: UDPExtraOptions): Promise\;
旧版本信息:|类名:UDPSocket;
方法or属性:setExtraOptions(options: UDPExtraOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPConnectOptions;
方法or属性:export interface TCPConnectOptions
旧版本信息:|类名:TCPConnectOptions;
方法or属性:export interface TCPConnectOptions
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSendOptions;
方法or属性:export interface TCPSendOptions
旧版本信息:|类名:TCPSendOptions;
方法or属性:export interface TCPSendOptions
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPExtraOptions;
方法or属性:export interface TCPExtraOptions
旧版本信息:|类名:TCPExtraOptions;
方法or属性:export interface TCPExtraOptions
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:export interface TCPSocket
旧版本信息:|类名:TCPSocket;
方法or属性:export interface TCPSocket
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:connect(options: TCPConnectOptions): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:connect(options: TCPConnectOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:send(options: TCPSendOptions): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:send(options: TCPSendOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:getRemoteAddress(): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:getRemoteAddress(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getRemoteAddress(): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:getRemoteAddress(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TCPSocket;
方法or属性:setExtraOptions(options: TCPExtraOptions): Promise\;
旧版本信息:|类名:TCPSocket;
方法or属性:setExtraOptions(options: TCPExtraOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:setExtraOptions(options: TCPExtraOptions): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:setExtraOptions(options: TCPExtraOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getCertificate(): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:getCertificate(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getRemoteCertificate(): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:getRemoteCertificate(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getProtocol(): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:getProtocol(): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getCipherSuite(): Promise\>;
旧版本信息:|类名:TLSSocket;
方法or属性:getCipherSuite(): Promise\>;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:getSignatureAlgorithms(): Promise\>;
旧版本信息:|类名:TLSSocket;
方法or属性:getSignatureAlgorithms(): Promise\>;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:connect(options: TLSConnectOptions): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:connect(options: TLSConnectOptions): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSSocket;
方法or属性:send(data: string): Promise\;
旧版本信息:|类名:TLSSocket;
方法or属性:send(data: string): Promise\;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:TLSConnectOptions;
方法or属性:secureOptions: TLSSecureOptions;
旧版本信息:|类名:TLSConnectOptions;
方法or属性:secureOptions: TLSSecureOptions;
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:Protocol;
方法or属性:TLSv12 = "TLSv1.2"
旧版本信息:|类名:Protocol;
方法or属性:TLSv12 = "TLSv1.2"
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:Protocol;
方法or属性:TLSv13 = "TLSv1.3"
旧版本信息:|类名:Protocol;
方法or属性:TLSv13 = "TLSv1.3"
新版本信息:crossplatform|@ohos.net.socket.d.ts| -|跨平台能力有变化|类名:webSocket;
方法or属性:declare webSocket
旧版本信息:|类名:webSocket;
方法or属性:declare webSocket
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocketRequestOptions;
方法or属性:export interface WebSocketRequestOptions
旧版本信息:|类名:WebSocketRequestOptions;
方法or属性:export interface WebSocketRequestOptions
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocketCloseOptions;
方法or属性:export interface WebSocketCloseOptions
旧版本信息:|类名:WebSocketCloseOptions;
方法or属性:export interface WebSocketCloseOptions
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocket;
方法or属性:export interface WebSocket
旧版本信息:|类名:WebSocket;
方法or属性:export interface WebSocket
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocket;
方法or属性:connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void;
旧版本信息:|类名:WebSocket;
方法or属性:connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocket;
方法or属性:connect(url: string, options?: WebSocketRequestOptions): Promise\;
旧版本信息:|类名:WebSocket;
方法or属性:connect(url: string, options?: WebSocketRequestOptions): Promise\;
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocket;
方法or属性:send(data: string \| ArrayBuffer): Promise\;
旧版本信息:|类名:WebSocket;
方法or属性:send(data: string \| ArrayBuffer): Promise\;
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocket;
方法or属性:close(options: WebSocketCloseOptions, callback: AsyncCallback\): void;
旧版本信息:|类名:WebSocket;
方法or属性:close(options: WebSocketCloseOptions, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| -|跨平台能力有变化|类名:WebSocket;
方法or属性:close(options?: WebSocketCloseOptions): Promise\;
旧版本信息:|类名:WebSocket;
方法or属性:close(options?: WebSocketCloseOptions): Promise\;
新版本信息:crossplatform|@ohos.net.webSocket.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-compiler-and-runtime.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-compiler-and-runtime.md index cc76efa8087990b94123d6f77b44e6e36df100ff..8c05191e4e22ecbeb75b700dc6445074a618dc90 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-compiler-and-runtime.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-compiler-and-runtime.md @@ -49,57 +49,3 @@ |函数有变化|类名:Base64Helper;
方法or属性:decodeSync(src: Uint8Array \| string): Uint8Array;|类名:Base64Helper;
方法or属性:decodeSync(src: Uint8Array \| string, options?: Type): Uint8Array;|@ohos.util.d.ts| |函数有变化|类名:Base64Helper;
方法or属性:encodeToString(src: Uint8Array): Promise\;|类名:Base64Helper;
方法or属性:encodeToString(src: Uint8Array, options?: Type): Promise\;|@ohos.util.d.ts| |函数有变化|类名:Base64Helper;
方法or属性:decode(src: Uint8Array \| string): Promise\;|类名:Base64Helper;
方法or属性:decode(src: Uint8Array \| string, options?: Type): Promise\;|@ohos.util.d.ts| -|跨平台能力有变化|类名:buffer;
方法or属性:type BufferEncoding =
\| 'ascii'
\| 'utf8'
\| 'utf-8'
\| 'utf16le'
\| 'ucs2'
\| 'ucs-2'
\| 'base64'
\| 'base64url'
\| 'latin1'
\| 'binary'
\| 'hex';
旧版本信息:|类名:buffer;
方法or属性:type BufferEncoding =
\| 'ascii'
\| 'utf8'
\| 'utf-8'
\| 'utf16le'
\| 'ucs2'
\| 'ucs-2'
\| 'base64'
\| 'base64url'
\| 'latin1'
\| 'binary'
\| 'hex';
新版本信息:crossplatform|@ohos.buffer.d.ts| -|跨平台能力有变化|类名:TypedArray;
方法or属性:interface TypedArray
旧版本信息:|类名:TypedArray;
方法or属性:interface TypedArray
新版本信息:crossplatform|@ohos.buffer.d.ts| -|跨平台能力有变化|类名:Buffer;
方法or属性:class Buffer
旧版本信息:|类名:Buffer;
方法or属性:class Buffer
新版本信息:crossplatform|@ohos.buffer.d.ts| -|跨平台能力有变化|类名:Blob;
方法or属性:class Blob
旧版本信息:|类名:Blob;
方法or属性:class Blob
新版本信息:crossplatform|@ohos.buffer.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:type EventListener = (evt: Object) => void;
旧版本信息:|类名:process;
方法or属性:type EventListener = (evt: Object) => void;
新版本信息:crossplatform|@ohos.process.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:function runCmd(

command: string,

options?: ConditionType

): ChildProcess;
旧版本信息:crossplatform|类名:process;
方法or属性:function runCmd(

command: string,

options?: ConditionType

): ChildProcess;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:function on(type: string, listener: EventListener): void;
旧版本信息:crossplatform|类名:process;
方法or属性:function on(type: string, listener: EventListener): void;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:function off(type: string): boolean;
旧版本信息:crossplatform|类名:process;
方法or属性:function off(type: string): boolean;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:function exit(code: number): void;
旧版本信息:crossplatform|类名:process;
方法or属性:function exit(code: number): void;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:function cwd(): string;
旧版本信息:crossplatform|类名:process;
方法or属性:function cwd(): string;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:process;
方法or属性:function chdir(dir: string): void;
旧版本信息:crossplatform|类名:process;
方法or属性:function chdir(dir: string): void;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:export interface ChildProcess
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:export interface ChildProcess
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:readonly pid: number;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:readonly pid: number;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:readonly ppid: number;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:readonly ppid: number;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:readonly exitCode: number;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:readonly exitCode: number;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:readonly killed: boolean;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:readonly killed: boolean;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:wait(): Promise\;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:wait(): Promise\;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:getOutput(): Promise\;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:getOutput(): Promise\;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:getErrorOutput(): Promise\;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:getErrorOutput(): Promise\;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:close(): void;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:close(): void;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:ChildProcess;
方法or属性:kill(signal: number \| string): void;
旧版本信息:crossplatform|类名:ChildProcess;
方法or属性:kill(signal: number \| string): void;
新版本信息:|@ohos.process.d.ts| -|跨平台能力有变化|类名:taskpool;
方法or属性:declare taskpool
旧版本信息:|类名:taskpool;
方法or属性:declare taskpool
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:taskpool;
方法or属性:function execute(func: Function, ...args: unknown[]): Promise\;
旧版本信息:|类名:taskpool;
方法or属性:function execute(func: Function, ...args: unknown[]): Promise\;
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:taskpool;
方法or属性:function execute(task: Task, priority?: Priority): Promise\;
旧版本信息:|类名:taskpool;
方法or属性:function execute(task: Task, priority?: Priority): Promise\;
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:taskpool;
方法or属性:function cancel(task: Task): void;
旧版本信息:|类名:taskpool;
方法or属性:function cancel(task: Task): void;
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Priority;
方法or属性:enum Priority
旧版本信息:|类名:Priority;
方法or属性:enum Priority
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Priority;
方法or属性:HIGH = 0
旧版本信息:|类名:Priority;
方法or属性:HIGH = 0
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Priority;
方法or属性:MEDIUM = 1
旧版本信息:|类名:Priority;
方法or属性:MEDIUM = 1
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Priority;
方法or属性:LOW = 2
旧版本信息:|类名:Priority;
方法or属性:LOW = 2
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Task;
方法or属性:class Task
旧版本信息:|类名:Task;
方法or属性:class Task
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Task;
方法or属性:constructor(func: Function, ...args: unknown[]);
旧版本信息:|类名:Task;
方法or属性:constructor(func: Function, ...args: unknown[]);
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Task;
方法or属性:function: Function;
旧版本信息:|类名:Task;
方法or属性:function: Function;
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:Task;
方法or属性:arguments?: unknown[];
旧版本信息:|类名:Task;
方法or属性:arguments?: unknown[];
新版本信息:crossplatform|@ohos.taskpool.d.ts| -|跨平台能力有变化|类名:ArrayList;
方法or属性:declare class ArrayList
旧版本信息:|类名:ArrayList;
方法or属性:declare class ArrayList
新版本信息:crossplatform|@ohos.util.ArrayList.d.ts| -|跨平台能力有变化|类名:Scope;
方法or属性:class Scope
旧版本信息:crossplatform|类名:Scope;
方法or属性:class Scope
新版本信息:|@ohos.util.d.ts| -|跨平台能力有变化|类名:ScopeHelper;
方法or属性:getLower(): ScopeType;
旧版本信息:|类名:ScopeHelper;
方法or属性:getLower(): ScopeType;
新版本信息:crossplatform|@ohos.util.d.ts| -|跨平台能力有变化|类名:Deque;
方法or属性:declare class Deque
旧版本信息:|类名:Deque;
方法or属性:declare class Deque
新版本信息:crossplatform|@ohos.util.Deque.d.ts| -|跨平台能力有变化|类名:HashMap;
方法or属性:declare class HashMap
旧版本信息:|类名:HashMap;
方法or属性:declare class HashMap
新版本信息:crossplatform|@ohos.util.HashMap.d.ts| -|跨平台能力有变化|类名:HashSet;
方法or属性:declare class HashSet
旧版本信息:|类名:HashSet;
方法or属性:declare class HashSet
新版本信息:crossplatform|@ohos.util.HashSet.d.ts| -|跨平台能力有变化|类名:LightWeightMap;
方法or属性:declare class LightWeightMap
旧版本信息:|类名:LightWeightMap;
方法or属性:declare class LightWeightMap
新版本信息:crossplatform|@ohos.util.LightWeightMap.d.ts| -|跨平台能力有变化|类名:LightWeightSet;
方法or属性:declare class LightWeightSet
旧版本信息:|类名:LightWeightSet;
方法or属性:declare class LightWeightSet
新版本信息:crossplatform|@ohos.util.LightWeightSet.d.ts| -|跨平台能力有变化|类名:LinkedList;
方法or属性:declare class LinkedList
旧版本信息:|类名:LinkedList;
方法or属性:declare class LinkedList
新版本信息:crossplatform|@ohos.util.LinkedList.d.ts| -|跨平台能力有变化|类名:List;
方法or属性:declare class List
旧版本信息:|类名:List;
方法or属性:declare class List
新版本信息:crossplatform|@ohos.util.List.d.ts| -|跨平台能力有变化|类名:PlainArray;
方法or属性:declare class PlainArray
旧版本信息:|类名:PlainArray;
方法or属性:declare class PlainArray
新版本信息:crossplatform|@ohos.util.PlainArray.d.ts| -|跨平台能力有变化|类名:Queue;
方法or属性:declare class Queue
旧版本信息:|类名:Queue;
方法or属性:declare class Queue
新版本信息:crossplatform|@ohos.util.Queue.d.ts| -|跨平台能力有变化|类名:Stack;
方法or属性:declare class Stack
旧版本信息:|类名:Stack;
方法or属性:declare class Stack
新版本信息:crossplatform|@ohos.util.Stack.d.ts| -|跨平台能力有变化|类名:TreeMap;
方法or属性:declare class TreeMap
旧版本信息:|类名:TreeMap;
方法or属性:declare class TreeMap
新版本信息:crossplatform|@ohos.util.TreeMap.d.ts| -|跨平台能力有变化|类名:TreeSet;
方法or属性:declare class TreeSet
旧版本信息:|类名:TreeSet;
方法or属性:declare class TreeSet
新版本信息:crossplatform|@ohos.util.TreeSet.d.ts| -|跨平台能力有变化|类名:WorkerEventTarget;
方法or属性:addEventListener(type: string, listener: WorkerEventListener): void;
旧版本信息:crossplatform|类名:WorkerEventTarget;
方法or属性:addEventListener(type: string, listener: WorkerEventListener): void;
新版本信息:|@ohos.worker.d.ts| -|跨平台能力有变化|类名:XmlSerializer;
方法or属性:constructor(buffer: ArrayBuffer \| DataView, encoding?: string);
旧版本信息:|类名:XmlSerializer;
方法or属性:constructor(buffer: ArrayBuffer \| DataView, encoding?: string);
新版本信息:crossplatform|@ohos.xml.d.ts| -|跨平台能力有变化|类名:XmlPullParser;
方法or属性:constructor(buffer: ArrayBuffer \| DataView, encoding?: string);
旧版本信息:|类名:XmlPullParser;
方法or属性:constructor(buffer: ArrayBuffer \| DataView, encoding?: string);
新版本信息:crossplatform|@ohos.xml.d.ts| -|跨平台能力有变化|类名:EventType;
方法or属性:enum EventType
旧版本信息:|类名:EventType;
方法or属性:enum EventType
新版本信息:crossplatform|@ohos.xml.d.ts| -|跨平台能力有变化|类名:ParseInfo;
方法or属性:interface ParseInfo
旧版本信息:|类名:ParseInfo;
方法or属性:interface ParseInfo
新版本信息:crossplatform|@ohos.xml.d.ts| -|跨平台能力有变化|类名:ParseOptions;
方法or属性:interface ParseOptions
旧版本信息:|类名:ParseOptions;
方法or属性:interface ParseOptions
新版本信息:crossplatform|@ohos.xml.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-dfx.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-dfx.md index 653d7c0d95e04a37def923515ba36c44ae0bed3d..f65a4e78a52a3d7ec0a1a4f14d29c37761b8225f 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-dfx.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-dfx.md @@ -52,7 +52,3 @@ |type有变化|类名:HiTraceId;
方法or属性:spanId?: number;
旧版本信息:|类名:HiTraceId;
方法or属性:spanId?: number;
新版本信息:?number|@ohos.hiTraceChain.d.ts| |type有变化|类名:HiTraceId;
方法or属性:parentSpanId?: number;
旧版本信息:|类名:HiTraceId;
方法or属性:parentSpanId?: number;
新版本信息:?number|@ohos.hiTraceChain.d.ts| |type有变化|类名:HiTraceId;
方法or属性:flags?: number;
旧版本信息:|类名:HiTraceId;
方法or属性:flags?: number;
新版本信息:?number|@ohos.hiTraceChain.d.ts| -|跨平台能力有变化|类名:hilog;
方法or属性:declare hilog
旧版本信息:|类名:hilog;
方法or属性:declare hilog
新版本信息:crossplatform|@ohos.hilog.d.ts| -|跨平台能力有变化|类名:hiTraceMeter;
方法or属性:declare hiTraceMeter
旧版本信息:|类名:hiTraceMeter;
方法or属性:declare hiTraceMeter
新版本信息:crossplatform|@ohos.hiTraceMeter.d.ts| -|跨平台能力有变化|类名:hiTraceMeter;
方法or属性:function startTrace(name: string, taskId: number): void;
旧版本信息:|类名:hiTraceMeter;
方法or属性:function startTrace(name: string, taskId: number): void;
新版本信息:crossplatform|@ohos.hiTraceMeter.d.ts| -|跨平台能力有变化|类名:hiTraceMeter;
方法or属性:function finishTrace(name: string, taskId: number): void;
旧版本信息:|类名:hiTraceMeter;
方法or属性:function finishTrace(name: string, taskId: number): void;
新版本信息:crossplatform|@ohos.hiTraceMeter.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-distributed-data.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-distributed-data.md index 06629d571b9fc7560df3cb4cc3cf0a30ba3e4d9f..e0eaf15590bf2eefcc62479450abfc9c9115fe52 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-distributed-data.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-distributed-data.md @@ -121,9 +121,3 @@ |函数有变化|类名:DataShareExtensionAbility;
方法or属性:context?: ExtensionContext;|类名:DataShareExtensionAbility;
方法or属性:context: ExtensionContext;|@ohos.application.DataShareExtensionAbility.d.ts| |函数有变化|类名:PublishedItem;
方法or属性:data: string \| Ashmem;|类名:PublishedItem;
方法or属性:data: string \| ArrayBuffer;|@ohos.data.dataShare.d.ts| |函数有变化|类名:relationalStore;
方法or属性:type ValueType = null \| number \| string \| boolean \| Uint8Array;|类名:relationalStore;
方法or属性:type ValueType = null \| number \| string \| boolean \| Uint8Array \| Asset \| Assets;|@ohos.data.relationalStore.d.ts| -|跨平台能力有变化|类名:StoreConfig;
方法or属性:securityLevel: SecurityLevel;
旧版本信息:|类名:StoreConfig;
方法or属性:securityLevel: SecurityLevel;
新版本信息:crossplatform|@ohos.data.relationalStore.d.ts| -|跨平台能力有变化|类名:SecurityLevel;
方法or属性:enum SecurityLevel
旧版本信息:|类名:SecurityLevel;
方法or属性:enum SecurityLevel
新版本信息:crossplatform|@ohos.data.relationalStore.d.ts| -|跨平台能力有变化|类名:SecurityLevel;
方法or属性:S1 = 1
旧版本信息:|类名:SecurityLevel;
方法or属性:S1 = 1
新版本信息:crossplatform|@ohos.data.relationalStore.d.ts| -|跨平台能力有变化|类名:SecurityLevel;
方法or属性:S2 = 2
旧版本信息:|类名:SecurityLevel;
方法or属性:S2 = 2
新版本信息:crossplatform|@ohos.data.relationalStore.d.ts| -|跨平台能力有变化|类名:SecurityLevel;
方法or属性:S3 = 3
旧版本信息:|类名:SecurityLevel;
方法or属性:S3 = 3
新版本信息:crossplatform|@ohos.data.relationalStore.d.ts| -|跨平台能力有变化|类名:SecurityLevel;
方法or属性:S4 = 4
旧版本信息:|类名:SecurityLevel;
方法or属性:S4 = 4
新版本信息:crossplatform|@ohos.data.relationalStore.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-file-management.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-file-management.md index edfe18a1ac06bd590ad71475dc0eb349a3727596..6f3ccd09592716948f2204d50908d95304b18b1a 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-file-management.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-file-management.md @@ -446,24 +446,3 @@ |type有变化|类名:PhotoSaveOptions;
方法or属性:newFileNames?: Array\;
旧版本信息:Array\|类名:PhotoSaveOptions;
方法or属性:newFileNames?: Array\;
新版本信息:?Array\|@ohos.file.picker.d.ts| |type有变化|类名:DocumentSaveOptions;
方法or属性:newFileNames?: Array\;
旧版本信息:Array\|类名:DocumentSaveOptions;
方法or属性:newFileNames?: Array\;
新版本信息:?Array\|@ohos.file.picker.d.ts| |type有变化|类名:AudioSaveOptions;
方法or属性:newFileNames?: Array\;
旧版本信息:Array\|类名:AudioSaveOptions;
方法or属性:newFileNames?: Array\;
新版本信息:?Array\|@ohos.file.picker.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function access(path: string): Promise\;
旧版本信息:|类名:sourcefile;
方法or属性:declare function access(path: string): Promise\;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function access(path: string, callback: AsyncCallback\): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function access(path: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function accessSync(path: string): boolean;
旧版本信息:|类名:sourcefile;
方法or属性:declare function accessSync(path: string): boolean;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function copyFile(src: string \| number, dest: string \| number, mode?: number): Promise\;
旧版本信息:|类名:sourcefile;
方法or属性:declare function copyFile(src: string \| number, dest: string \| number, mode?: number): Promise\;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function copyFile(src: string \| number, dest: string \| number, callback: AsyncCallback\): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function copyFile(src: string \| number, dest: string \| number, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function copyFile(
src: string \| number,
dest: string \| number,
mode: number,
callback: AsyncCallback\
): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function copyFile(
src: string \| number,
dest: string \| number,
mode: number,
callback: AsyncCallback\
): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function copyFileSync(src: string \| number, dest: string \| number, mode?: number): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function copyFileSync(src: string \| number, dest: string \| number, mode?: number): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function listFile(
path: string,
options?: {
recursion?: boolean;
listNum?: number;
filter?: Filter;
}
): Promise\;
旧版本信息:|类名:sourcefile;
方法or属性:declare function listFile(
path: string,
options?: {
recursion?: boolean;
listNum?: number;
filter?: Filter;
}
): Promise\;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function listFile(path: string, callback: AsyncCallback\): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function listFile(path: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function listFile(
path: string,
options: {
recursion?: boolean;
listNum?: number;
filter?: Filter;
},
callback: AsyncCallback\
): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function listFile(
path: string,
options: {
recursion?: boolean;
listNum?: number;
filter?: Filter;
},
callback: AsyncCallback\
): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function listFileSync(
path: string,
options?: {
recursion?: boolean;
listNum?: number;
filter?: Filter;
}
): string[];
旧版本信息:|类名:sourcefile;
方法or属性:declare function listFileSync(
path: string,
options?: {
recursion?: boolean;
listNum?: number;
filter?: Filter;
}
): string[];
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function moveFile(src: string, dest: string, mode?: number): Promise\;
旧版本信息:|类名:sourcefile;
方法or属性:declare function moveFile(src: string, dest: string, mode?: number): Promise\;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function moveFile(src: string, dest: string, callback: AsyncCallback\): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function moveFile(src: string, dest: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function moveFile(src: string, dest: string, mode: number, callback: AsyncCallback\): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function moveFile(src: string, dest: string, mode: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function moveFileSync(src: string, dest: string, mode?: number): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function moveFileSync(src: string, dest: string, mode?: number): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function readText(
filePath: string,
options?: {
offset?: number;
length?: number;
encoding?: string;
}
): Promise\;
旧版本信息:|类名:sourcefile;
方法or属性:declare function readText(
filePath: string,
options?: {
offset?: number;
length?: number;
encoding?: string;
}
): Promise\;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function readText(filePath: string, callback: AsyncCallback\): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function readText(filePath: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function readText(
filePath: string,
options: {
offset?: number;
length?: number;
encoding?: string;
},
callback: AsyncCallback\
): void;
旧版本信息:|类名:sourcefile;
方法or属性:declare function readText(
filePath: string,
options: {
offset?: number;
length?: number;
encoding?: string;
},
callback: AsyncCallback\
): void;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:declare function readTextSync(
filePath: string,
options?: {
offset?: number;
length?: number;
encoding?: string;
}
): string;
旧版本信息:|类名:sourcefile;
方法or属性:declare function readTextSync(
filePath: string,
options?: {
offset?: number;
length?: number;
encoding?: string;
}
): string;
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:sourcefile;
方法or属性:export type Filter = {
/**
* @type { ?Array\ }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
suffix?: Array\;
/**
* @type { ?Array\ }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
displayName?: Array\;
/**
* @type { ?Array\ }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
mimeType?: Array\;
/**
* @type { ?number }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
fileSizeOver?: number;
/**
* @type { ?number }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
lastModifiedAfter?: number;
/**
* @type { ?boolean }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
excludeMedia?: boolean;
};
旧版本信息:|类名:sourcefile;
方法or属性:export type Filter = {
/**
* @type { ?Array\ }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
suffix?: Array\;
/**
* @type { ?Array\ }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
displayName?: Array\;
/**
* @type { ?Array\ }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
mimeType?: Array\;
/**
* @type { ?number }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
fileSizeOver?: number;
/**
* @type { ?number }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
lastModifiedAfter?: number;
/**
* @type { ?boolean }
* @syscap SystemCapability.FileManagement.File.FileIO
* @since 10
*/
excludeMedia?: boolean;
};
新版本信息:crossplatform|@ohos.file.fs.d.ts| -|跨平台能力有变化|类名:fileIo;
方法or属性:declare fileIo
旧版本信息:|类名:fileIo;
方法or属性:declare fileIo
新版本信息:crossplatform|@ohos.file.fs.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-global.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-global.md index f3aafc0e06d2b51bf49118e27e6c9755f53dc7a9..5f6592c6e4422dc18a6982501ecd9d45487a2b28 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-global.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-global.md @@ -32,9 +32,3 @@ |新增|NA|类名:ResourceManager;
方法or属性:getColorByNameSync(resName: string) : number;|@ohos.resourceManager.d.ts| |新增|NA|类名:ResourceManager;
方法or属性:addResource(path: string) : void;|@ohos.resourceManager.d.ts| |新增|NA|类名:ResourceManager;
方法or属性:removeResource(path: string) : void;|@ohos.resourceManager.d.ts| -|跨平台能力有变化|类名:DateTimeOptions;
方法or属性:year?: string;
旧版本信息:|类名:DateTimeOptions;
方法or属性:year?: string;
新版本信息:crossplatform|@ohos.intl.d.ts| -|跨平台能力有变化|类名:DeviceType;
方法or属性:DEVICE_TYPE_TABLET = 0x01
旧版本信息:crossplatform|类名:DeviceType;
方法or属性:DEVICE_TYPE_TABLET = 0x01
新版本信息:|@ohos.resourceManager.d.ts| -|跨平台能力有变化|类名:DeviceType;
方法or属性:DEVICE_TYPE_CAR = 0x02
旧版本信息:crossplatform|类名:DeviceType;
方法or属性:DEVICE_TYPE_CAR = 0x02
新版本信息:|@ohos.resourceManager.d.ts| -|跨平台能力有变化|类名:DeviceType;
方法or属性:DEVICE_TYPE_PC = 0x03
旧版本信息:crossplatform|类名:DeviceType;
方法or属性:DEVICE_TYPE_PC = 0x03
新版本信息:|@ohos.resourceManager.d.ts| -|跨平台能力有变化|类名:DeviceType;
方法or属性:DEVICE_TYPE_TV = 0x04
旧版本信息:crossplatform|类名:DeviceType;
方法or属性:DEVICE_TYPE_TV = 0x04
新版本信息:|@ohos.resourceManager.d.ts| -|跨平台能力有变化|类名:DeviceType;
方法or属性:DEVICE_TYPE_WEARABLE = 0x06
旧版本信息:crossplatform|类名:DeviceType;
方法or属性:DEVICE_TYPE_WEARABLE = 0x06
新版本信息:|@ohos.resourceManager.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-multimedia.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-multimedia.md index 13ddc5fbda1afe0e3ccfcc1edbcc5b3df6d0dfee..105069268e5e07e3e7e0c6579791e4cc13fcb972 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-multimedia.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-multimedia.md @@ -13,6 +13,8 @@ |删除|类名:OutputDeviceInfo;
方法or属性:deviceName: Array\;|NA|@ohos.multimedia.avsession.d.ts| |删除|类名:ImageSource;
方法or属性:getDelayTime(): Promise\>;|NA|@ohos.multimedia.image.d.ts| |删除|类名:ImageSource;
方法or属性:getDelayTime(callback: AsyncCallback\>): void;|NA|@ohos.multimedia.image.d.ts| +|新增|NA|类名:effectKit;
方法or属性:function createColorPicker(source:image.PixelMap,region:Array\):Promise\;|@ohos.effectKit.d.ts| +|新增|NA|类名:effectKit;
方法or属性:function createColorPicker(source:image.PixelMap,region:Array\,callback:AsyncCallback\):void;|@ohos.effectKit.d.ts| |新增|NA|类名:AVMediaDescription;
方法or属性:artist?: string;|@ohos.multimedia.avsession.d.ts| |新增|NA|类名:AVMediaDescription;
方法or属性:duration?: number;|@ohos.multimedia.avsession.d.ts| |新增|NA|类名:AVCastController;
方法or属性:getAVPlaybackState(callback: AsyncCallback\): void;|@ohos.multimedia.avsession.d.ts| @@ -210,6 +212,8 @@ |新增|NA|类名:ImageSource;
方法or属性:getDelayTimeList(): Promise\>;|@ohos.multimedia.image.d.ts| |新增|NA|类名:ImageSource;
方法or属性:getDelayTimeList(callback: AsyncCallback\>): void;|@ohos.multimedia.image.d.ts| |新增|NA|类名:AVPlayer;
方法or属性:audioEffectMode ?: audio.AudioEffectMode;|@ohos.multimedia.media.d.ts| +|新增(错误码)|类名:effectKit;
方法or属性:function createColorPicker(source:image.PixelMap): Promise\;
旧版本信息:|类名:effectKit;
方法or属性:function createColorPicker(source:image.PixelMap): Promise\;
新版本信息:401|@ohos.effectKit.d.ts| +|新增(错误码)|类名:effectKit;
方法or属性:function createColorPicker(source:image.PixelMap,callback:AsyncCallback\):void;
旧版本信息:|类名:effectKit;
方法or属性:function createColorPicker(source:image.PixelMap,callback:AsyncCallback\):void;
新版本信息:401|@ohos.effectKit.d.ts| |新增(错误码)|类名:avSession;
方法or属性:function createAVSession(context: Context, tag: string, type: AVSessionType): Promise\;
旧版本信息:|类名:avSession;
方法or属性:function createAVSession(context: Context, tag: string, type: AVSessionType): Promise\;
新版本信息:401,6600101|@ohos.multimedia.avsession.d.ts| |新增(错误码)|类名:avSession;
方法or属性:function getAllSessionDescriptors(): Promise\>>;
旧版本信息:|类名:avSession;
方法or属性:function getAllSessionDescriptors(): Promise\>>;
新版本信息:201,6600101|@ohos.multimedia.avsession.d.ts| |新增(错误码)|类名:avSession;
方法or属性:function createController(sessionId: string): Promise\;
旧版本信息:|类名:avSession;
方法or属性:function createController(sessionId: string): Promise\;
新版本信息:201,401,6600101,6600102|@ohos.multimedia.avsession.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-sdk.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-sdk.md deleted file mode 100644 index b5192aa02c0cfc35d7b81cef0b5925d722575c7d..0000000000000000000000000000000000000000 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-sdk.md +++ /dev/null @@ -1,11 +0,0 @@ -| 操作 | 旧版本 | 新版本 | d.ts文件 | -| ---- | ------ | ------ | -------- | -|跨平台能力有变化|类名:Callback;
方法or属性:export interface Callback
旧版本信息:|类名:Callback;
方法or属性:export interface Callback
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:Callback;
方法or属性:(data: T): void;
旧版本信息:|类名:Callback;
方法or属性:(data: T): void;
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:ErrorCallback;
方法or属性:export interface ErrorCallback
旧版本信息:|类名:ErrorCallback;
方法or属性:export interface ErrorCallback
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:ErrorCallback;
方法or属性:(err: T): void;
旧版本信息:|类名:ErrorCallback;
方法or属性:(err: T): void;
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:AsyncCallback;
方法or属性:export interface AsyncCallback
旧版本信息:|类名:AsyncCallback;
方法or属性:export interface AsyncCallback
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:AsyncCallback;
方法or属性:(err: BusinessError\, data: T): void;
旧版本信息:|类名:AsyncCallback;
方法or属性:(err: BusinessError\, data: T): void;
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:BusinessError;
方法or属性:export interface BusinessError
旧版本信息:|类名:BusinessError;
方法or属性:export interface BusinessError
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:BusinessError;
方法or属性:code: number;
旧版本信息:|类名:BusinessError;
方法or属性:code: number;
新版本信息:crossplatform|@ohos.base.d.ts| -|跨平台能力有变化|类名:BusinessError;
方法or属性:data?: T;
旧版本信息:|类名:BusinessError;
方法or属性:data?: T;
新版本信息:crossplatform|@ohos.base.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-unitest.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-unitest.md index 544feba6613f75fc91685419cf8e7911d01ec1cf..9e57ea9c3a47c60b16815bbcad4dee9d78584ef1 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-unitest.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-unitest.md @@ -10,53 +10,3 @@ |type有变化|类名:WindowFilter;
方法or属性:title?: string;
旧版本信息:string?|类名:WindowFilter;
方法or属性:title?: string;
新版本信息:?string|@ohos.UiTest.d.ts| |type有变化|类名:WindowFilter;
方法or属性:focused?: boolean;
旧版本信息:boolean?|类名:WindowFilter;
方法or属性:focused?: boolean;
新版本信息:?boolean|@ohos.UiTest.d.ts| |type有变化|类名:WindowFilter;
方法or属性:actived?: boolean;
旧版本信息:boolean?|类名:WindowFilter;
方法or属性:actived?: boolean;
新版本信息:?boolean|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:MatchPattern;
方法or属性:declare enum MatchPattern
旧版本信息:|类名:MatchPattern;
方法or属性:declare enum MatchPattern
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:MatchPattern;
方法or属性:EQUALS = 0
旧版本信息:|类名:MatchPattern;
方法or属性:EQUALS = 0
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:MatchPattern;
方法or属性:CONTAINS = 1
旧版本信息:|类名:MatchPattern;
方法or属性:CONTAINS = 1
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:MatchPattern;
方法or属性:STARTS_WITH = 2
旧版本信息:|类名:MatchPattern;
方法or属性:STARTS_WITH = 2
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:MatchPattern;
方法or属性:ENDS_WITH = 3
旧版本信息:|类名:MatchPattern;
方法or属性:ENDS_WITH = 3
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Point;
方法or属性:declare interface Point
旧版本信息:|类名:Point;
方法or属性:declare interface Point
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Point;
方法or属性:readonly x: number;
旧版本信息:|类名:Point;
方法or属性:readonly x: number;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Point;
方法or属性:readonly y: number;
旧版本信息:|类名:Point;
方法or属性:readonly y: number;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:text(txt: string, pattern?: MatchPattern): On;
旧版本信息:|类名:On;
方法or属性:text(txt: string, pattern?: MatchPattern): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:id(id: string): On;
旧版本信息:|类名:On;
方法or属性:id(id: string): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:type(tp: string): On;
旧版本信息:|类名:On;
方法or属性:type(tp: string): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:clickable(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:clickable(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:longClickable(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:longClickable(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:scrollable(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:scrollable(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:enabled(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:enabled(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:focused(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:focused(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:selected(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:selected(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:checked(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:checked(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:On;
方法or属性:checkable(b?: boolean): On;
旧版本信息:|类名:On;
方法or属性:checkable(b?: boolean): On;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:click(): Promise\;
旧版本信息:|类名:Component;
方法or属性:click(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:doubleClick(): Promise\;
旧版本信息:|类名:Component;
方法or属性:doubleClick(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:longClick(): Promise\;
旧版本信息:|类名:Component;
方法or属性:longClick(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:getId(): Promise\;
旧版本信息:|类名:Component;
方法or属性:getId(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:getText(): Promise\;
旧版本信息:|类名:Component;
方法or属性:getText(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:getType(): Promise\;
旧版本信息:|类名:Component;
方法or属性:getType(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isClickable(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isClickable(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isLongClickable(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isLongClickable(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isScrollable(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isScrollable(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isEnabled(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isEnabled(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isFocused(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isFocused(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isSelected(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isSelected(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isChecked(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isChecked(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:isCheckable(): Promise\;
旧版本信息:|类名:Component;
方法or属性:isCheckable(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:inputText(text: string): Promise\;
旧版本信息:|类名:Component;
方法or属性:inputText(text: string): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:clearText(): Promise\;
旧版本信息:|类名:Component;
方法or属性:clearText(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:scrollToTop(speed?: number): Promise\;
旧版本信息:|类名:Component;
方法or属性:scrollToTop(speed?: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:scrollToBottom(speed?: number): Promise\;
旧版本信息:|类名:Component;
方法or属性:scrollToBottom(speed?: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:scrollSearch(on: On): Promise\;
旧版本信息:|类名:Component;
方法or属性:scrollSearch(on: On): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Component;
方法or属性:getBoundsCenter(): Promise\;
旧版本信息:|类名:Component;
方法or属性:getBoundsCenter(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:static create(): Driver;
旧版本信息:|类名:Driver;
方法or属性:static create(): Driver;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:delayMs(duration: number): Promise\;
旧版本信息:|类名:Driver;
方法or属性:delayMs(duration: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:findComponent(on: On): Promise\;
旧版本信息:|类名:Driver;
方法or属性:findComponent(on: On): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:findComponents(on: On): Promise\>;
旧版本信息:|类名:Driver;
方法or属性:findComponents(on: On): Promise\>;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:assertComponentExist(on: On): Promise\;
旧版本信息:|类名:Driver;
方法or属性:assertComponentExist(on: On): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:pressBack(): Promise\;
旧版本信息:|类名:Driver;
方法or属性:pressBack(): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:click(x: number, y: number): Promise\;
旧版本信息:|类名:Driver;
方法or属性:click(x: number, y: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:doubleClick(x: number, y: number): Promise\;
旧版本信息:|类名:Driver;
方法or属性:doubleClick(x: number, y: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:longClick(x: number, y: number): Promise\;
旧版本信息:|类名:Driver;
方法or属性:longClick(x: number, y: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:swipe(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\;
旧版本信息:|类名:Driver;
方法or属性:swipe(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| -|跨平台能力有变化|类名:Driver;
方法or属性:fling(from: Point, to: Point, stepLen: number, speed: number): Promise\;
旧版本信息:|类名:Driver;
方法or属性:fling(from: Point, to: Point, stepLen: number, speed: number): Promise\;
新版本信息:crossplatform|@ohos.UiTest.d.ts| diff --git a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-window.md b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-window.md index 70e472b0dace492b5fb2cb731c066cccffab16c4..a7e59afd3b9521e466af1e8c1a1b6e3fe2801b00 100644 --- a/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-window.md +++ b/zh-cn/release-notes/api-diff/v4.0-beta2/js-apidiff-window.md @@ -61,89 +61,4 @@ |访问级别有变化|类名:ScreenModeInfo;
方法or属性:interface ScreenModeInfo
旧版本信息:|类名:ScreenModeInfo;
方法or属性:interface ScreenModeInfo
新版本信息:systemapi|@ohos.screen.d.ts| |权限有变化|类名:screen;
方法or属性:function createVirtualScreen(options: VirtualScreenOption): Promise\;
旧版本信息:|类名:screen;
方法or属性:function createVirtualScreen(options: VirtualScreenOption): Promise\;
新版本信息:ohos.permission.CAPTURE_SCREEN|@ohos.screen.d.ts| |权限有变化|类名:screen;
方法or属性:function setVirtualScreenSurface(screenId: number, surfaceId: string): Promise\;
旧版本信息:|类名:screen;
方法or属性:function setVirtualScreenSurface(screenId: number, surfaceId: string): Promise\;
新版本信息:ohos.permission.CAPTURE_SCREEN|@ohos.screen.d.ts| -|跨平台能力有变化|类名:display;
方法or属性:declare display
旧版本信息:|类名:display;
方法or属性:declare display
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:display;
方法or属性:function getDefaultDisplaySync(): Display;
旧版本信息:|类名:display;
方法or属性:function getDefaultDisplaySync(): Display;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:enum Orientation
旧版本信息:|类名:Orientation;
方法or属性:enum Orientation
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:PORTRAIT = 0
旧版本信息:|类名:Orientation;
方法or属性:PORTRAIT = 0
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:LANDSCAPE = 1
旧版本信息:|类名:Orientation;
方法or属性:LANDSCAPE = 1
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:PORTRAIT_INVERTED = 2
旧版本信息:|类名:Orientation;
方法or属性:PORTRAIT_INVERTED = 2
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:LANDSCAPE_INVERTED = 3
旧版本信息:|类名:Orientation;
方法or属性:LANDSCAPE_INVERTED = 3
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:interface Rect
旧版本信息:|类名:Rect;
方法or属性:interface Rect
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:left: number;
旧版本信息:|类名:Rect;
方法or属性:left: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:top: number;
旧版本信息:|类名:Rect;
方法or属性:top: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:width: number;
旧版本信息:|类名:Rect;
方法or属性:width: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Display;
方法or属性:width: number;
旧版本信息:|类名:Display;
方法or属性:width: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:height: number;
旧版本信息:|类名:Rect;
方法or属性:height: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Display;
方法or属性:height: number;
旧版本信息:|类名:Display;
方法or属性:height: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Display;
方法or属性:interface Display
旧版本信息:|类名:Display;
方法or属性:interface Display
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Display;
方法or属性:id: number;
旧版本信息:|类名:Display;
方法or属性:id: number;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:Display;
方法or属性:orientation: Orientation;
旧版本信息:|类名:Display;
方法or属性:orientation: Orientation;
新版本信息:crossplatform|@ohos.display.d.ts| -|跨平台能力有变化|类名:window;
方法or属性:declare window
旧版本信息:|类名:window;
方法or属性:declare window
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:window;
方法or属性:function createWindow(config: Configuration, callback: AsyncCallback\): void;
旧版本信息:|类名:window;
方法or属性:function createWindow(config: Configuration, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:window;
方法or属性:function createWindow(config: Configuration): Promise\;
旧版本信息:|类名:window;
方法or属性:function createWindow(config: Configuration): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:window;
方法or属性:function findWindow(name: string): Window;
旧版本信息:|类名:window;
方法or属性:function findWindow(name: string): Window;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:window;
方法or属性:function getLastWindow(ctx: BaseContext, callback: AsyncCallback\): void;
旧版本信息:|类名:window;
方法or属性:function getLastWindow(ctx: BaseContext, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:window;
方法or属性:function getLastWindow(ctx: BaseContext): Promise\;
旧版本信息:|类名:window;
方法or属性:function getLastWindow(ctx: BaseContext): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowType;
方法or属性:enum WindowType
旧版本信息:|类名:WindowType;
方法or属性:enum WindowType
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowType;
方法or属性:TYPE_APP
旧版本信息:|类名:WindowType;
方法or属性:TYPE_APP
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:interface Rect
旧版本信息:|类名:Rect;
方法or属性:interface Rect
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:left: number;
旧版本信息:|类名:Rect;
方法or属性:left: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:top: number;
旧版本信息:|类名:Rect;
方法or属性:top: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:width: number;
旧版本信息:|类名:Rect;
方法or属性:width: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Size;
方法or属性:width: number;
旧版本信息:|类名:Size;
方法or属性:width: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Rect;
方法or属性:height: number;
旧版本信息:|类名:Rect;
方法or属性:height: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Size;
方法or属性:height: number;
旧版本信息:|类名:Size;
方法or属性:height: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Size;
方法or属性:interface Size
旧版本信息:|类名:Size;
方法or属性:interface Size
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowProperties;
方法or属性:interface WindowProperties
旧版本信息:|类名:WindowProperties;
方法or属性:interface WindowProperties
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowProperties;
方法or属性:windowRect: Rect;
旧版本信息:|类名:WindowProperties;
方法or属性:windowRect: Rect;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowProperties;
方法or属性:type: WindowType;
旧版本信息:|类名:WindowProperties;
方法or属性:type: WindowType;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowProperties;
方法or属性:brightness: number;
旧版本信息:|类名:WindowProperties;
方法or属性:brightness: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowProperties;
方法or属性:isKeepScreenOn: boolean;
旧版本信息:|类名:WindowProperties;
方法or属性:isKeepScreenOn: boolean;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Configuration;
方法or属性:interface Configuration
旧版本信息:|类名:Configuration;
方法or属性:interface Configuration
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Configuration;
方法or属性:name: string;
旧版本信息:|类名:Configuration;
方法or属性:name: string;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Configuration;
方法or属性:windowType: WindowType;
旧版本信息:|类名:Configuration;
方法or属性:windowType: WindowType;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Configuration;
方法or属性:ctx?: BaseContext;
旧版本信息:|类名:Configuration;
方法or属性:ctx?: BaseContext;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Configuration;
方法or属性:displayId?: number;
旧版本信息:|类名:Configuration;
方法or属性:displayId?: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Configuration;
方法or属性:parentId?: number;
旧版本信息:|类名:Configuration;
方法or属性:parentId?: number;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:enum Orientation
旧版本信息:|类名:Orientation;
方法or属性:enum Orientation
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:UNSPECIFIED = 0
旧版本信息:|类名:Orientation;
方法or属性:UNSPECIFIED = 0
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:PORTRAIT = 1
旧版本信息:|类名:Orientation;
方法or属性:PORTRAIT = 1
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:LANDSCAPE = 2
旧版本信息:|类名:Orientation;
方法or属性:LANDSCAPE = 2
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:PORTRAIT_INVERTED = 3
旧版本信息:|类名:Orientation;
方法or属性:PORTRAIT_INVERTED = 3
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Orientation;
方法or属性:LANDSCAPE_INVERTED = 4
旧版本信息:|类名:Orientation;
方法or属性:LANDSCAPE_INVERTED = 4
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:showWindow(callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:showWindow(callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:showWindow(): Promise\;
旧版本信息:|类名:Window;
方法or属性:showWindow(): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:destroyWindow(callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:destroyWindow(callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:destroyWindow(): Promise\;
旧版本信息:|类名:Window;
方法or属性:destroyWindow(): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:moveWindowTo(x: number, y: number): Promise\;
旧版本信息:|类名:Window;
方法or属性:moveWindowTo(x: number, y: number): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:moveWindowTo(x: number, y: number, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:moveWindowTo(x: number, y: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:resize(width: number, height: number): Promise\;
旧版本信息:|类名:Window;
方法or属性:resize(width: number, height: number): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:resize(width: number, height: number, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:resize(width: number, height: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:getWindowProperties(): WindowProperties;
旧版本信息:|类名:Window;
方法or属性:getWindowProperties(): WindowProperties;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowSystemBarEnable(names: Array\<'status' \| 'navigation'>, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:setWindowSystemBarEnable(names: Array\<'status' \| 'navigation'>, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowSystemBarEnable(names: Array\<'status' \| 'navigation'>): Promise\;
旧版本信息:|类名:Window;
方法or属性:setWindowSystemBarEnable(names: Array\<'status' \| 'navigation'>): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setPreferredOrientation(orientation: Orientation): Promise\;
旧版本信息:|类名:Window;
方法or属性:setPreferredOrientation(orientation: Orientation): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setPreferredOrientation(orientation: Orientation, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:setPreferredOrientation(orientation: Orientation, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:loadContent(path: string, storage: LocalStorage, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:loadContent(path: string, storage: LocalStorage, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:loadContent(path: string, storage: LocalStorage, callback: AsyncCallback\): void;
旧版本信息:|类名:WindowStage;
方法or属性:loadContent(path: string, storage: LocalStorage, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:loadContent(path: string, storage: LocalStorage): Promise\;
旧版本信息:|类名:Window;
方法or属性:loadContent(path: string, storage: LocalStorage): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setUIContent(path: string, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:setUIContent(path: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setUIContent(path: string): Promise\;
旧版本信息:|类名:Window;
方法or属性:setUIContent(path: string): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:isWindowShowing(): boolean;
旧版本信息:|类名:Window;
方法or属性:isWindowShowing(): boolean;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowBackgroundColor(color: string): void;
旧版本信息:|类名:Window;
方法or属性:setWindowBackgroundColor(color: string): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowBrightness(brightness: number): Promise\;
旧版本信息:|类名:Window;
方法or属性:setWindowBrightness(brightness: number): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowBrightness(brightness: number, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:setWindowBrightness(brightness: number, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowKeepScreenOn(isKeepScreenOn: boolean): Promise\;
旧版本信息:|类名:Window;
方法or属性:setWindowKeepScreenOn(isKeepScreenOn: boolean): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:Window;
方法or属性:setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback\): void;
旧版本信息:|类名:Window;
方法or属性:setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:interface WindowStage
旧版本信息:|类名:WindowStage;
方法or属性:interface WindowStage
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:getMainWindow(): Promise\;
旧版本信息:|类名:WindowStage;
方法or属性:getMainWindow(): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:getMainWindow(callback: AsyncCallback\): void;
旧版本信息:|类名:WindowStage;
方法or属性:getMainWindow(callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:getMainWindowSync(): Window;
旧版本信息:|类名:WindowStage;
方法or属性:getMainWindowSync(): Window;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:createSubWindow(name: string): Promise\;
旧版本信息:|类名:WindowStage;
方法or属性:createSubWindow(name: string): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:createSubWindow(name: string, callback: AsyncCallback\): void;
旧版本信息:|类名:WindowStage;
方法or属性:createSubWindow(name: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:getSubWindow(): Promise\>;
旧版本信息:|类名:WindowStage;
方法or属性:getSubWindow(): Promise\>;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:getSubWindow(callback: AsyncCallback\>): void;
旧版本信息:|类名:WindowStage;
方法or属性:getSubWindow(callback: AsyncCallback\>): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:loadContent(path: string, storage?: LocalStorage): Promise\;
旧版本信息:|类名:WindowStage;
方法or属性:loadContent(path: string, storage?: LocalStorage): Promise\;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:loadContent(path: string, callback: AsyncCallback\): void;
旧版本信息:|类名:WindowStage;
方法or属性:loadContent(path: string, callback: AsyncCallback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:on(eventType: 'windowStageEvent', callback: Callback\): void;
旧版本信息:|类名:WindowStage;
方法or属性:on(eventType: 'windowStageEvent', callback: Callback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| -|跨平台能力有变化|类名:WindowStage;
方法or属性:off(eventType: 'windowStageEvent', callback?: Callback\): void;
旧版本信息:|类名:WindowStage;
方法or属性:off(eventType: 'windowStageEvent', callback?: Callback\): void;
新版本信息:crossplatform|@ohos.window.d.ts| +|函数有变化|类名:Window;
方法or属性:off(type: 'windowEvent',callback:Callback\):void;|类名:Window;
方法or属性:off(type:'windowEvent',callback?: Callback\ + ): void; + static clean(accountId: string, appActions: { [bundleName: string]: Action }): Promise; + ``` + +修改后的接口原型: + + ```ts + static clear( + accountId: string, + appActions: { [bundleName: string]: ClearAction }, + callback: AsyncCallback + ): void; + static clear(accountId: string, appActions: { [bundleName: string]: ClearAction }): Promise; + ``` + +## cl.data.relationalStore修改Statistic中的success为successful + +**变更影响** + +基于OpenHarmony4.0.9.3及之后的SDK版本开发的应用,可以使用Statistic.successful表示数据库表中端云同步成功的行数。 + +**关键接口/组件变更** + +Statistic中的枚举项success变更为successful,successful表示数据库表中端云同步成功的行数。 + +修改前的接口原型: + + ```ts + interface Statistic { + total: number; + success: number; + failed: number; + remained: number; + } + ``` + +修改后的接口原型: + + ```ts + interface Statistic { + total: number; + successful: number; + failed: number; + remained: number; + } + ``` + +## cl.data.relationalStore修改setDistributedTables接口入参type类型由number变为DistributedType + +**变更影响** + +基于OpenHarmony4.0.9.3及之后的SDK版本开发的应用,setDistributedTables接口入参type类型由number变为DistributedType。 + +**关键接口/组件变更** + +修改前setDistributedTables接口: + + ```ts +setDistributedTables(tables: Array, type: number, config: DistributedConfig, callback: AsyncCallback): void; +setDistributedTables(tables: Array, type?: number, config?: DistributedConfig): Promise; + ``` + +修改后setDistributedTables接口: + + ```ts +setDistributedTables(tables: Array, type: DistributedType, config: DistributedConfig, callback: AsyncCallback): void; +setDistributedTables(tables: Array, type?: DistributedType, config?: DistributedConfig): Promise; + ``` + diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.3/changelogs-wifiManager.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.3/changelogs-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..2ca92cb60b808544f3a7ae94b0ccd1460c219e03 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.3/changelogs-wifiManager.md @@ -0,0 +1,48 @@ +# wifi子系统ChangeLog + +## 1 权限变更。 + +1. 接口新增返回随机mac,取消位置权限。 +1. 返回真实mac需要GET_PEER_MAC权限。 + +| 接口声明 | 权限变更说明 | +| -------- | ---------------------------- | +|**function** getCandidateConfigs(): Array; | 1.取消位置权限 | +|**function** getDeviceConfigs(): Array; | 1.取消位置权限 | +|**function** getStations(): Array; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** getScanInfoList(): Array; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** getCurrentP2pGroup(): Promise; | 1.取消位置权限 | +| **function** getCurrentP2pGroup(callback: AsyncCallback): **void**; | 1.取消位置权限 | +| **function** getP2pPeerDevices(): Promise; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** getP2pPeerDevices(callback: AsyncCallback): **void**; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** p2pConnect(config: WifiP2PConfig): **void**; | 1.取消位置权限 | +| **function** startDiscoverDevices(): **void**; | 1.取消位置权限 | +| **function** getP2pGroups(): Promise>; | 1.取消位置权限 | +| **function** getP2pGroups(callback: AsyncCallback>): **void**; | 1.取消位置权限 | +| **function** on(**type**: "p2pDeviceChange", callback: Callback): **void**; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** off(**type**: "p2pDeviceChange", callback?: Callback): **void**; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** on(**type**: "p2pPeerDeviceChange", callback: Callback): **void**; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | +| **function** off(**type**: "p2pPeerDeviceChange", callback?: Callback): **void**; | 1.取消位置权限;2.返回随机MAC(GET_PEER_MAC权限返回真实MAC) | + + +### 2 新增接口声明 +| 接口声明 | 接口描述 | +|------|---------| +| **function** startScan(): **void**; | 启动扫描 | +| **function** getScanInfoList(): Array; | 获取扫描列表 | +| **function** setScanAlwaysAllowed(isScanAlwaysAllowed: boolean): **void**; | 设置后台扫描开关 | +| **function** getScanAlwaysAllowed(): boolean; | 获取后台扫描开关 | +| **function** getIpv6Info(): Ipv6Info; | 获取ipv6地址信息 | +| **function** isBandTypeSupported(bandType: WifiBandType): boolean; | 判断是否支持BandType | +| **function** get5GChannelList(): Array<**number**>; | 获取5G信道列表 | +| **function** getDisconnectedReason(): DisconnectedReason; | 获取网络断开原因 | + +### 3 废弃接口 + + +| 接口声明 |废弃说明 | +| ------------- |-------------------------------------------------------- | +| **function** scan(): **void**; | 使用startScan接口启动扫描 | +| **function** getScanResults(): Promise>; | 使用getScanInfoList获取扫描列表 | +| **function** getScanResults(callback: AsyncCallback>): **void**; | 使用getScanInfoList获取扫描列表 | +| **function** getScanResultsSync(): Array; | 使用getScanInfoList获取扫描列表 | diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-filemanagement.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-filemanagement.md new file mode 100644 index 0000000000000000000000000000000000000000..fe8a138de08225d8740733fee5a45ab96952e4b9 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-filemanagement.md @@ -0,0 +1,25 @@ +# 文件管理子系统ChangeLog +## c1.filemanager.1 fileAccess 模块变更 +fileAccess 将不支持获取缩略图和媒体资源的部分查询 + +**变更影响** +1. getThumbnail 接口下架 +2. FILEKEY 图像和音频选项下架 + +**关键的接口/组件变更** +删除接口如下 + +| 类名 | 删除接口声明 | +| -------------- | ------------------------------------------------------------ | +| fileAccessHelper | getThumbnail(uri: string, size: image.Size): Promise;| +| fileAccessHelper | getThumbnail(uri: string, size: image.Size, callback: AsyncCallback): void;| + + 选项删除 +| 枚举类型 | 删除的键值 | +| -------- | ---- | +| FileKey | DURATION = 'duration' | +| FileKey | WIDTH = 'width' | +| FileKey | HEIGHT = 'height' | + + + diff --git a/zh-cn/release-notes/changelogs/v3.2-Release/changelogs-arkui.md b/zh-cn/release-notes/changelogs/v3.2-Release/changelogs-arkui.md index 23d453b41ef6811d484f1c62796676f6a2f1013b..204cfef02cb9f9dc919f08e6379e91609e5d91a5 100644 --- a/zh-cn/release-notes/changelogs/v3.2-Release/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/v3.2-Release/changelogs-arkui.md @@ -304,3 +304,11 @@ pluginComponentManager.request({ } ) ``` + +## cl.arkui.4 FormComponent组件中的JS卡片禁用网络图片 + +FormComponent组件中的JS卡片禁止使用网络图片。 + +**变更影响** + +影响FormComponent中JS卡片中网络图片的加载显示。变更前JS卡片支持网络图片加载,变更后JS卡片不支持网络图片的加载。变更后建议将所需的网络图片下载至内存后刷新。 diff --git a/zh-cn/release-notes/changelogs/v3.2-beta5/changelogs-arkui.md b/zh-cn/release-notes/changelogs/v3.2-beta5/changelogs-arkui.md index d661cf1d84f2b2c6b06bb8102d30455fb07a7e43..b1af2ae07fc10e153745bfb8c589a3aef082ff09 100644 --- a/zh-cn/release-notes/changelogs/v3.2-beta5/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/v3.2-beta5/changelogs-arkui.md @@ -39,8 +39,6 @@ } ``` - ![datePicker](../../../application-dev/reference/arkui-ts/figures/datePicker.gif) - 2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。 类型定义中的Length、ResourceStr、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。 diff --git a/zh-cn/third-party-cases/app_quality_improvement_cases_about_crash.md b/zh-cn/third-party-cases/app_quality_improvement_cases_about_crash.md new file mode 100644 index 0000000000000000000000000000000000000000..3143a0c25a0ef47e45e145b598c90ec03b857d51 --- /dev/null +++ b/zh-cn/third-party-cases/app_quality_improvement_cases_about_crash.md @@ -0,0 +1,83 @@ +# 应用质量提升案例-应用Crash闪退问题案例分析 + +## 问题描述 + +OpenHarmony某应用点击多次或者页面切换时,会出现应用闪退现象。 + + + +## 问题现象 + +1.打印提示Crash,每次Crash的进程一致,均是Process name:com.chinasoftinc.launcher, 线程却不确定,mosquitto loop、jsThread-1随机出现; + +2.Crash的时机不确定,页面点击次数累计一定程序出现,native不回调JS function时不会出现Crash,JS function代码量多时,则Crash概率大,代码量小时,Crash概率小。 + + mosquitto loop、jsThread-1 二者crash随机出现 + +![img](figures/crash_1.png) + +mosquitto loop crash: + +![img](figures/crash_2.png) + +jsThread-1 crash: + +![img](figures/crash_3.png) + + Crash报错的其中两次堆栈信息如下,可以看到两次堆栈信息并不一致: + +![img](figures/crash_4.png) + +![img](figures/crash_5.png) + + + +## 问题分析 + +虽然每次crash的线程不一样,但范围是确定的,jsThread-1 或者 mosquitto loop,可以确定是两个线程交互的问题。 + +jsThread-1为UI线程,即应用页面对应的线程; + +mosquitto loop是用来监听mosquitto服务器是否有消息上来,有则触发JS Function回调函数; + +JS为单线程,没有锁,严格意义上不支持多线程,线程间的调度需要使用ArkUI统一的调度函数uv_queue_work来处理多线程调度问题。 + +如果不使用统一调度函数,会发生下面两种异常情况: + +1. jsThread-1线程运行时,mosquitto loop消息上来直接触发回调,会导致jsThread-1异常退出; + +2. mosquitto loop处理回调时,jsThread-1可能直接抢占处理,导致mosquitto loop异常退出。 + + + +## 问题冲突 + +Napi 提供了创建新线程的方法:napi_get_uv_event_loop,但只能在JS主线程中使用,uv_queue_work只能处理napi_get_uv_event_loop创建的线程,不支持mosquitto loop方式; + +若要监听消息,只能用mosquitto loop起新线程监听。 + + + +## 解决方案 + +问题本质原因是调用回调函数时出的问题: + +![img](figures/crash_6.png) + +监听消息的线程可以正常处理,与JS线程无冲突。 + +修改方案为:保留mosquitto loop获取消息,触发C处理消息上来事件,将原有消息事件处理中 直接调用napi_call_function 的方式改为 napi_get_uv_event_loop方式创建新的线程,uv_queue_work队列方式管理新线程调度,在新线程中调用napi_call_function。 + +消息事件处理函数: + +![img](figures/crash_7.png) + + 新线程中处理JS Function回调: + +![img](figures/crash_8.png) + + + +至此,crash问题得到解决。 + +希望本文能够为应用开发者处理类似crash问题提供帮助。 \ No newline at end of file diff --git a/zh-cn/third-party-cases/app_quality_improvement_cases_about_jserror.md b/zh-cn/third-party-cases/app_quality_improvement_cases_about_jserror.md new file mode 100644 index 0000000000000000000000000000000000000000..1710fe42fad3b341c91caa9e6da5f3df2b15aaaa --- /dev/null +++ b/zh-cn/third-party-cases/app_quality_improvement_cases_about_jserror.md @@ -0,0 +1,187 @@ +# 应用质量提升案例-稳定性测试常见JS_ERROR问题分析与定位 + +## 问题描述 + +本文案例分析OpenHarmony开发的应用进行稳定性测试遇到的JS_ERROR,对其产生的原因进行分析与定位,并给出解决方案。 + +几种常见的错误信息如下: + +1)Obj is not a valid object :访问对象无效或不存在; + +2)is not callable :调用方法不存在; + +3)Internal error. UI execution context not found:未找到UI执行的上下文。 + + + +## 案例分析 + +### softwareUpdate.js出现JS_ERROR + +问题描述: + +系统稳定性测试10000分钟,com.ohos.settings 出现 17次JS_ERROR(softwareUpdate.js)。 + +堆栈异常信息: + +``` +Module name:com.ohos.settings +Pid:28150 +Uid:20010012 +Lifetime: 0.000000s +Js-Engine: ark +page: pages/softwareUpdate.js +Error message: Obj is not a valid object +Stacktrace: + at get (\\MainAbility\\pages\\softwareUpdate.ets:512:25) + at loading (./pages/softwareUpdate.js:2127:16) + at anonymous (./pages/softwareUpdate.js:2141:13) +``` + +问题定位: + +该问题提示错误类型:Obj is not a valid object。 + +发生在调用 loading时get 操作,相关代码行数在commons.js中2141、2127、512等行数。 + +![img](figures/jserror_1.png) + +问题原因: + +经过代码比对、流程分析、hilog校对等方式,确认该问题是由于偶发退出页面时未销毁setInterval定时器,导致后台程序仍访问前台page页面中的全局变量this.angle。 + +通过模拟该场景可必现相同jserror日志。 + +解决措施: + +对业务代码流程进行梳理,确保开启/关闭定时器操作成对出现,避免再次发生后台程序访问前台page页面中的全局变量。 + + + +### notificationManage.js出现JS_ERROR + +问题描述: + +应用稳定性测试48小时,com.ohos.settings出现14次JS_ERROR(notificationManage.js)。 + +堆栈异常信息: + +``` +Module name:com.ohos.settings +Pid:17337 +Uid:20010012 +Lifetime: 0.000000s +Js-Engine: ark +page: pages/noticeApp/notificationManage.js +Error message: Obj is not a valid object +Stacktrace: + at initNotificationEnableInit (/pages/noticeApp/notificationManage.js:8479:16) + at initNotificationEnableInit (\pages\noticeApp\notificationManage.ets:31:5) + at anonymous (\pages\noticeApp\notificationManage.ets:20:7) +``` + + 问题定位: + +该问题提示错误类型:Obj is not a valid object。 + +发生在调用initNotificationEnableInit 时,相关代码行数在notificationManage.ets中20、31行,commons.js中8479行。 + +![img](figures/jserror_2.png) + +问题原因: + +经过代码比对、流程分析、hilog校对确认问题根因是notificationManage中调用initNotificationEnableInit 方法时参数非法,导致最终调用接口Notification.isNotificationEnabled时产生jserror。 + +解决措施: + +对非法参数进行异常处理。 + + + +### softwareUDiskUpdate.js出现JS_ERROR + +问题描述: + +系统稳定性测试10000分钟,com.ohos.settings 出现 1次JS_ERROR(softwareUDiskUpdate.js)。 + +堆栈信息: + +``` +Module name:com.ohos.settings +Pid:22221 +Uid:20010012 +Lifetime: 0.000000s +Js-Engine: ark +page: pages/softwareUDiskUpdate.js +Error message: is not callable +Stacktrace: + at anonymous (\\MainAbility\\pages\\softwareUDiskUpdate.ets:69:15) +``` + + 问题定位:该问题提示错误类型:is not callable。 + +发生softwareUDiskUpdate.ets中,相关代码行数69行。 + +![img](figures/jserror_3.png) + +问题原因: + +经过代码比对、流程分析、hilog校对确认问题根因是调用系统不存在的接口:UpdateSystemFromUDisk()。 + +解决措施: + +此部分代码为冗余未删除代码,需要进行代码清理。 + + + +### wifiPsd.js出现JS_ERROR + +问题描述: + +系统稳定性测试72小时,com.ohos.settings出现1次JS_ERROR:ohos_router_1.back。 + +堆栈信息: + +``` +Module name:com.ohos.settings +Version:2.0.0.002 +Pid:3995 +Uid:20010028 +Reason:Error +Error message:Internal error. UI execution context not found. +SourceCode: + _ohos_router_1.back({ + ^ +Stacktrace: + at anonymous (D:/WorkSpace/Code/Common_Master_3.2/product_min_system/kh_applications_system/applications_settings/product/phone/build/default/intermediates/loader_out/default/ets/pages/wlan/wifiPsd_.js:1197:17) + at anonymous (D:/WorkSpace/Code/Common_Master_3.2/product_min_system/kh_applications_system/applications_settings/product/phone/build/default/intermediates/loader_out/default/ets/MainAbility/MainAbility_.js:2009:17) + at anonymous (D:/WorkSpace/Code/Common_Master_3.2/product_min_system/kh_applications_system/applications_settings/product/phone/build/default/intermediates/loader_out/default/ets/MainAbility/MainAbility_.js:2008:13) +``` + + 问题定位: + +该问题错误提示:UI execution context not found。 + +发生在wifiPsd.js中,调用router.back()函数时出现异常。 + +![img](figures/jserror_4.png) + +问题原因: + +当在异步回调中执行router.back()时,会产生已经不在当前页面的现象,导致router操作失败,例如: + +1)在A页面设置定时器setTimeOut 5秒后router到B页面; + +2)在5S内手动点击切换到其他非A页面上,等待A页面设置的定时器setTimeOut执行时,必现jserror。 + +解决措施: + +对调用router.back()处代码添加try-catch保护。 + + + +## 总结 + +随着OpenHarmony生态的推广,对应的应用开发IDE、测试工具等也会不断完善,应用层面的错误信息也会披露的越来越清晰。大家在应用开发的过程中如果遇到JS_ERROR,可以通过阅读给出的堆栈或者log信息,结合代码来定位问题。 + +希望本文能够为应用开发者在此方面提供一些参考。 \ No newline at end of file diff --git a/zh-cn/third-party-cases/distributed-canvas.md b/zh-cn/third-party-cases/distributed-canvas.md new file mode 100644 index 0000000000000000000000000000000000000000..911ba45da6ba3395f434e7f6a338d2ace302fdbd --- /dev/null +++ b/zh-cn/third-party-cases/distributed-canvas.md @@ -0,0 +1,417 @@ +# 分布式画布流转场景 + +## 场景说明 + +两台设备组网,当其中一个设备修改文件时,两个设备可以同步修改的结果。分布式场景可以在协同办公(如多人多设备编辑同一文件),设备文档更新(分布式设备更新文件内容,所有设备同步更新)中发挥重要作用,有助于加快工作效率,减少工作中的冗余。 + +本示例将为大家介绍如何实现上述功能。 + +## 效果呈现 + +本例效果如下: + +| 设置分布式权限 | 进行分布式连接 | 连接后状态显示 | +| -------------------------------------- | ------------------------------------------ | ----------------------------------------- | +| ![](figures/disributed_permission.png) | ![](figures/disributed_canvas_connect.png) | ![](figures/disributed_canvas-before.png) | + +| 点击rect和ellipse按钮后后本机显示 | 另外一台机器分布式应用显示 | +| ---------------------------------------- | ---------------------------------------- | +| ![](figures/disributed_canvas-after.png) | ![](figures/disributed_canvas-after.png) | + +## 运行环境 + +本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。 + +- IDE:DevEco Studio 4.0.0.201 Beta1 +- SDK:Ohos_sdk_public 4.0.7.5 (API Version 10 Beta1) + +## 实现思路 + +在分布式文件场景中,分布式设备管理包含了分布式设备搜索、分布式设备列表弹窗、远端设备拉起三部分。 +首先在分布式组网内搜索设备,然后把设备展示到分布式设备列表弹窗中,最后根据用户的选择拉起远端设备。 + +- 分布式设备搜索:通过SUBSCRIBE_ID搜索分布式组网内的设备。 + +- 分布式设备列表弹窗:使用@CustomDialog装饰器来装饰分布式设备列表弹窗。 + +- 远端设备拉起:通过startAbility(deviceId)方法拉起远端设备的包。 + +- 分布式数据管理:(1)管理分布式数据库:创建一个distributedObject分布式数据对象实例,用于管理分布式数据对象。 + + ​ (2)订阅分布式数据变化:通过this.distributedObject.on('status', this.statusCallback)监听分布式数据对象的变更。 + +## 开发步骤 + +1. 申请所需权限 + + 在model.json5中添加以下配置: + + ```json + "requestPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC"//允许不同设备间的数据交换 + }, + { + "name": "ohos.permission.ACCESS_SERVICE_DM"//允许系统应用获取分布式设备的认证组网能力 + } + ] + ``` + +2. 构建UI框架 + + indexCanvas页面: + + TitleBar组件呈现标题栏。通过数据懒加载的方式遍历绘制的图形。被划出可视区域外的资源会被回收。 + + 绘制ellipse图形、rect图形的按钮使用Button组件呈现。 + + 返回按钮、删除按钮也通过Button组件呈现。 + + ```typescript + build() { + Column() { + TitleBar({ rightBtn: $r('app.media.trans'), onRightBtnClicked: this.showDialog }) + //自/common/TitleBar.ets中引入标题栏相关。点击标题栏中的右侧按钮会调用showDialog()函数连接组网设备 + Row() { + Text($r('app.string.state')) + .fontSize(30) + Image(this.isOnline ? $r('app.media.green') : $r('app.media.red')) + .size({ width: 30, height: 30 }) + .objectFit(ImageFit.Contain) + } + .width('100%') + .padding(16) + //通过懒加载模式遍历绘制的图形,将每个图形绘制在画布上 + LazyForEach(this.canvasDataSource, (item: CanvasPath, index) => { + Canvas(this.context) + .width('100%') + .height(200) + .backgroundColor('#00ffff') + .onReady(() => { + if (item.path === 'rect') { + this.context.save(); + this.path2Df.rect(80, 80, 100, 100); + this.context.stroke(this.path2Df); + this.context.restore(); + } + if (item.path === 'ellipse') { + this.context.restore(); + this.path2De.ellipse(100, 100, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI); + this.context.stroke(this.path2De); + this.context.save(); + } + }) + }, item => JSON.stringify(item)) + + Row() { + Button('ellipse')//绘制ellipse图形的按钮 + .width(130) + .height(45) + .key('ellipse') + .onClick(() => { + if (this.globalObject.isContainString('ellipse') === -1) { + this.globalObject.add('ellipse'); //将绘制信息保存在持久全局数据中 + } + this.onPageShow(); + }) + Button('rect')//绘制rect图形的按钮 + .width(130) + .height(45) + .key('rect') + .onClick(() => { + if (this.globalObject.isContainString('rect') === -1) { + this.globalObject.add('rect'); + } + this.onPageShow(); + }) + }.margin({ top: 10 }) + .width('100%') + .justifyContent(FlexAlign.SpaceAround) + + Row() { + Button('back') + .width(130) + .height(45) + .key('back') + .backgroundColor(Color.Orange) + .onClick(() => { + router.back() + }) + Button('delete')//删除图形 + .width(130) + .height(45) + .key('delete') + .onClick(() => { + this.globalObject.clear(); + this.canvasDataSource['pathArray'] = []; + this.canvasDataSource.notifyDataReload(); + this.context.clearRect(0, 0, 950, 950) + }) + }.margin({ top: 10 }) + .width('100%') + .justifyContent(FlexAlign.SpaceAround) + } + .width('100%') + .height('100%') + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + } + } + ``` + +3. 数据model + + 通过registerDataChangeListener进行对数据变动的监听,数据发生变化时,调用notifyDataReload方法通知数据已经准备就绪。 + + ```typescript + //BasicDataSource.ets + class BasicDataSource implements IDataSource { + private listeners: DataChangeListener[] = [] + + public totalCount(): number { + return 0 + } + + public getData(index: number): any { + return undefined + } + + //注册数据变动的监听 + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + console.info('add listener') + this.listeners.push(listener) + } + } + + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { + console.info('remove listener') + this.listeners.splice(pos, 1) + } + } + + //数据reloaded,分布式数据数值变化需要调用这个接口重载下 + notifyDataReload(): void { + this.listeners.forEach(listener => { + listener.onDataReloaded() + }) + } + + notifyDataAdd(index: number): void { + this.listeners.forEach(listener => { + listener.onDataAdd(index) + }) + } + + .... + + export class CanvasDataSource extends BasicDataSource { + //监听的数据类型 + private pathArray: Canvas[] = [] + + //重载接口 + public totalCount(): number { + return this.pathArray.length + } + + public getData(index: number): any { + return this.pathArray[index] + } + + public addData(index: number, data: Canvas): void { + this.pathArray.splice(index, 0, data) + this.notifyDataAdd(index) + } + + public pushData(data: Canvas): void { + this.pathArray.push(data) + this.notifyDataAdd(this.pathArray.length - 1) + } + } + ``` + +4. 将两台设备组网 + + 使用自RemoteDeviceModel.ts中引入的类RemoteDeviceModel以扫描获得附近可以连接的设备。 + + ```typescript + showDialog = () => { + //RemoteDeviceModel引入自model/RemoteDeviceModel.ts + RemoteDeviceModel.registerDeviceListCallback(() => { + //得到附近可信的设备列表 + Logger.info(TAG, 'registerDeviceListCallback, callback entered') + this.devices = [] + this.devices = RemoteDeviceModel.discoverDevices.length > 0 ? RemoteDeviceModel.discoverDevices : RemoteDeviceModel.devices + if (this.dialogController) { + this.dialogController.close() + this.dialogController = undefined + } + this.dialogController = new CustomDialogController({ + builder: DeviceDialog({ + devices: this.devices, + onSelectedIndexChange: this.onSelectedDevice + }), + autoCancel: true + }) + this.dialogController.open() + }) + } + .................................... + //model/RemoteDeviceModel.ts + import deviceManager from '@ohos.distributedHardware.deviceManager' + registerDeviceListCallback(stateChangeCallback: () => void) { + if (typeof (this.deviceManager) !== 'undefined') { + this.registerDeviceListCallbackImplement(stateChangeCallback) + return + } + Logger.info(TAG, 'deviceManager.createDeviceManager begin') + try { + deviceManager.createDeviceManager(BUNDLE, (error, value) => { + if (error) { + Logger.error(TAG, 'createDeviceManager failed.') + return + } + this.deviceManager = value + this.registerDeviceListCallbackImplement(stateChangeCallback) + Logger.info(TAG, `createDeviceManager callback returned,value=${value}`) + }) + } catch (error) { + Logger.error(TAG, `createDeviceManager throw error, code=${error.code} message=${error.message}`) + } + + Logger.info(TAG, 'deviceManager.createDeviceManager end') + } + registerDeviceListCallbackImplement(stateChangeCallback: () => void) { + Logger.info(TAG, 'registerDeviceListCallback') + this.stateChangeCallback = stateChangeCallback + if (this.deviceManager === undefined) { + Logger.error(TAG, 'deviceManager has not initialized') + this.stateChangeCallback() + return + } + Logger.info(TAG, 'getTrustedDeviceListSync begin') + try { + let list = this.deviceManager.getTrustedDeviceListSync()//同步获取所有可信设备列表 + Logger.info(TAG, `getTrustedDeviceListSync end, devices=${JSON.stringify(list)}`) + if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') { + this.devices = list + } + } catch (error) { + Logger.error(TAG, `getLocalDeviceInfoSync throw error, code=${error.code} message=${error.message}`) + } + this.stateChangeCallback() + Logger.info(TAG, 'callback finished') + try { + this.deviceManager.on('deviceStateChange', (data) => { + if (data === null) { + return + } + Logger.info(TAG, `deviceStateChange data = ${JSON.stringify(data)}`) + switch (data.action) { + case deviceManager.DeviceStateChangeAction.READY://即设备处于可用状态,表示设备间信息已在分布式数据中同步完成, 可以运行分布式业务 + this.discoverDevices = [] + this.devices.push(data.device) + this.stateChangeCallback() + try { + let list = this.deviceManager.getTrustedDeviceListSync() + if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') { + this.devices = list + } + } catch (error) { + Logger.error(TAG, `getTrustedDeviceListSync throw error, code=${error.code} message=${error.message}`) + } + this.stateChangeCallback() + break + default: + break + } + }) + this.deviceManager.on('deviceFound', (data) => { + if (data === null) { + return + } + Logger.info(TAG, `deviceFound data=${JSON.stringify(data)}`) + this.onDeviceFound(data) + }) + this.deviceManager.on('discoverFail', (data) => { + Logger.info(TAG, `discoverFail data=${JSON.stringify(data)}`) + }) + this.deviceManager.on('serviceDie', () => { + Logger.info(TAG, 'serviceDie') + }) + } catch (error) { + Logger.error(TAG, `on throw error, code=${error.code} message=${error.message}`) + } + this.startDeviceDiscovery() + } + startDeviceDiscovery() { + SUBSCRIBE_ID = Math.floor(65536 * Math.random()) + var info = { + subscribeId: SUBSCRIBE_ID, + mode: 0xAA, + medium: 2, + freq: 2,//高频率 + isSameAccount: false, + isWakeRemote: true, + capability: 0 + } + Logger.info(TAG, `startDeviceDiscovery${SUBSCRIBE_ID}`) + try { + this.deviceManager.startDeviceDiscovery(info)//开始发现周边设备 + } catch (error) { + Logger.error(TAG, `startDeviceDiscovery throw error, code=${error.code} message=${error.message}`) + } + + } + ``` + +5. 实现同步编辑 + + 通过AppStorage设置持久性数据,然后实现IDataSource接口,通过注册数据监听接口监听数据的变化。 + + ```typescript + onPageShow() { + //每当完成编辑或者新建文件,就会回到主页,此时就会执行onPageShow() + //noteDataSource获取globalObject保存的分布式的持久性数据,并进行Reload操作传递。 + this.noteDataSource['dataArray'] = this.globalObject.distributedObject.documents + this.noteDataSource.notifyDataReload() + Logger.info(TAG, `this.sessionId = ${this.sessionId}`) + Logger.info(TAG, `globalSessionId = ${this.globalSessionId}`) + if (this.sessionId !== this.globalSessionId) { + this.sessionId = this.globalSessionId + this.share() + } + } + share() { + //多个设备间的对象如果设置为同一个sessionId,数据自动同步 + Logger.info(TAG, `sessionId = ${this.sessionId}`) + this.globalObject.setChangeCallback(() => { + this.noteDataSource['dataArray'] = this.globalObject.distributedObject.documents + this.noteDataSource.notifyDataReload() + }) + this.globalObject.setStatusCallback((session, networkId, status) => { + Logger.info(TAG, `StatusCallback,${status}`) + if (status === 'online') { + this.isOnline = true + } else { + this.isOnline = false + } + }) + this.globalObject.distributedObject.setSessionId(this.sessionId) + AppStorage.SetOrCreate('objectModel', this.globalObject) + } + ``` + +## 全部代码 + +本例完整代码sample示例链接:[分布式对象](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedNote) + +## 参考 + +[权限列表](../application-dev/security/permission-list.md#ohospermissiondistributed_datasync) + +[Path2D对象](../application-dev/reference/arkui-ts/ts-components-canvas-path2d.md) + +[分布式数据对象](../application-dev/reference/apis/js-apis-data-distributedobject.md) diff --git a/zh-cn/third-party-cases/distributed-file.md b/zh-cn/third-party-cases/distributed-file.md new file mode 100644 index 0000000000000000000000000000000000000000..2cef7070e7aa4479d5b4c69639e91d06d2ad1f4f --- /dev/null +++ b/zh-cn/third-party-cases/distributed-file.md @@ -0,0 +1,482 @@ +# 分布式文件场景 + +## 场景说明 + +两台设备组网的分布式场景是工作中常常需要的。常见的如代码的同步编辑、文档的同步修改等。这样的分布式场景有助于加快工作效率,减少工作中的冗余,本例将为大家介绍如何实现上述功能。 + +## 效果呈现 + +本例效果如下: + +| 设置分布式权限 | 进行分布式连接 | 连接后状态显示 | +| -------------------------------------- | ---------------------------------------- | --------------------------------------- | +| ![](figures/disributed_permission.png) | ![](figures/disributed_note_connect.png) | ![](figures/disributed_note-before.png) | + +| 点击添加进入编辑界面 | 保存后本机显示 | 另外一台机器分布式应用显示 | +| ------------------------------------- | -------------------------------------- | -------------------------------------- | +| ![](figures/disributed_note-edit.png) | ![](figures/disributed_note-after.png) | ![](figures/disributed_note-after.png) | + +## 运行环境 + +本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。 + +- IDE:DevEco Studio 4.0.0.201 Beta1 +- SDK:Ohos_sdk_public 4.0.7.5 (API Version 10 Beta1) + +## 实现思路 + +在分布式文件场景中,分布式设备管理包含了分布式设备搜索、分布式设备列表弹窗、远端设备拉起三部分。 +首先在分布式组网内搜索设备,然后把设备展示到分布式设备列表弹窗中,最后根据用户的选择拉起远端设备。 + +- 分布式设备搜索:通过SUBSCRIBE_ID搜索分布式组网内的设备。 + +- 分布式设备列表弹窗:使用@CustomDialog装饰器来装饰分布式设备列表弹窗。 + +- 远端设备拉起:通过startAbility(deviceId)方法拉起远端设备的包。 + +- 分布式数据管理:(1)管理分布式数据库:创建一个distributedObject分布式数据对象实例,用于管理分布式数据对象。 + + ​ (2)订阅分布式数据变化:通过this.distributedObject.on('status', this.statusCallback)监听分布式数据对象的变更。 + +## 开发步骤 + +1. 申请所需权限 + + 在model.json5中添加以下配置: + + ```json + "requestPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC"//允许不同设备间的数据交换 + }, + { + "name": "ohos.permission.ACCESS_SERVICE_DM"//允许系统应用获取分布式设备的认证组网能力 + } + ] + ``` + +2. 构建UI框架 + + index页面: + + TitleBar组件呈现标题栏。使用List组件呈现文件列表,ListItem由一个呈现文件类型标志的Image组件,一个呈现文件标题的Text组件,一个呈现文件内容的Text组件组成。 + + ```typescript + build() { + Column() { + TitleBar({ rightBtn: $r('app.media.trans'), onRightBtnClicked: this.showDialog }) + //自/common/TitleBar.ets中引入标题栏相关。点击标题栏中的右侧按钮会调用showDialog()函数连接组网设备 + Row() { + Text($r('app.string.state')) + .fontSize(30) + Image(this.isOnline ? $r('app.media.green') : $r('app.media.red'))//两台设备组网成功后状态显示为绿色、否则为红色 + .size({ width: 30, height: 30 }) + .objectFit(ImageFit.Contain) + } + .width('100%') + .padding(16) + //通过数据懒加载的方式从数据源中每次迭代一个文件进行展示,可用列表被放置在滚动容器中,被划出可视区域外的资源会被回收 + List({ space: 10 }) { + LazyForEach(this.noteDataSource, (item: Note, index) => { + ListItem() { + NoteItem({ note: item, index: index })//NoteItem引入自common/NoteItem.ets,负责主页文件信息的呈现 + .id(`${item.title}`) + } + }, item => JSON.stringify(item)) + } + .width('95%') + .margin(10) + .layoutWeight(1) + + Row() { + Column() { + Image($r('app.media.clear'))//清除按钮 + .size({ width: 40, height: 40 }) + Text($r('app.string.clear')) + .fontColor(Color.Red) + .fontSize(20) + }.layoutWeight(1) + .id('clearNote') + .onClick(() => { + //点击清除按钮清除所有文件 + Logger.info(TAG, 'clear notes') + this.noteDataSource['dataArray'] = [] + this.noteDataSource.notifyDataReload() + this.globalObject.clear() + AppStorage.SetOrCreate('sessionId', this.sessionId) + }) + + Column() { + Image($r('app.media.add'))//添加按钮 + .size({ width: 40, height: 40 }) + Text($r('app.string.add')) + .fontColor(Color.Black) + .fontSize(20) + }.layoutWeight(1) + .id('addNote') + .onClick(() => { + //点击添加按钮跳转到编辑页面 + router.push({ + url: 'pages/Edit', + params: { + note: new Note('', '', -1), + isAdd: true + } + }) + }) + } + .width('100%') + .padding(10) + .backgroundColor('#F0F0F0') + } + .width('100%') + .height('100%') + .backgroundColor('#F5F5F5') + } + } + ... + //common/NoteItem.ets + import router from '@ohos.router' + import { MARKS } from '../model/Const' + import Note from '../model/Note' + + @Component + export default struct NoteItem { + @State note: Note | undefined = undefined + private index: number = 0 + + build() { + Row() { + Image(this.note.mark >= 0 ? MARKS[this.note.mark] : $r('app.media.note'))//文件标志图片 + .size({ width: 30, height: 30 }) + .objectFit(ImageFit.Contain) + Column() { + Text(this.note.title)//文件标题 + .fontColor(Color.Black) + .fontSize(30) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + Text(this.note.content)//文件内容 + .fontColor(Color.Gray) + .margin({ top: 10 }) + .fontSize(25) + .maxLines(1)//在列表中最多展示一行 + .textOverflow({ overflow: TextOverflow.Ellipsis }) + } + .alignItems(HorizontalAlign.Start) + .margin({ left: 20 }) + } + .padding(16) + .width('100%') + .borderRadius(16) + .backgroundColor(Color.White) + .onClick(() => { + //点击文件进入此文件编辑页面 + router.push({ + url: 'pages/Edit', + params: { + index: this.index, + note: this.note, + isAdd: false + } + }) + }) + } + } + ``` + + Edit页面: + + 使用TextInput组件呈现文件标题输入框,使用TextArea组件呈现文件内容的输入区域,使用Button组件呈现保存按钮并绑定点击事件以新建或更新文件内容。 + + ```typescript + build() { + Column() { + TitleBar({ title: this.note.title === '' ? $r('app.string.add_note') : this.note.title }) + Column() { + Row() { + Image(this.note.mark >= 0 ? MARKS[this.note.mark] : $r('app.media.mark')) + .width(30) + .aspectRatio(1) + .margin({ left: 16, top: 16 }) + .objectFit(ImageFit.Contain) + .alignSelf(ItemAlign.Start) + Select([{ value: ' ', icon: MARKS[0] }, + { value: ' ', icon: MARKS[1] }, + { value: ' ', icon: MARKS[2] }, + { value: ' ', icon: MARKS[3] }, + { value: ' ', icon: MARKS[4] }]) + .selected(this.note.mark) + .margin({ top: 5 }) + .onSelect((index: number) => { + this.note.mark = index + }) + } + .width('100%') + + TextInput({ placeholder: 'input the title', text: this.note.title })//文件标题输入框 + .id('titleInput') + .placeholderColor(Color.Gray) + .fontSize(30) + .margin({ left: 15, right: 15, top: 15 }) + .height(60) + .backgroundColor(Color.White) + .onChange((value: string) => { + this.note.title = value + }) + TextArea({ placeholder: 'input the content', text: this.note.content })//文件内容输入区域 + .id('contentInput') + .placeholderColor(Color.Gray) + .backgroundColor(Color.White) + .fontSize(30) + .height('35%') + .margin({ left: 16, right: 16, top: 16 }) + .textAlign(TextAlign.Start) + .onChange((value: string) => { + this.note.content = value + }) + + Button() { + //保存按钮 + Text($r('app.string.save')) + .fontColor(Color.White) + .fontSize(17) + } + .id('saveNote') + .backgroundColor('#0D9FFB') + .height(50) + .width(200) + .margin({ top: 20 }) + .onClick(() => { + //点击按钮时调用model/DistributedObjectModel.ts定义的类globalObject中的方法 + if (!this.isAdd) { + let index = router.getParams()['index'] + this.globalObject.update(index, this.note.title, this.note.content, this.note.mark)//编辑时更新内容 + } else { + this.globalObject.add(this.note.title, this.note.content, this.note.mark)//新建时添加内容 + } + router.back()//返回主页 + }) + } + } + .width('100%') + .height('100%') + .backgroundColor('#F5F5F5') + } + } + ``` + +3. 将两台设备组网 + + 使用自RemoteDeviceModel.ts中引入的类RemoteDeviceModel以扫描获得附近可以连接的设备。 + + ```typescript + showDialog = () => { + //RemoteDeviceModel引入自model/RemoteDeviceModel.ts + RemoteDeviceModel.registerDeviceListCallback(() => { + //得到附近可信的设备列表 + Logger.info(TAG, 'registerDeviceListCallback, callback entered') + this.devices = [] + this.devices = RemoteDeviceModel.discoverDevices.length > 0 ? RemoteDeviceModel.discoverDevices : RemoteDeviceModel.devices + if (this.dialogController) { + this.dialogController.close() + this.dialogController = undefined + } + this.dialogController = new CustomDialogController({ + builder: DeviceDialog({ + devices: this.devices, + onSelectedIndexChange: this.onSelectedDevice + }), + autoCancel: true + }) + this.dialogController.open() + }) + } + ... + //model/RemoteDeviceModel.ts + import deviceManager from '@ohos.distributedHardware.deviceManager' + registerDeviceListCallback(stateChangeCallback: () => void) { + if (typeof (this.deviceManager) !== 'undefined') { + this.registerDeviceListCallbackImplement(stateChangeCallback) + return + } + Logger.info(TAG, 'deviceManager.createDeviceManager begin') + try { + deviceManager.createDeviceManager(BUNDLE, (error, value) => { + if (error) { + Logger.error(TAG, 'createDeviceManager failed.') + return + } + this.deviceManager = value + this.registerDeviceListCallbackImplement(stateChangeCallback) + Logger.info(TAG, `createDeviceManager callback returned,value=${value}`) + }) + } catch (error) { + Logger.error(TAG, `createDeviceManager throw error, code=${error.code} message=${error.message}`) + } + + Logger.info(TAG, 'deviceManager.createDeviceManager end') + } + registerDeviceListCallbackImplement(stateChangeCallback: () => void) { + Logger.info(TAG, 'registerDeviceListCallback') + this.stateChangeCallback = stateChangeCallback + if (this.deviceManager === undefined) { + Logger.error(TAG, 'deviceManager has not initialized') + this.stateChangeCallback() + return + } + Logger.info(TAG, 'getTrustedDeviceListSync begin') + try { + let list = this.deviceManager.getTrustedDeviceListSync()//同步获取所有可信设备列表 + Logger.info(TAG, `getTrustedDeviceListSync end, devices=${JSON.stringify(list)}`) + if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') { + this.devices = list + } + } catch (error) { + Logger.error(TAG, `getLocalDeviceInfoSync throw error, code=${error.code} message=${error.message}`) + } + this.stateChangeCallback() + Logger.info(TAG, 'callback finished') + try { + this.deviceManager.on('deviceStateChange', (data) => { + if (data === null) { + return + } + Logger.info(TAG, `deviceStateChange data = ${JSON.stringify(data)}`) + switch (data.action) { + case deviceManager.DeviceStateChangeAction.READY://即设备处于可用状态,表示设备间信息已在分布式数据中同步完成, 可以运行分布式业务 + this.discoverDevices = [] + this.devices.push(data.device) + this.stateChangeCallback() + try { + let list = this.deviceManager.getTrustedDeviceListSync() + if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') { + this.devices = list + } + } catch (error) { + Logger.error(TAG, `getTrustedDeviceListSync throw error, code=${error.code} message=${error.message}`) + } + this.stateChangeCallback() + break + default: + break + } + }) + this.deviceManager.on('deviceFound', (data) => { + if (data === null) { + return + } + Logger.info(TAG, `deviceFound data=${JSON.stringify(data)}`) + this.onDeviceFound(data) + }) + this.deviceManager.on('discoverFail', (data) => { + Logger.info(TAG, `discoverFail data=${JSON.stringify(data)}`) + }) + this.deviceManager.on('serviceDie', () => { + Logger.info(TAG, 'serviceDie') + }) + } catch (error) { + Logger.error(TAG, `on throw error, code=${error.code} message=${error.message}`) + } + this.startDeviceDiscovery() + } + startDeviceDiscovery() { + SUBSCRIBE_ID = Math.floor(65536 * Math.random()) + var info = { + subscribeId: SUBSCRIBE_ID, + mode: 0xAA, + medium: 2, + freq: 2,//高频率 + isSameAccount: false, + isWakeRemote: true, + capability: 0 + } + Logger.info(TAG, `startDeviceDiscovery${SUBSCRIBE_ID}`) + try { + this.deviceManager.startDeviceDiscovery(info)//开始发现周边设备 + } catch (error) { + Logger.error(TAG, `startDeviceDiscovery throw error, code=${error.code} message=${error.message}`) + } + + } + ``` + +4. 实现同步编辑 + + 通过AppStorage设置持久性数据,然后实现IDataSource接口,通过注册数据监听接口监听数据的变化。 + + ```typescript + class BasicDataSource implements IDataSource { + private listeners: DataChangeListener[] = [] + + public totalCount(): number { + return 0 + } + + public getData(index: number): any { + return undefined + } + + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + console.info('add listener') + this.listeners.push(listener) + } + } + + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { + console.info('remove listener') + this.listeners.splice(pos, 1) + } + } + //数据准备好了 + notifyDataReload(): void { + this.listeners.forEach(listener => { + listener.onDataReloaded() + }) + } + ... + } + + onPageShow() { + //每当完成编辑或者新建文件,就会回到主页,此时就会执行onPageShow() + //noteDataSource获取globalObject保存的分布式的持久性数据,并进行Reload操作传递。 + this.noteDataSource['dataArray'] = this.globalObject.distributedObject.documents + this.noteDataSource.notifyDataReload() + Logger.info(TAG, `this.sessionId = ${this.sessionId}`) + Logger.info(TAG, `globalSessionId = ${this.globalSessionId}`) + if (this.sessionId !== this.globalSessionId) { + this.sessionId = this.globalSessionId + this.share() + } + } + share() { + //多个设备间的对象如果设置为同一个sessionId的笔记数据自动同步 + Logger.info(TAG, `sessionId = ${this.sessionId}`) + this.globalObject.setChangeCallback(() => { + this.noteDataSource['dataArray'] = this.globalObject.distributedObject.documents + this.noteDataSource.notifyDataReload() + }) + this.globalObject.setStatusCallback((session, networkId, status) => { + Logger.info(TAG, `StatusCallback,${status}`) + if (status === 'online') { + this.isOnline = true + } else { + this.isOnline = false + } + }) + this.globalObject.distributedObject.setSessionId(this.sessionId) + AppStorage.SetOrCreate('objectModel', this.globalObject) + } + ``` + +## 全部代码 + +本例完整代码sample示例链接:[分布式对象](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedNote) + +## 参考 + +- [权限列表](../application-dev/security/permission-list.md#ohospermissiondistributed_datasync) +- [分布式数据对象](../application-dev/reference/apis/js-apis-data-distributedobject.md) diff --git a/zh-cn/third-party-cases/figures/bluetooth_delete.png b/zh-cn/third-party-cases/figures/bluetooth_delete.png new file mode 100644 index 0000000000000000000000000000000000000000..60e73b525e27c0eb73e3f437e749bc96eff16943 Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_delete.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_delete_en.png b/zh-cn/third-party-cases/figures/bluetooth_delete_en.png new file mode 100644 index 0000000000000000000000000000000000000000..e9b040c7cd39ba4162feb5f4da81dbc0e64af474 Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_delete_en.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_dialog.png b/zh-cn/third-party-cases/figures/bluetooth_dialog.png new file mode 100644 index 0000000000000000000000000000000000000000..38ab4a29a780b6baba25d353a170c0f74743b668 Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_dialog.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_dialog_en.png b/zh-cn/third-party-cases/figures/bluetooth_dialog_en.png new file mode 100644 index 0000000000000000000000000000000000000000..63857c729802e00d4c3cc65ac236aa2ff34ce607 Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_dialog_en.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_list.png b/zh-cn/third-party-cases/figures/bluetooth_list.png new file mode 100644 index 0000000000000000000000000000000000000000..6edbda56e6cf01a45d055f995169ccf6e9463cbb Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_list.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_list_en.png b/zh-cn/third-party-cases/figures/bluetooth_list_en.png new file mode 100644 index 0000000000000000000000000000000000000000..4df05c5c4aee9216e0a0b5d2c0d7164fb18949be Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_list_en.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_match.png b/zh-cn/third-party-cases/figures/bluetooth_match.png new file mode 100644 index 0000000000000000000000000000000000000000..1daa1043afbdc2648c73675aba365722dc3df2b1 Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_match.png differ diff --git a/zh-cn/third-party-cases/figures/bluetooth_match_en.png b/zh-cn/third-party-cases/figures/bluetooth_match_en.png new file mode 100644 index 0000000000000000000000000000000000000000..4cb0101c6dd18298dbd1f94c4c56af4bc6c5da12 Binary files /dev/null and b/zh-cn/third-party-cases/figures/bluetooth_match_en.png differ diff --git a/zh-cn/third-party-cases/figures/camera.png b/zh-cn/third-party-cases/figures/camera.png new file mode 100644 index 0000000000000000000000000000000000000000..245a0585d523889ba1f4411a1593176160ff80be Binary files /dev/null and b/zh-cn/third-party-cases/figures/camera.png differ diff --git a/zh-cn/third-party-cases/figures/camerapreview.gif b/zh-cn/third-party-cases/figures/camerapreview.gif new file mode 100644 index 0000000000000000000000000000000000000000..1e1f06dac46a9386f941d4701e5143fd0388ab1c Binary files /dev/null and b/zh-cn/third-party-cases/figures/camerapreview.gif differ diff --git a/zh-cn/third-party-cases/figures/connect.png b/zh-cn/third-party-cases/figures/connect.png new file mode 100644 index 0000000000000000000000000000000000000000..18be004d104f1672e42af11186eecc7586333a41 Binary files /dev/null and b/zh-cn/third-party-cases/figures/connect.png differ diff --git a/zh-cn/third-party-cases/figures/crash_1.png b/zh-cn/third-party-cases/figures/crash_1.png new file mode 100644 index 0000000000000000000000000000000000000000..35bf5af9d40e890796b95c8f5f44a3c2b7fb53b6 Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_1.png differ diff --git a/zh-cn/third-party-cases/figures/crash_2.png b/zh-cn/third-party-cases/figures/crash_2.png new file mode 100644 index 0000000000000000000000000000000000000000..a45f034cbb545b3c63db6962ce509fa018343c64 Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_2.png differ diff --git a/zh-cn/third-party-cases/figures/crash_3.png b/zh-cn/third-party-cases/figures/crash_3.png new file mode 100644 index 0000000000000000000000000000000000000000..5d3060410c0becbf3164a3a8820503933c9e5abc Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_3.png differ diff --git a/zh-cn/third-party-cases/figures/crash_4.png b/zh-cn/third-party-cases/figures/crash_4.png new file mode 100644 index 0000000000000000000000000000000000000000..1c1f87ceeaaaafd7a2b43a3ac291b06c6cc15500 Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_4.png differ diff --git a/zh-cn/third-party-cases/figures/crash_5.png b/zh-cn/third-party-cases/figures/crash_5.png new file mode 100644 index 0000000000000000000000000000000000000000..0eaf71d314ebe3f4151ae81867da33b568bea2e3 Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_5.png differ diff --git a/zh-cn/third-party-cases/figures/crash_6.png b/zh-cn/third-party-cases/figures/crash_6.png new file mode 100644 index 0000000000000000000000000000000000000000..d91d3277be2c3d1d022b2f1520dd7bd24f8f2a02 Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_6.png differ diff --git a/zh-cn/third-party-cases/figures/crash_7.png b/zh-cn/third-party-cases/figures/crash_7.png new file mode 100644 index 0000000000000000000000000000000000000000..ecd7c3a6a01f0f1b799d8b28a510bbf8514e795c Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_7.png differ diff --git a/zh-cn/third-party-cases/figures/crash_8.png b/zh-cn/third-party-cases/figures/crash_8.png new file mode 100644 index 0000000000000000000000000000000000000000..c0721d5826f914922b812a5ecff6fe0c02cb46d4 Binary files /dev/null and b/zh-cn/third-party-cases/figures/crash_8.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_canvas-after.png b/zh-cn/third-party-cases/figures/disributed_canvas-after.png new file mode 100644 index 0000000000000000000000000000000000000000..7bc98d9f9f596af7150c173f9577a30f1f5ee1ff Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_canvas-after.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_canvas-before.png b/zh-cn/third-party-cases/figures/disributed_canvas-before.png new file mode 100644 index 0000000000000000000000000000000000000000..e6a17222c21405ee2a191946af81c5429fa821e7 Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_canvas-before.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_canvas_connect.png b/zh-cn/third-party-cases/figures/disributed_canvas_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..249fae29cd541d0bae0150448eed500d70fdaf06 Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_canvas_connect.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_note-after.png b/zh-cn/third-party-cases/figures/disributed_note-after.png new file mode 100644 index 0000000000000000000000000000000000000000..9eef39c0351577a06a15be085bca058051bc8012 Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_note-after.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_note-before.png b/zh-cn/third-party-cases/figures/disributed_note-before.png new file mode 100644 index 0000000000000000000000000000000000000000..5b863b7a491a6a3671815637c90b13830043cc7e Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_note-before.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_note-edit.png b/zh-cn/third-party-cases/figures/disributed_note-edit.png new file mode 100644 index 0000000000000000000000000000000000000000..585a7084b4a95f63a08aaa2ac8a1a783c4727602 Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_note-edit.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_note_connect.png b/zh-cn/third-party-cases/figures/disributed_note_connect.png new file mode 100644 index 0000000000000000000000000000000000000000..a983cf00ca81f7280c84bb1e05d03494a5b76df4 Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_note_connect.png differ diff --git a/zh-cn/third-party-cases/figures/disributed_permission.png b/zh-cn/third-party-cases/figures/disributed_permission.png new file mode 100644 index 0000000000000000000000000000000000000000..8d86371911f97124694b2555b1dd6eee975a9147 Binary files /dev/null and b/zh-cn/third-party-cases/figures/disributed_permission.png differ diff --git a/zh-cn/third-party-cases/figures/distributed.png b/zh-cn/third-party-cases/figures/distributed.png new file mode 100644 index 0000000000000000000000000000000000000000..b0fb2e9bc8958a06521bf2befe5377f4a195776b Binary files /dev/null and b/zh-cn/third-party-cases/figures/distributed.png differ diff --git a/zh-cn/third-party-cases/figures/jserror_1.png b/zh-cn/third-party-cases/figures/jserror_1.png new file mode 100644 index 0000000000000000000000000000000000000000..ad3987092bf60e16b5f9bbf7c60333cacdc0da8e Binary files /dev/null and b/zh-cn/third-party-cases/figures/jserror_1.png differ diff --git a/zh-cn/third-party-cases/figures/jserror_2.png b/zh-cn/third-party-cases/figures/jserror_2.png new file mode 100644 index 0000000000000000000000000000000000000000..43561e6ceb2b11cf5f1ca62d67e5b4b185d7ae72 Binary files /dev/null and b/zh-cn/third-party-cases/figures/jserror_2.png differ diff --git a/zh-cn/third-party-cases/figures/jserror_3.png b/zh-cn/third-party-cases/figures/jserror_3.png new file mode 100644 index 0000000000000000000000000000000000000000..f8e57ddd5d39f4c9cbd817dcc7b67f60f2993c27 Binary files /dev/null and b/zh-cn/third-party-cases/figures/jserror_3.png differ diff --git a/zh-cn/third-party-cases/figures/jserror_4.png b/zh-cn/third-party-cases/figures/jserror_4.png new file mode 100644 index 0000000000000000000000000000000000000000..e7535b656f7dcff1903be544ce65934051619687 Binary files /dev/null and b/zh-cn/third-party-cases/figures/jserror_4.png differ diff --git a/zh-cn/third-party-cases/figures/wlanconnect.png b/zh-cn/third-party-cases/figures/wlanconnect.png new file mode 100644 index 0000000000000000000000000000000000000000..7e1a604a564ad61652d907311a68dc15ecbf0e29 Binary files /dev/null and b/zh-cn/third-party-cases/figures/wlanconnect.png differ diff --git a/zh-cn/third-party-cases/figures/wlandisconnect.png b/zh-cn/third-party-cases/figures/wlandisconnect.png new file mode 100644 index 0000000000000000000000000000000000000000..5050ec683cd16c0fc8a224924584f1facccf2906 Binary files /dev/null and b/zh-cn/third-party-cases/figures/wlandisconnect.png differ diff --git a/zh-cn/third-party-cases/figures/wlanmain.png b/zh-cn/third-party-cases/figures/wlanmain.png new file mode 100644 index 0000000000000000000000000000000000000000..c8454fc71d01b013dbb68c0579773d12278782a6 Binary files /dev/null and b/zh-cn/third-party-cases/figures/wlanmain.png differ diff --git a/zh-cn/third-party-cases/figures/wlanscan.png b/zh-cn/third-party-cases/figures/wlanscan.png new file mode 100644 index 0000000000000000000000000000000000000000..366799135770c2bb5fa3d93f67b251f304d42641 Binary files /dev/null and b/zh-cn/third-party-cases/figures/wlanscan.png differ diff --git a/zh-cn/third-party-cases/how-to-connect-to-bluetooth.md b/zh-cn/third-party-cases/how-to-connect-to-bluetooth.md new file mode 100644 index 0000000000000000000000000000000000000000..45b22ac7716edab37e44b46b6ed54cc39b7e7fd6 --- /dev/null +++ b/zh-cn/third-party-cases/how-to-connect-to-bluetooth.md @@ -0,0 +1,413 @@ +# 如何进行蓝牙连接 + +## 场景说明 +蓝牙技术是一种无线数据和语音通信开放的全球规范,它是基于低成本的近距离无线连接,为固定和移动设备建立通信环境的一种特殊的连接。本示例通过[@ohos.bluetoothManager](../application-dev/reference/apis/js-apis-bluetoothManager.md)接口实现蓝牙设备发现、配对、取消配对功能。 + +## 效果呈现 + +本示例最终效果如下: + +| 发现设备 | 连接设备 | 断开连接 | +| ------------------------------- | --------------------------------- | --------------------------------- | +| ![](figures/bluetooth_list.png) | ![](figures/bluetooth_dialog.png) | ![](figures/bluetooth_delete.png) | + +## 运行环境 + +本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。 + +- IDE:DevEco Studio 3.1.1 Release +- SDK:Ohos_sdk_full 4.0.8.5(API Version 10 Beta1) + +## 实现思路 +本文涉及到蓝牙的设备发现、配对、取消配对三个功能特性,实现思路如下: + +- 启动和关闭蓝牙:在Index页面中通过Toggle组件的onChange函数控制蓝牙的开关,开关打开的情况下执行initBluetooth函数,关闭的情况下执行bluetooth.disableBluetooth()方法来断开蓝牙; +- 验证蓝牙是否处于连接状态:蓝牙打开的时候通过bluetooth.on('stateChange')方法监听蓝牙连接状态改变事件,如确认已打开,执行foundDevices()函数来查找设备接口,确认已关闭则执行bluetooth.stopBluetoothDiscovery()方法停止查询接口。 +- 发现设备:在foundDevices()函数中通过bluetooth.on('bluetoothDeviceFind')方法监听设备发现事件,通过bluetooth.getPairedDevices()方法更新已配对蓝牙地址,然后通过bluetooth.startBluetoothDiscovery()方法开启蓝牙扫描发现远端设备,并且通过bluetooth.setBluetoothScanMode()方法来被远端设备发现。 +- 蓝牙配对:通过bluetooth.on('pinRequired')方法监听远端蓝牙设备的配对请求事件,点击配对执行bluetooth.setDevicePairingConfirmation(this.data.deviceId, true)方法,点击取消执行bluetooth.setDevicePairingConfirmation(this.data.deviceId, false)方法。 +- 取消配对:使用bluetooth.cancelPairedDevice()断开指定的远端设备连接。 + +## 开发步骤 +1. 申请蓝牙权限。 + 使用蓝牙需要先申请对应的权限,在module.json5文件中添加以下配置: + + ```json + "requestPermissions": [ + { + //允许应用查看蓝牙的配置 + "name": "ohos.permission.USE_BLUETOOTH", + "reason": "$string:grant_use_bluetooth", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + }, + { + //允许应用配置本地蓝牙,查找远端设备且与之配对连接 + "name": "ohos.permission.DISCOVER_BLUETOOTH", + "reason": "$string:grant_discovery_bluetooth", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + }, + { + //允许应用获取设备位置信息 + "name": "ohos.permission.LOCATION", + "reason": "$string:grant_location", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + }, + { + //允许应用获取设备模糊位置信息 + "name": "ohos.permission.APPROXIMATELY_LOCATION", + "reason": "$string:grant_location", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + }, + { + //允许应用配对蓝牙设备,并对设备的电话簿或消息进行访问 + "name": "ohos.permission.MANAGE_BLUETOOTH", + "reason": "$string:grant_manage_bluetooth", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "inuse" + } + } + ] + ``` + +2. 构建UI框架,整体的UI框架分为TitleBar(页面名称),PinDialog(配对蓝牙弹框),index(主页面)三个部分。 + + ```ts + //Common/TitleBar.ets + @Component + export struct TitleBar { + private handlerClickButton: () => void + + build() { + Row() { + Image($r('app.media.ic_back')) + .width(40) + .height(30) + .onClick(() => { + this.handlerClickButton() + }) + Text($r('app.string.bluetooth')) + .fontSize(30) + .width(150) + .height(50) + .margin({ left: 15 }) + .fontColor('#ffa2a3a4') + } + .width('100%') + .height(60) + .padding({ left: 20, top: 10 }) + .backgroundColor('#ff2d30cb') + .constraintSize({ minHeight: 50 }) + } + } + + //Common/PinDalog.ets + ... + aboutToAppear() { + this.titleText = `"${this.data.deviceId}"要与您配对。请确认此配对码已在"${this.data.deviceId}"上直接显示,且不是手动输入的。` + this.pinCode = JSON.stringify(this.data.pinCode) + } + build() { + //配对弹框描述文字 + Column({ space: 10 }) { + Text($r('app.string.match_request')) + .fontSize(30) + .alignSelf(ItemAlign.Start) + Text(this.titleText) + .alignSelf(ItemAlign.Start) + .margin({ top: 20 }) + .fontSize(21) + Text(this.pinCode) + .fontSize(40) + .fontWeight(FontWeight.Bold) + .margin({ top: 20 }) + Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox' }) + .select(false) + .selectedColor('#ff3d6fb8') + .key('checkBox') + Text($r('app.string.grant_permission')) + .fontSize(15) + .margin({ left: 3, top: 6 }) + } + .alignSelf(ItemAlign.Start) + .width('95%') + .margin({ top: 5 }) + + Row() { + //配对选择UI,取消or配对 + this.choiceText($r('app.string.cancel'), () => { + bluetooth.setDevicePairingConfirmation(this.data.deviceId, false) + logger.info(TAG, `setDevicePairingConfirmation = ${bluetooth.setDevicePairingConfirmation(this.data.deviceId, false)}`) + this.controller.close() + }) + + Divider() + .vertical(true) + .height(32) + + this.choiceText($r('app.string.match'), () => { + bluetooth.setDevicePairingConfirmation(this.data.deviceId, true) + logger.info(TAG, `setDevicePairingConfirmation = ${bluetooth.setDevicePairingConfirmation(this.data.deviceId, true)}`) + this.controller.close() + }) + } + .margin({ top: 20 }) + } + .width('100%') + .padding(15) + } + ... + + //pages/index.ets + @Entry + @Component + struct Index { + build() { + Column() { + TitleBar({ handlerClickButton: this.handlerClickButton }) + Scroll() { + Column() { + Row() { + //蓝牙开关 + Column() { + Text($r('app.string.bluetooth')) + .fontSize(30) + .margin({ top: 20 }) + .alignSelf(ItemAlign.Start) + if (true === this.isOn) { + Text($r('app.string.discovery')) + .fontSize(20) + .alignSelf(ItemAlign.Start) + } + } + + Blank() + + Column() { + Toggle({ type: ToggleType.Switch, isOn: this.isOn }) + .selectedColor('#ff2982ea') + .onChange((isOn: boolean) => { + if (isOn) { + this.isOn = true + this.initBluetooth() + } else { + this.isOn = false + bluetooth.disableBluetooth() + this.deviceList = [] + this.discoveryList = [] + } + }) + } + .id('toggleBtn') + } + .width('90%') + + if (this.isOn) { + Divider() + .vertical(false) + .strokeWidth(10) + .color('#ffece7e7') + .lineCap(LineCapStyle.Butt) + .margin('1%') + //已配对的设备 + Text($r('app.string.paired_device')) + .fontSize(25) + .fontColor('#ff565555') + .margin({ left: '5%' }) + .alignSelf(ItemAlign.Start) + + ForEach(this.deviceList, (item, index) => { + Row() { + Text(item) + .fontSize(20) + } + .alignSelf(ItemAlign.Start) + .width('100%') + .height(50) + .margin({ left: '5%', top: '1%' }) + .id(`pairedDevice${index}`) + .onClick(() => { + AlertDialog.show({ + //取消配对 + title: $r('app.string.disconnect'), + message: '此操作将会断开您与以下设备的连接:' + item, + primaryButton: { + value: $r('app.string.cancel'), + action: () => { + } + }, + //确认取消 + secondaryButton: { + value: $r('app.string.confirm'), + action: () => { + try { + bluetooth.cancelPairedDevice(item); + this.deviceList = bluetooth.getPairedDevices() + this.discoveryList = [] + bluetooth.startBluetoothDiscovery() + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + } + } + }) + }) + }) + + Divider() + .vertical(false) + .strokeWidth(10) + .color('#ffece7e7') + .lineCap(LineCapStyle.Butt) + .margin('1%') + + Text($r('app.string.available_device')) + .fontSize(25) + .fontColor('#ff565555') + .margin({ left: '5%', bottom: '2%' }) + .alignSelf(ItemAlign.Start) + //可用设备列表 + ForEach(this.discoveryList, (item) => { + Row() { + Text(item) + .fontSize(20) + } + .alignSelf(ItemAlign.Start) + .width('100%') + .height(50) + .margin({ left: '5%', top: '1%' }) + //进行配对操作点击 + .onClick(() => { + logger.info(TAG, `start bluetooth.pairDevice,item = ${item}`) + let pairStatus = bluetooth.pairDevice(item) + logger.info(TAG, `pairStatus = ${pairStatus}`) + }) + + Divider() + .vertical(false) + .color('#ffece7e7') + .lineCap(LineCapStyle.Butt) + .margin('1%') + }) + } + } + } + .constraintSize({ maxHeight: '85%' }) + } + } + } + ``` + +3. 蓝牙开关打开关闭操作,需要打开蓝牙开关才能进行后续操作: + ```ts + initBluetooth() { + bluetooth.on('stateChange', (data) => { + logger.info(TAG, `enter on stateChange`) + //判断蓝牙开关状态 + if (data === bluetooth.BluetoothState.STATE_ON) { + logger.info(TAG, `enter BluetoothState.STATE_ON`) + //蓝牙打开后的相关操作 + this.foundDevices() + } + if (data === bluetooth.BluetoothState.STATE_OFF) { + logger.info(TAG, `enter BluetoothState.STATE_OFF`) + bluetooth.off('bluetoothDeviceFind', (data) => { + logger.info(TAG, `offBluetoothDeviceFindData = ${JSON.stringify(data)}`) + }) + //关闭 + bluetooth.stopBluetoothDiscovery() + this.discoveryList = [] + } + logger.info(TAG, `BluetoothState = ${JSON.stringify(data)}`) + }) + //开启蓝牙 + bluetooth.enableBluetooth() + } + ``` + +4. 设置蓝牙扫描模式并开启扫描去发现设备,并订阅蓝牙设备发现上报时间获取设备列表 + ```ts + foundDevices() { + //订阅蓝牙设备发现上报事件 + bluetooth.on('bluetoothDeviceFind', (data) => { + logger.info(TAG, `enter on bluetoothDeviceFind`) + if (data !== null && data.length > 0) { + if (this.discoveryList.indexOf(data[0]) === -1 && this.deviceList.indexOf(data[0]) === -1) { + this.discoveryList.push(data[0]) + } + logger.info(TAG, `discoveryList = ${JSON.stringify(this.discoveryList)}`) + } + let list = bluetooth.getPairedDevices() + if (list !== null && list.length > 0) { + this.deviceList = list + logger.info(TAG, `deviceList = ${JSON.stringify(this.deviceList)}`) + } + }) + //开启蓝牙扫描,可以发现远端设备 + bluetooth.startBluetoothDiscovery() + //设置蓝牙扫描模式,可以被远端设备发现 + bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, TIME) + } + ``` + +5. 设置蓝牙扫描模式并开启扫描去发现设备,并订阅蓝牙设备发现上报时间获取设备列表 + + ```ts + //配对确定和取消代码在PinDialog.ets文件中 + //setDevicePairingConfirmation(device: string, accept: boolean): void + //device string 表示远端设备地址,例如:"XX:XX:XX:XX:XX:XX + //accept boolean 接受配对请求设置为true,否则设置为false + + //订阅蓝牙配对状态改变事件,根据蓝牙状态更新设备列表 + bluetooth.on('bondStateChange', (data) => { + logger.info(TAG, `enter bondStateChange`) + logger.info(TAG, `data = ${JSON.stringify(data)}`) + if (data.state === bluetooth.BondState.BOND_STATE_BONDED) { + logger.info(TAG, `BOND_STATE_BONDED`) + let index = this.discoveryList.indexOf(data.deviceId) + this.discoveryList.splice(index, 1) + this.deviceList = bluetooth.getPairedDevices() + } + if (data.state === bluetooth.BondState.BOND_STATE_INVALID) { + logger.info(TAG, `BOND_STATE_INVALID`) + this.deviceList = bluetooth.getPairedDevices() + } + logger.info(TAG, `bondStateChange,data = ${JSON.stringify(data)}`) + }) + ``` + +​ + +## 完整代码 + +本例完整代码sample示例链接:[蓝牙Sample](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Connectivity/Bluetooth) + + + +## 参考 +- [权限申请指导](../application-dev/security/accesstoken-guidelines.md) +- [@ohos.bluetooth](../application-dev/reference/apis/js-apis-bluetooth.md) + +​ \ No newline at end of file diff --git a/zh-cn/third-party-cases/property-animation.md b/zh-cn/third-party-cases/property-animation.md index bc487097c9d5fb8a13273b9d39369ecd0458c2c1..8d6a28f9053e90f04d5853f98aebb312b57c127f 100644 --- a/zh-cn/third-party-cases/property-animation.md +++ b/zh-cn/third-party-cases/property-animation.md @@ -507,7 +507,7 @@ struct Index { [Curve](../application-dev/reference/arkui-ts/ts-appendix-enums.md#curve) -[弹簧曲线动画](../application-dev/ui/arkts-spring-animation.md) +[弹簧曲线动画](../application-dev/ui/arkts-spring-curve.md) [Flex布局](../application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md) diff --git a/zh-cn/third-party-cases/take-picture-and-preview.md b/zh-cn/third-party-cases/take-picture-and-preview.md new file mode 100644 index 0000000000000000000000000000000000000000..f45e3fee25151ba9b519beb56fac2f5087ee4e2f --- /dev/null +++ b/zh-cn/third-party-cases/take-picture-and-preview.md @@ -0,0 +1,257 @@ +# 如何调用设备摄像头进行拍照、预览并将拍摄结果保存在媒体库中 + +## 场景说明 + +调用设备摄像头进行拍照、预览是许多应用开发过程中都需要的功能。在拍照完成时显示照片预览图可以确认拍摄的照片是否达到预期,本例将为大家介绍如何实现上述功能。 + +## 效果呈现 + +本例效果如下: + +| 拍照 | 预览 | +| :----------------------------------------------------------: | :----------------------------------------------------------: | +| contactlist | contactlist | + + + +## 运行环境 + +本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。 + +- IDE:DevEco Studio 4.0.0.201 Beta1 +- SDK:Ohos_sdk_public 4.0.7.5 (API Version 10 Beta1) + +## 实现思路 + +本例使用@ohos.multimedia.camera接口实现相机示例的主要功能:拍照、预览; + +- 拍照:XComponent组件负责绘制摄像头画面呈现的窗口,其onload事件调用cameraModel.ts的initCamera方法初始化相机功能输出画面信息。拍照动作使用Image组件实现,其onclick事件调用cameraModel.ts的takepicture方法开始拍照。 + +- 预览:返回相机界面点击底部左侧预览图可进入相册应用,可以在其中查看照片和录制的视频。 + +## 开发步骤 + +1. 申请所需权限 + + 在model.json5中添加以下配置: + + ```json + "requestPermissions": [ + { + "name": "ohos.permission.CAMERA"//允许应用使用相机拍摄照片和录制视频 + }, + { + "name": "ohos.permission.MICROPHONE"//允许应用使用麦克风 + }, + { + "name": "ohos.permission.MEDIA_LOCATION"//允许应用访问用户媒体文件中的地理位置信息 + }, + { + "name": "ohos.permission.WRITE_MEDIA"//允许应用读写用户外部存储中的媒体文件信息 + }, + { + "name": "ohos.permission.READ_MEDIA"//允许应用读取用户外部存储中的媒体文件信息 + } + ] + ``` + +2. 创建绘制组件XComponent以输出摄像头获取的画面,其绑定的onload方法中设定了画幅的大小。 + + ```typescript + build() { + Column() { + Title() + .visibility(this.isTitleShow ? Visibility.Visible : Visibility.None) + Stack({ alignContent: Alignment.Bottom }) { + Stack({ alignContent: Alignment.TopStart }) { + XComponent({ + id: 'componentId', + type: 'surface', + controller: this.mXComponentController //将控制器绑定至XComponent组件 + }) + .onLoad(() => { + this.mXComponentController.setXComponentSurfaceSize({ surfaceWidth: 640, surfaceHeight: 480 });//设置surface大小 + this.surfaceId = this.mXComponentController.getXComponentSurfaceId(); + this.currentModel = CameraMode.modePhoto; + this.cameraModel.initCamera(this.surfaceId); //调用model/cameraModel.ts初始化相机功能 + }) + .width('100%') + .height('100%') + .margin({ bottom: 152 }) + Column() { + } + .width('97%') + .height('100%') + ``` + +3. 初始化相机功能 + + initCamera方法通过创建相机管理器实例cameraMgr来创建画面输出对象previewOutput。cameraMgr再通过创建CaptureSession实例来配置会话,完成相机功能的准备工作。 + + ```typescript + import image from '@ohos.multimedia.image';//自@ohos.multimedia.image引入image,提供图片处理效果 + ... + private receiver: image.ImageReceiver = undefined;//图像接收类,用于获取组件surface id,接收最新的图片和读取下一张图片 + ... + constructor() { + this.mediaModel = MediaModel.getMediaInstance();//通过调用model/MediaModel.ets中的方法创建mediaInstance类mediaModel + //创建ImageReceiver实例receiver + this.receiver = image.createImageReceiver( + cameraWH.width, + cameraWH.height, + FOUR, + EIGHT + ); + //接收图片时注册回调 + this.receiver.on('imageArrival', () => { + //从ImageReceiver读取下一张图片 + this.receiver.readNextImage((err, image) => { + if (err || image === undefined) { + return; + } + //根据图像的组件类型从图像中获取组件缓存 + image.getComponent(FOUR, (errMsg, img) => { + if (errMsg || img === undefined) { + return; + } + let buffer = new ArrayBuffer(FOUR_THOUSAND_AND_SIXTY_NINE); + if (img.byteBuffer) { + buffer = img.byteBuffer; + } + this.saveImage(buffer, image); + }); + }); + }); + } + + + async initCamera(surfaceId: string): Promise { + ... + try { + this.cameraMgr = camera.getCameraManager(globalThis.cameraContext);//获取相机管理器实例 + } + this.camerasArray = this.cameraMgr.getSupportedCameras();//获取支持指定的相机设备对象 + if (this.camerasArray.length === 0) { + return; + } + let mCamera = this.camerasArray[0]; + this.cameraInput = this.cameraMgr.createCameraInput(mCamera); + this.cameraInput.open(); + this.capability = this.cameraMgr.getSupportedOutputCapability(mCamera);//查询相机设备支持的输出能力 + let previewProfile = this.capability.previewProfiles[0]; + //通过相机管理器创建预览输出对象 + this.previewOutput = this.cameraMgr.createPreviewOutput( + previewProfile, + surfaceId //surfaceId从XComponent组件获取 + ); + let rSurfaceId = await this.receiver.getReceivingSurfaceId();//获取一个surface id供其他组件使用 + let photoProfile = this.capability.photoProfiles[0]; + //通过相机管理器创建照片输出对象 + this.photoOutPut = this.cameraMgr.createPhotoOutput( + photoProfile, + rSurfaceId //rSurfaceId通过构造函数中定义的图像接收类receiver获取 + ); + this.capSession = this.cameraMgr.createCaptureSession();//创建CaptureSession实例 + this.capSession.beginConfig();//开始配置会话 + this.capSession.addInput(this.cameraInput);//将cameraInput加入会话 + this.capSession.addOutput(this.previewOutput);//将预览输出加入会话 + this.capSession.addOutput(this.photoOutPut);//将照片输出加入会话 + await this.capSession.commitConfig();//提交配置信息 + await this.capSession.start();//开始输出 + } + + ``` + +4. 点击按钮进行拍照 + + 拍照按钮通过Image组件呈现,其绑定的onClick方法调用takePicture方法开始拍照。 + + ```typescript + Image(this.getCameraIcon()) + .size({ width: 64, height: 64 }) + .margin({ left: 10 }) + .id('camera') + .onClick(() => { + if (this.currentModel === CameraMode.modePhoto) { + prompt.showToast({ message: '拍照中...', duration: 200 }); + this.cameraModel.takePicture();//调用model/cameraModel.takePicture()开始拍照 + } + }) + ``` + +5. 拍照功能具体实现 + + - 拍照 + + ```typescript + async takePicture(): Promise { + //设置拍照相关参数 + let photoSettings = { + rotation: this.imageRotation, + quality: camera.QualityLevel.QUALITY_LEVEL_MEDIUM, + location: { + // 位置信息,经纬度 + latitude: 12.9698, + longitude: 77.75, + altitude: 1000, + }, + mirror: false, + }; + await this.photoOutPut.capture(photoSettings); + AppStorage.Set('isRefresh', true); + } + ``` + + - 保存图片 + + saveImage方法使用MediaModel中的createAndGetUri方法创建Image类型资源,将拍摄到的照片写入到这个资源中去。 + + ```typescript + //model/MediaModel.ts中定义的负责保存图片的相关方法 + async createAndGetUri(mediaType: mediaLibrary.MediaType): Promise { + let dateTimeUtil: DateTimeUtil = new DateTimeUtil(); + let info: FileInfo = this.getInfoFromMediaType(mediaType); + let name: string = `${dateTimeUtil.getDate()}_${dateTimeUtil.getTime()}`;//获取当前时间 + let displayName: string = `${info.prefix}${name}${info.suffix}`; + //获取公共目录路径。 + let publicPath: string = await this.mediaLibraryTest.getPublicDirectory( + info.directory + );//通过引用自@ohos.multimedia.mediaLibrary的mediaLibraryTest类创建媒体资源,其中定义了媒体类型、名称、路径。 + let fileAsset: mediaLibrary.FileAsset = await this.mediaLibraryTest.createAsset( + mediaType,//根据传入函数createAndGetUri的mediaType参数决定创建什么类型的媒体资源 + displayName, + publicPath + ); + return fileAsset; + } + async getFdPath(fileAsset: mediaLibrary.FileAsset): Promise { + let fd: number = await fileAsset.open('Rw');//打开当前文件 + return fd; + } + ... + + async saveImage(buffer: ArrayBuffer, img: image.Image): Promise { + this.fileAsset = await this.mediaModel.createAndGetUri(mediaLibrary.MediaType.IMAGE); + //通过调用MediaModel中的方法创建Image类型资源 + this.photoPath = this.fileAsset.uri; + this.fd = await this.mediaModel.getFdPath(this.fileAsset); + await fileIo.write(this.fd, buffer);//将拍摄的照片写入到Mediamodel传回的资源中去 + await this.fileAsset.close(this.fd);//释放open函数 + await img.release(); + if (this.takePictureHandle) { + this.takePictureHandle(this.photoPath); + } + } + ``` + +## 全部代码 + +本例完整代码sample示例链接:[相机](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Media/Camera) + +## 参考 + +- [权限列表](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md#ohospermissiondistributed_datasync) +- [@ohos.multimedia.camera](../application-dev/reference/apis/js-apis-camera.md) + + + diff --git a/zh-cn/third-party-cases/wlan-search-connect-disconnect.md b/zh-cn/third-party-cases/wlan-search-connect-disconnect.md new file mode 100644 index 0000000000000000000000000000000000000000..8439befad413a6c6a9460f9b9eb5e60990935fb2 --- /dev/null +++ b/zh-cn/third-party-cases/wlan-search-connect-disconnect.md @@ -0,0 +1,448 @@ +# 如何实现WLAN网络扫描、连接、断开 + +## 场景说明 + +对可用的WLAN列表进行扫描,连接、断开WLAN网络是设备常见的功能,本例将为大家介绍如何实现上述功能。 + +## 效果呈现 + +本例效果如下: + +| 扫描WLAN | 连接WLAN | 断开WLAN | +| :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| contactlist | contactlist | contactlist | + +## 运行环境 + +本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。 + +- IDE:DevEco Studio 4.0.0.201 Beta1 +- SDK:Ohos_sdk_public 4.0.7.5 (API Version 10 Beta1) + +## 实现思路 + +本例主要通过@ohos.wifiManager 相关API实现WLAN激活和关闭、扫描和连接WLAN等功能。 + +- WLAN功能的激活和关闭:点击首页的切换按钮,如果是打开,使用wifi.enableWifi()开启WLAN功能;如果是关闭,则使用wifi.disconnect()断开WLAN功能, 然后使用wifi.disableWifi()关闭WLAN。 +- WLAN的连接:点击WLAN列表中加密的WLAN,并在弹窗中输入密码后,会在AvailableWifi.ets中通过WifiModule.connectNetwork()调用wifi.connectToDevice()连接WLAN。 +- WLAN的扫描:进入Index.ets 后就会间歇性的调用wifi.scan()开启扫描,然后通过WifiModel模块中的getScanInfos()调用wifi.getScanResults()来获取扫描的结果. + +## 开发步骤 + +1. 申请所需权限 + + 在model.json5中添加以下配置: + + ```json + "requestPermissions": [ + { + "name": "ohos.permission.GET_WIFI_INFO"//允许应用获取WLAN信息 + }, + { + "name": "ohos.permission.GET_WIFI_INFO_INTERNAL"//允许应用获取WLAN信息 + }, + { + "name": "ohos.permission.SET_WIFI_INFO"//允许应用配置WLAN设备 + }, + { + "name": "ohos.permission.GET_WIFI_PEERS_MAC"//允许应用获取对端WLAN或者蓝牙设备的MAC地址 + }, + { + "name": "ohos.permission.GET_WIFI_LOCAL_MAC"//允许应用获取本机WLAN或者蓝牙设备的MAC地址 + }, + { + "name": "ohos.permission.GET_WIFI_CONFIG"//允许应用获取WLAN配置信息 + }, + { + "name": "ohos.permission.SET_WIFI_CONFIG"//允许应用配置WLAN信息 + }, + { + "name": "ohos.permission.MANAGE_WIFI_CONNECTION"//允许应用管理WLAN连接 + }, + { + "name": "ohos.permission.MANAGE_WIFI_HOTSPOT"//允许应用开启或者关闭WLAN热点 + }, + { + "name": "ohos.permission.LOCATION"//允许应用获取设备位置信息 + }, + { + "name": "ohos.permission.APPROXIMATELY_LOCATION"//允许应用获取设备模糊位置信息 + } + ] + ``` + +2. 准备工作 + + 定义boolean变量isSwitchOn作为WLAN开关是否打开的标志。 + + ```typescript + import wifi from '@ohos.wifiManager' + aboutToAppear() { + // 如果WLAN是开的,就记录下状态,然后扫描WLAN,并获取连接信息 + if (wifi.isWifiActive()) {//查询WLAN是否已使能 + Logger.log(TAG, 'wifi is active') + this.isSwitchOn = true//已使能说明WLAN开关已被打开,那么让isSwitchOn为true + wifi.scan()//@ohos.wifiManager的接口,对WLAN进行扫描 + this.scan()//自定义的scan函数,确保扫描的持续性 + this.getLinkedInfo() + } + // 启动监听 + this.addListener()//监听连接状态的变化 + } + ``` + +3. 持续地扫描可用WLAN + + scan方法不断地自我调用以实现对WLAN的不停扫描。 + + ```typescript + async getLinkedInfo() { + try { + //调用getLinkedInfo接口得到是否已连接WLAN的信息 + let wifiLinkedInfo = await wifi.getLinkedInfo() + if (wifiLinkedInfo === null || wifiLinkedInfo.bssid === '') { + //如果结果为空,则说明未连接 + this.isLinked = false + this.linkedInfo = null + return + } + this.isLinked = true + this.linkedInfo = wifiLinkedInfo + } catch (err) { + Logger.info(`getLinkedInfo failed err is ${JSON.stringify(err)}`) + } + } + async scan() { + // 获取有关WLAN连接的信息,存入linkedInfo + await this.getLinkedInfo() + // 不停地扫描WLAN + let result: Array = await this.wifiModel.getScanInfos()//调用model/WifiModel.ets中的getScanInfos得到扫描结果 + if (this.isSwitchOn) { + //如果WLAN功能已打开,则要进行不停地扫描 + AppStorage.SetOrCreate('wifiList', result)//将扫描结果存至全局 + //每3000毫秒调用一次scan(),实现不停扫描可用WLAN + setTimeout(async () => { + await this.scan() + }, 3000) + } + } + addListener() { + // WLAN连接状态改变事件发生时,修改连接信息 + wifi.on('wifiConnectionChange', async state => { + Logger.log(TAG, `wifiConnectionChange: ${state}`) + await this.getLinkedInfo()//WLAN连接状态改变,重新获取WLAN连接信息 + }) + // WLAN状态改变时,先清空WLAN列表,然后判断是否是开启状态,如果是就扫描 + wifi.on('wifiStateChange', state => { + Logger.log(TAG, `wifiStateLisener state: ${state}`) + AppStorage.SetOrCreate('wifiList', []) + if (state === 1) { // 1: wifi is enable, 0:wifi is disable + this.scan() + } + }) + } + ... + //model/WifiModel.ets + async getScanInfos(): Promise> { + Logger.log(TAG, 'scanWifi begin') + let wifiList: Array = [] + let result: Array = [] + try { + result = await wifi.getScanResults()//因为在abouttoappear()中执行了wifi.scan(),所以这里直接调用getScanResults接口得到扫描结果 + } catch (err) { + Logger.log(TAG, `scan info err: ${JSON.stringify(err)}`) + return wifiList + } + Logger.log(TAG, `scan info call back: ${result.length}`) + for (var i = 0; i < result.length; ++i) { + wifiList.push({ + ssid: result[i].ssid, + bssid: result[i].bssid, + securityType: result[i].securityType, + rssi: result[i].rssi, + band: result[i].band, + frequency: result[i].frequency, + timestamp: result[i].timestamp + }) + } + return wifiList + } + ``` + +4. 构建UI框架、通过关闭按钮实现断开WLAN连接。 + + TitleBar组件呈现了标题框。WLAN开关按钮由一个Toggle组件呈现,其绑定的onChange事件在按钮被打开时开始扫描可用WLAN,在被关闭时断开当前连接WLAN并且关闭WLAN功能。当前已连接的WLAN由两个Text组件分别显示其ssid与连接状态。 + + ```typescript + build() { + Column() { + TitleBar()//引入自component/TitleBar.ets,负责标题框的具体呈现 + Row() { + Text($r('app.string.wlan')) + .fontSize(22) + .fontWeight(FontWeight.Bold) + .height(40) + Column() { + Toggle({ type: ToggleType.Switch, isOn: this.isSwitchOn })//切换按钮 + .id('switch') + .onChange((isOn: boolean) => { + Logger.log(`LSQ: wifi swtich is: ${isOn}`) + AppStorage.SetOrCreate('wifiList', []) + try { + // 如果按钮被打开了,记录状态,打开网络,开始扫描可用WLAN + if (isOn) { + this.isSwitchOn = true + wifi.enableWifi()//使WLAN功能可用 + return + } else { + // 如果按钮被关闭了记录状态,断开网络禁用网络 + this.isSwitchOn = false + this.isLinked = false + wifi.disconnect()//断开当前WLAN连接 + wifi.disableWifi()//使WLAN功能不可用 + } + } catch (error) { + Logger.error(TAG, `failed,code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`) + } + }) + } + } + .width('100%') + .padding({ left: 16, right: 16 }) + if (this.isLinked && this.isSwitchOn) { + //如果当前按钮处于打开状态,且WLAN是已连接状态 + Column() { + Text($r('app.string.connected')) + .fontSize(22) + .width('100%') + Row() { + Text(this.linkedInfo.ssid)//展示当前已连接的WLAN + .fontSize(20) + .fontColor(Color.Black) + .layoutWeight(1) + Text($r('app.string.connected')) + .fontSize(18) + .fontColor(Color.Black) + } + .width('100%') + .padding(10) + .margin({ left: 16, right: 16 }) + .border({ radius: 15, color: Color.Gray, width: 1 }) + .backgroundColor(Color.White) + } + .width('100%') + .padding({ left: 16, right: 16 }) + } + if (this.isSwitchOn) { + //如果按钮处于打开状态,展示所有可用WLAN + AvailableWifi({ linkedInfo: this.linkedInfo })//AvailableWifi引入自component/AvailableWifi.ets + } + } + .width('100%') + .height('100%') + .backgroundColor($r('app.color.index_bg')) + } + ``` + +5. 展示可用WLAN列表及WLAN的连接。 + + 使用List组件呈现可用WLAN列表,ListItem由一个呈现WLANssid的Text组件,一个表示其是否被加密的Text组件和一个展示其加密与否图像的Image组件组成。 + + ```typescript + //component/AvailableWifi.ets + build() { + List() { + ListItem() { + Row() { + Text($r('app.string.available_wlan')) + .fontSize(22) + .layoutWeight(1) + } + .id('validWlan') + .width('100%') + } + //通过数据懒加载的方式从数据源中每次迭代一个可用WLAN进行展示,可用列表被放置在滚动容器中,被划出可视区域外的资源会被回收 + LazyForEach(this.wifiDataResource, (item, index) => { + ListItem() { + WifiView({ wifi: item })//WifiView引入自Component/WifiView.ets,负责可用WLAN信息展示的具体实现 + } + .id(`Wifi${index}`) + //对可用WLAN点击时触发事件 + .onClick(() => { + Logger.info(TAG, 'wifi click') + this.scanInfo = item + if (this.linkedInfo !== null && item.ssid === this.linkedInfo.ssid) { + prompt.showToast({ message: 'this wifi is connected' })//如果当前已连接WLAN并且点击的就是这个WLAN,创建并显示文本提示框 + return + } + if (item.securityType === 0 || item.securityType === 1) { + //如果点击的这个WLAN的加密类型是无效加密类型或者开放加密类型,调用model/Wifimodel.ets中的connectNetwork方法连接此WLAN + this.wifiModel.connectNetwork(item, '') + return + } + //如果点击的这个WLAN的加密类型是其他加密类型,则需要输入密码,调用component/PswDialog.ets中的方法进行弹窗的生成 + this.pswDialogController.open() + }) + }, item => JSON.stringify(item)) + } + .width('100%') + .height('100%') + .padding({ left: 16, right: 16 }) + .layoutWeight(1) + .divider({ strokeWidth: 1, color: Color.Gray, startMargin: 10, endMargin: 10 }) + .margin({ top: 10 }) + } + //pswDialogController回调的action函数,将传回的WLAN信息与密码传入model/Wifimodel.ets中的connectNetwork方法中 + onAccept(scanInfo, psw) { + Logger.info(TAG, 'connect wifi') + self.wifiModel.connectNetwork(scanInfo, psw) + } + ... + //Component/WifiView.ets + aboutToAppear() { + Logger.debug(TAG, `aboutToAppear ${JSON.stringify(this.wifi)}`) + if (this.wifi) { + if (this.wifi.securityType) { + if (this.wifi.securityType === 0 || this.wifi.securityType === 1) { + //WLAN的加密类型是无效加密类型或者开放加密类型 + this.securityString = $r('app.string.open') + this.isLock = false + } + } + } + } + build() { + Row() { + Column() { + if (this.wifi) { + if (this.wifi.ssid) { + Text(this.wifi.ssid) + .fontSize(20) + .width('100%') + } + } + //如果WLAN的加密类型是无效加密类型或者开放加密类型,显示“开放”,反之显示“加密” + Text(this.securityString) + .fontSize(18) + .fontColor(Color.Gray) + .width('100%') + } + .layoutWeight(1) + + Stack({ alignContent: Alignment.BottomEnd }) { + //如果WLAN的加密类型是无效加密类型或者开放加密类型,显示不带锁的图标,反之显示带锁的图标 + Image($r('app.media.wifi')) + .height(30) + .width(30) + .objectFit(ImageFit.Contain) + if (this.isLock) { + Image($r('app.media.lock')) + .objectFit(ImageFit.Contain) + .width(15) + .height(15) + } + } + .width(40) + .height(40) + .margin({ right: 10 }) + } + .backgroundColor(Color.White) + .width('100%') + .padding(10) + } + } + ... + //model/Wifimodel.ets + connectNetwork(scanInfo: wifi.WifiScanInfo, psw) { + prompt.showToast({ message: 'connecting', duration: 5000 }) + Logger.debug(TAG, `connectNetwork bssid=${scanInfo.bssid}`) + // 这里因为api问题,需要声明为any,已提单 + let deviceConfig: any = { + ssid: scanInfo.ssid, + bssid: scanInfo.bssid, + preSharedKey: psw, + isHiddenSsid: false, + securityType: scanInfo.securityType + } + try { + wifi.connectToDevice(deviceConfig)//连接到指定网络 + Logger.debug(TAG, `connectToDevice success`) + } catch (err) { + Logger.debug(TAG, `connectToDevice fail err is ${JSON.stringify(err)}`) + } + try { + wifi.addDeviceConfig(deviceConfig)//添加网络配置 + } catch (err) { + Logger.debug(TAG, `addDeviceConfig fail err is ${JSON.stringify(err)}`) + } + } + ... + //component/PswDialog.ets + build() { + Column() { + Text(this.scanInfo.ssid) + .fontSize(20) + .width('95%') + + TextInput({ placeholder: 'input password' })//密码的输入框 + .id('input') + .type(InputType.Password) + .placeholderColor(Color.Gray) + .fontSize(19) + .margin({ top: 15 }) + .width('95%') + .height(36) + //每当输入框中的内容变化,它就赋值给psw + .onChange((value: string) => { + this.psw = value + }) + + Row() { + //确认按钮 + Button() { + Text($r('app.string.sure')) + .fontColor(Color.Blue) + .fontSize(17) + } + .id('sure') + .layoutWeight(7) + .backgroundColor(Color.White) + .margin(5) + .onClick(() => { + this.controller.close() + this.action(this.scanInfo, this.psw) + }) + + Text() + .width(1) + .height(35) + .backgroundColor($r('app.color.text_color')) + //取消按钮 + Button() { + Text($r('app.string.cancel')) + .fontColor(Color.Red) + .fontSize(17) + } + .layoutWeight(7) + .backgroundColor(Color.White) + .margin(5) + .onClick(() => { + this.controller.close() + }) + } + .width('100%') + .margin({ top: '3%' }) + } + .padding(15) + } + ``` + +## 全部代码 + +本例完整代码sample示例链接:[WLAN](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Connectivity/Wlan) + +## 参考 + +- [权限列表](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md#ohospermissiondistributed_datasync) +- [@ohos.wifiManager](../application-dev/reference/apis/js-apis-wifiManager.md) +