diff --git a/CODEOWNERS b/CODEOWNERS index 075b95363eddc75d792d3e65f5c34f3114e666fd..3598264d0126154e0a84838f393fb3864f493dd7 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -14,121 +14,7 @@ - limitations under the License. */ -zh-cn/device-dev/kernel/ @Austin23 -zh-cn/device-dev/website.md @Austin23 -zh-cn/device-dev/faqs/ @Austin23 -zh-cn/device-dev/porting/ @Austin23 -zh-cn/device-dev/security/ @Austin23 -zh-cn/device-dev/guide/ @duangavin123_admin -zh-cn/device-dev/quick-start/ @li-yan339 -zh-cn/device-dev/driver/ @li-yan339 -zh-cn/device-dev/get-code/ @li-yan339 -zh-cn/device-dev/hpm-part/ @duangavin123_admin -zh-cn/device-dev/reference/hdi-apis/ @li-yan339 -zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @li-yan339 @chenmudan -zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan -zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan -zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan -zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-all.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-product.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-zh-cn/device-dev/subsystems/subsystem.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-component.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-module.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-chip_solution.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-feature.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-syscap.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-FAQ.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-graphics-layout-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-graphics-common-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-graphics-animation-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-camera-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-camera-photo-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-camera-record-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-camera-preview-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-video-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-video-play-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-multimedia-video-record-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23 -zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-devguide-conf.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-demo-sdk.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-demo-plugin.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-demo-conf.md @Austin23 -zh-cn/device-dev/subsystems/subsys-data-relational-database.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-data-relational-database-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-data-relational-database-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-data-storage.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-data-storage-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-data-storage-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-sensor-overview.md @Austin23 -zh-cn/device-dev/subsystems/subsys-sensor-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-sensor-demo.md @Austin23 -zh-cn/device-dev/subsystems/subsys-usbservice-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-usbservice-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-usbservice-demo.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-application-framework-overview.md @Austin23 -zh-cn/device-dev/subsystems/subsys-application-framework-envbuild.md @Austin23 -zh-cn/device-dev/subsystems/subsys-application-framework-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-application-framework-demo.md @Austin23 -zh-cn/device-dev/subsystems/subsys-ota-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-tel-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-tel-guide.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-security-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-security-huks-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init-cfg.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init-service.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init-sysparam.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot-ref.md @Austin23 -zh-cn/device-dev/subsystems/subsys-boot.md @Austin23 -zh-cn/device-dev/subsystems/subsys-testguide-test.md @Austin23 -zh-cn/device-dev/subsystems/subsys-dfx-overview.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hilog-lite.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hitrace.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hicollie.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-listening.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-query.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hidumper.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-hichecker.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-dfx-faultlogger.md @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-toolchain-bytrace-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23 -zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 +zh-cn/device-dev/ @li-yan339 @zengyawen zh-cn/application-dev/quick-start/arkts-get-started.md @HelloCrease @tomatodevboy @s10021109 zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md @HelloCrease @tomatodevboy @s10021109 zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md @HelloCrease @tomatodevboy @s10021109 @@ -371,7 +257,7 @@ zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @z zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw -zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @liuchao92 @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-environment.md @panqinxu @zengyawen @bubble_mao @jinhaihw @@ -517,7 +403,7 @@ zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zhang-hai-feng @zengy zh-cn/application-dev/reference/apis/js-apis-wifi.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers -zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @liuchao92 @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001 @@ -557,7 +443,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515 -zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee +zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @liuchao92 @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208 diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 5147d8c5200157e6a2edc8091630bbf22a6b9fb6..6e40eb34a50e798f7ae75f7c8cba2804cb6dfc51 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -50,6 +50,7 @@ - [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md) - [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md) - [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md) + - [\@AnimatableExtend Decorator: Definition of Animatable Attributes](quick-start/arkts-animatable-extend.md) - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) - State Management - [State Management Overview](quick-start/arkts-state-management-overview.md) @@ -77,6 +78,7 @@ - Development - [Application Models](application-models/Readme-EN.md) - [UI Development](ui/Readme-EN.md) + - [ArkTS Common Library](arkts-utils/Readme-EN.md) - [Web](web/Readme-EN.md) - [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) diff --git a/en/application-dev/ai/Readme-EN.md b/en/application-dev/ai/Readme-EN.md index 525a9f3afe7e1e951d2216160cc23ba4c9b3335b..ac075993f5e8dc7ecba94e4f101f73005344b76f 100644 --- a/en/application-dev/ai/Readme-EN.md +++ b/en/application-dev/ai/Readme-EN.md @@ -1,3 +1,7 @@ # AI -- [Using MindSpore Lite for Model Inference (JS)](mindspore-lite-js-guidelines.md) +- [AI Development](ai-overview.md) +- [Using MindSpore Lite JavaScript APIs to Develop AI Applications](mindspore-guidelines-based-js.md) +- [Using MindSpore Lite Native APIs to Develop AI Applications](mindspore-guidelines-based-native.md) + + diff --git a/en/application-dev/ai/ai-overview.md b/en/application-dev/ai/ai-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..968ee3439966cf2062e35cbb7929e4783566a2c6 --- /dev/null +++ b/en/application-dev/ai/ai-overview.md @@ -0,0 +1,40 @@ +# AI Development + +## Overview + +OpenHarmony provides native distributed AI capabilities. The AI subsystem consists of the following components: +- MindSpore Lite: an AI inference framework that provides unified APIs for AI inference. +- Neural Network Runtime (NNRt): an intermediate bridge that connects the inference framework and AI hardware. + +## MindSpore Lite + +MindSpore Lite is a built-in AI inference framework of OpenHarmony. It provides AI model inference capabilities for different hardware devices and end-to-end AI model inference solutions for developers to empower intelligent applications in all scenarios. Currently, MindSpore Lite has been widely used in applications such as image classification, target recognition, facial recognition, and character recognition. + +**Figure 1** Development process for MindSpore Lite model inference +![MindSpore workflow](figures/mindspore_workflow.png) + +The MindSpore Lite development process consists of two phases: + +- Model conversion + + MindSpore Lite uses models in `.ms` format for inference. You can use the model conversion tool provided by MindSpore Lite to convert third-party framework models, such as TensorFlow, TensorFlow Lite, Caffe, and ONNX, into `.ms` models. For details, see [Converting Models for Inference](https://www.mindspore.cn/lite/docs/en/r1.8/use/converter_tool.html). + +- Model inference + + You can call the MindSpore Lite runtime APIs to implement model inference. The procedure is as follows: + + 1. Create an inference context by setting the inference hardware and number of threads. + 2. Load the **.ms** model file. + 3. Set the model input data. + 4. Perform model inference, and read the output. + +MindSpore Lite is built in the OpenHarmony standard system as a system component. You can develop AI applications based on MindSpore Lite in the following ways: + +- Method 1: [Using MindSpore Lite JavaScript APIs to develop AI applications](./mindspore-guidelines-based-js.md). You directly call MindSpore Lite JavaScript APIs in the UI code to load the AI model and perform model inference. An advantage of this method is the quick verification of the inference effect. +- Method 2: [Using MindSpore Lite native APIs to develop AI applications](./mindspore-guidelines-based-native.md). You encapsulate the algorithm models and the code for calling MindSpore Lite native APIs into a dynamic library, and then use N-API to encapsulate the dynamic library into JavaScript APIs for the UI to call. + +## Neural Network Runtime + +Neural Network Runtime (NNRt) functions as a bridge to connect the upper-layer AI inference framework and bottom-layer acceleration chip, implementing cross-chip inference computing of AI models. + +MindSpore Lite supports configuration of the NNRt backend, and therefore you can directly configure MindSpore Lite to use the NNRt hardware. The focus of this topic is about how to develop AI applications using MindSpore Lite. For details about how to use NNRt, see [Connecting the Neural Network Runtime to an AI Inference Framework](../napi/neural-network-runtime-guidelines.md). diff --git a/en/application-dev/ai/figures/mindspore_workflow.png b/en/application-dev/ai/figures/mindspore_workflow.png new file mode 100644 index 0000000000000000000000000000000000000000..babb4b4e1ec2b8961b79a324e3ac556fd1522e81 Binary files /dev/null and b/en/application-dev/ai/figures/mindspore_workflow.png differ diff --git a/en/application-dev/ai/mindspore-lite-js-guidelines.md b/en/application-dev/ai/mindspore-guidelines-based-js.md similarity index 62% rename from en/application-dev/ai/mindspore-lite-js-guidelines.md rename to en/application-dev/ai/mindspore-guidelines-based-js.md index 1f309acf19ba608ac698892ed64bb2e75ffdc437..a504d6b2c9a1936b6408d76b3d5e34ed5da23db4 100644 --- a/en/application-dev/ai/mindspore-lite-js-guidelines.md +++ b/en/application-dev/ai/mindspore-guidelines-based-js.md @@ -1,10 +1,8 @@ -# Using MindSpore Lite for Model Inference (JS) +# Using MindSpore Lite JavaScript APIs to Develop AI Applications ## Scenarios -MindSpore Lite is an AI engine that implements AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. - -This document describes the general development process for implementing MindSpore Lite model inference. For details about how to use native APIs to implement model inference, see [Using MindSpore Lite for Model Inference](../napi/mindspore-lite-guidelines.md). +You can use the JavaScript APIs provided by MindSpore Lite to directly integrate MindSpore Lite capabilities into the UI code. This way, you can quickly deploy AI algorithms for AI model inference. ## Basic Concepts @@ -27,16 +25,14 @@ APIs involved in MindSpore Lite model inference are categorized into context API ## How to Develop -The development process consists of the following main steps: +Assume that you have prepared a model in the **.ms** format. The key steps in model inference are model reading, model building, model inference, and memory release. The development procedure is described as follows: + +1. Create a context, and set parameters such as the number of runtime threads and device type. +2. Load the model. In this example, the model is read from the file. +3. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor. +4. Perform model inference by calling **predict**, and read the output. -1. Prepare the required model. You can download the required model directly or obtain the model by using the model conversion tool. The required data is read from the `bin` file. - - If the downloaded model is in the `.ms` format, you can use it directly for inference. This document uses `mnet.caffemodel.ms` as an example. - - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r2.0/use/downloads.html#1-8-1) to convert it to the `.ms` format. -2. Create a context, and set parameters such as the number of runtime threads and device type. -3. Load the model. In this example, the model is read from the file. -4. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor. -5. Perform inference and print the output. Call the **predict** API to perform model inference. ```js @State inputName: string = 'mnet_caffemodel_nhwc.bin'; @State T_model_predict: string = 'Test_MSLiteModel_predict' @@ -49,7 +45,6 @@ build() { .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(async () => { - // 1. Prepare for a model. let syscontext = globalThis.context; syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { this.inputBuffer = buffer; @@ -57,20 +52,24 @@ build() { }).catch(error => { console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); }) - // 2. Create a context. + + // 1. Create a context. let context: mindSporeLite.Context = {}; context.target = ['cpu']; context.cpu = {} context.cpu.threadNum = 1; context.cpu.threadAffinityMode = 0; context.cpu.precisionMode = 'enforce_fp32'; - // 3. Load the model. + + // 2. Load the model. let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms'; let msLiteModel = await mindSporeLite.loadModelFromFile(modelFile, context); - // 4. Load data. + + // 3. Set the input data. const modelInputs = msLiteModel.getInputs(); modelInputs[0].setData(this.inputBuffer.buffer); - // 5. Perform inference and print the output. + + // 4. Perform inference and print the output. console.log('=========MSLITE predict start=====') msLiteModel.predict(modelInputs).then((modelOutputs) => { let output0 = new Float32Array(modelOutputs[0].getData()); @@ -89,21 +88,21 @@ build() { ## Debugging and Verification -1. Connect to the rk3568 development board on DevEco Studio, click **Run entry**, and compile your own HAP. The following information is displayed: +1. On DevEco Studio, connect to the device, click **Run entry**, and compile your own HAP. The following information is displayed: ```shell Launching com.example.myapptfjs $ hdc uninstall com.example.myapptfjs - $ hdc install -r "D:\TVOS\JSAPI\MyAppTfjs\entry\build\default\outputs\default\entry-default-signed.hap" + $ hdc install -r "path/to/xxx.hap" $ hdc shell aa start -a EntryAbility -b com.example.myapptfjs ``` -2. Use the hdc tool to connect to the rk3568 development board and push `mnet.caffemodel.ms` to the sandbox directory on the device. `mnet\_caffemodel\_nhwc.bin` is stored in the `rawfile` directory of the local project. +2. Use hdc to connect to the device, and push **mnet.caffemodel.ms** to the sandbox directory on the device. **mnet\_caffemodel\_nhwc.bin** is stored in the **rawfile** directory of the local project. ```shell - hdc -t 7001005458323933328a00bcdf423800 file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ + hdc -t your_device_id file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ ``` -3. Click **Test\_MSLiteModel\_predict** on the screen of the rk3568 development board to run the test case. The following information is displayed in the HiLog printing result: +3. Click **Test\_MSLiteModel\_predict** on the device screen to run the test case. The following information is displayed in the HiLog printing result: ```shell 08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start===== diff --git a/en/application-dev/ai/mindspore-guidelines-based-native.md b/en/application-dev/ai/mindspore-guidelines-based-native.md new file mode 100644 index 0000000000000000000000000000000000000000..8294ad4c3213ecd7815962cb96751e2af72a77d5 --- /dev/null +++ b/en/application-dev/ai/mindspore-guidelines-based-native.md @@ -0,0 +1,244 @@ +# Using MindSpore Lite Native APIs to Develop AI Applications + +## Scenarios + +You can use the native APIs provided by MindSpore Lite to deploy AI algorithms and provides APIs for the UI layer to invoke the algorithms for model inference. A typical scenario is the AI SDK development. + +## Basic concepts + +- [N-API](../reference/native-lib/third_party_napi/napi.md): a set of native APIs used to build JavaScript components. N-APIs can be used to encapsulate libraries developed using C/C++ into JavaScript modules. + +## Preparing the Environment + +- Install DevEco Studio 3.1.0.500 or later, and update the SDK to API version 10 or later. + +## How to Develop + +1. Create a native C++ project. + +Open DevEco Studio, choose **File** > **New** > **Create Project** to create a native C++ template project. By default, the **entry/src/main/** directory of the created project contains the **cpp/** directory. You can store C/C++ code in this directory and provide JavaScript APIs for the UI layer to call the code. + +2. Compile the C++ inference code. + +Assume that you have prepared a model in the **.ms** format. + +Before using the Native APIs provided by MindSpore Lite for development, you need to reference the corresponding header files. + +```c +#include +#include +#include +#include +``` + +(1). Read model files. + +```C++ +void *ReadModelFile(NativeResourceManager *nativeResourceManager, const std::string &modelName, size_t *modelSize) { + auto rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, modelName.c_str()); + if (rawFile == nullptr) { + LOGE("Open model file failed"); + return nullptr; + } + long fileSize = OH_ResourceManager_GetRawFileSize(rawFile); + void *modelBuffer = malloc(fileSize); + if (modelBuffer == nullptr) { + LOGE("Get model file size failed"); + } + int ret = OH_ResourceManager_ReadRawFile(rawFile, modelBuffer, fileSize); + if (ret == 0) { + LOGI("Read model file failed"); + OH_ResourceManager_CloseRawFile(rawFile); + return nullptr; + } + OH_ResourceManager_CloseRawFile(rawFile); + *modelSize = fileSize; + return modelBuffer; +} +``` + +(2). Create a context, set parameters such as the number of threads and device type, and load the model. + +```c++ +OH_AI_ModelHandle CreateMSLiteModel(void *modelBuffer, size_t modelSize) { + // Create a context. + auto context = OH_AI_ContextCreate(); + if (context == nullptr) { + DestroyModelBuffer(&modelBuffer); + LOGE("Create MSLite context failed.\n"); + return nullptr; + } + auto cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU); + OH_AI_ContextAddDeviceInfo(context, cpu_device_info); + + // Load the .ms model file. + auto model = OH_AI_ModelCreate(); + if (model == nullptr) { + DestroyModelBuffer(&modelBuffer); + LOGE("Allocate MSLite Model failed.\n"); + return nullptr; + } + + auto build_ret = OH_AI_ModelBuild(model, modelBuffer, modelSize, OH_AI_MODELTYPE_MINDIR, context); + DestroyModelBuffer(&modelBuffer); + if (build_ret != OH_AI_STATUS_SUCCESS) { + OH_AI_ModelDestroy(&model); + LOGE("Build MSLite model failed.\n"); + return nullptr; + } + LOGI("Build MSLite model success.\n"); + return model; +} +``` + +(3). Set the model input data, perform model inference, and obtain the output data. + +```js +void RunMSLiteModel(OH_AI_ModelHandle model) { + // Set the model input data. + auto inputs = OH_AI_ModelGetInputs(model); + FillInputTensors(inputs); + + auto outputs = OH_AI_ModelGetOutputs(model); + + // Perform inference and print the output. + auto predict_ret = OH_AI_ModelPredict(model, inputs, &outputs, nullptr, nullptr); + if (predict_ret != OH_AI_STATUS_SUCCESS) { + OH_AI_ModelDestroy(&model); + LOGE("Predict MSLite model error.\n"); + return; + } + LOGI("Run MSLite model success.\n"); + + LOGI("Get model outputs:\n"); + for (size_t i = 0; i < outputs.handle_num; i++) { + auto tensor = outputs.handle_list[i]; + LOGI("- Tensor %{public}d name is: %{public}s.\n", static_cast(i), OH_AI_TensorGetName(tensor)); + LOGI("- Tensor %{public}d size is: %{public}d.\n", static_cast(i), (int)OH_AI_TensorGetDataSize(tensor)); + auto out_data = reinterpret_cast(OH_AI_TensorGetData(tensor)); + std::cout << "Output data is:"; + for (int i = 0; (i < OH_AI_TensorGetElementNum(tensor)) && (i <= kNumPrintOfOutData); i++) { + std::cout << out_data[i] << " "; + } + std::cout << std::endl; + } + OH_AI_ModelDestroy(&model); +} +``` + + +(4). Implement a complete model inference process. + +```C++ +static napi_value RunDemo(napi_env env, napi_callback_info info) +{ + LOGI("Enter runDemo()"); + GET_PARAMS(env, info, 2); + napi_value error_ret; + napi_create_int32(env, -1, &error_ret); + + const std::string modelName = "ml_headpose.ms"; + size_t modelSize; + auto resourcesManager = OH_ResourceManager_InitNativeResourceManager(env, argv[1]); + auto modelBuffer = ReadModelFile(resourcesManager, modelName, &modelSize); + if (modelBuffer == nullptr) { + LOGE("Read model failed"); + return error_ret; + } + LOGI("Read model file success"); + + auto model = CreateMSLiteModel(modelBuffer, modelSize); + if (model == nullptr) { + OH_AI_ModelDestroy(&model); + LOGE("MSLiteFwk Build model failed.\n"); + return error_ret; + } + + RunMSLiteModel(model); + + napi_value success_ret; + napi_create_int32(env, 0, &success_ret); + + LOGI("Exit runDemo()"); + return success_ret; +} +``` + +(5). Write the **CMake** script to link the MindSpore Lite dynamic library `libmindspore_lite_ndk.so`. + +```cmake +cmake_minimum_required(VERSION 3.4.1) +project(OHOSMSLiteNapi) + +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + +include_directories(${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include) + +add_library(mslite_napi SHARED mslite_napi.cpp) +target_link_libraries(mslite_napi PUBLIC mindspore_lite_ndk) # MindSpore Lite dynamic library to link +target_link_libraries(mslite_napi PUBLIC hilog_ndk.z) +target_link_libraries(mslite_napi PUBLIC rawfile.z) +target_link_libraries(mslite_napi PUBLIC ace_napi.z) +``` + + +3. Use N-APIs to encapsulate C++ dynamic libraries into JavaScript modules. + + +Create the **libmslite_api/** subdirectory in **entry/src/main/cpp/types/**, and create the **index.d.ts** file in the subdirectory. The file content is as follows: + +```js +export const runDemo: (a:String, b:Object) => number; +``` + +Use the preceding code to define the JavaScript API `runDemo()`. + +In addition, add the **oh-package.json5** file to associate the API with the **.so** file to form a complete JavaScript module. + +```json +{ + "name": "libmslite_napi.so", + "types": "./index.d.ts" +} +``` + +4. Invoke the encapsulated MindSpore module in the UI code. + +In **entry/src/ets/MainAbility/pages/index.ets**, define the **onClick()** event and call the encapsulated **runDemo()** API in the event callback. + +```js +import msliteNapi from'libmslite_napi.so' // Import the msliteNapi module. + +// Certain code omitted + +// Trigger the event when the text on the UI is tapped. +.onClick(() => { + resManager.getResourceManager().then(mgr => { + hilog.info(0x0000, TAG, '*** Start MSLite Demo ***'); + let ret = 0; + ret = msliteNapi.runDemo("", mgr); // Call runDemo() to perform AI model inference. + if (ret == -1) { + hilog.info(0x0000, TAG, 'Error when running MSLite Demo!'); + } + hilog.info(0x0000, TAG, '*** Finished MSLite Demo ***'); + }) +}) +``` + +## Debugging and Verification + +On DevEco Studio, connect to the device and click **Run entry**. The following log is generated for the application process: + +```text +08-08 16:55:33.766 1513-1529/com.mslite.native_demo I A00000/MSLiteNativeDemo: *** Start MSLite Demo *** +08-08 16:55:33.766 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Enter runDemo() +08-08 16:55:33.772 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Read model file success +08-08 16:55:33.799 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Build MSLite model success. +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Run MSLite model success. +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Get model outputs: +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: - Tensor 0 name is: output_node_0. +08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: - Tensor 0 size is: 12. +08-08 16:55:33.826 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Exit runDemo() +08-08 16:55:33.827 1513-1529/com.mslite.native_demo I A00000/MSLiteNativeDemo: *** Finished MSLite Demo *** +``` diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 2a5ff1426182d415f09b55868c48d4238974ba64..9770de4b35a7e23d38a0266e5e0daf826e656e00 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -25,7 +25,8 @@ All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: -- [Web](web/web-component-overview.md) +- [ArkTS Common Library](arkts-utils/Readme-EN.md) +- [Web](web/Readme-EN.md) - [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) - [WebGL](webgl/Readme-EN.md) diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index d8bf473f9527e26eaf61c1a19757623879c4ef1d..65d3f42d95a37f3bdb9728a8e0b2897dd1ff8519 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -25,6 +25,7 @@ All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: +- [ArkTS Common Library](arkts-utils/arkts-commonlibrary-overview.md) - [Web](web/web-component-overview.md) - [Notification](notification/notification-overview.md) - [Window Manager](windowmanager/window-overview.md) diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index c655582af7834992c42025823b94ecab71eaa4ab..b7c1c93d21ec24673b3d07c4e971eadd7cd13661 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -89,7 +89,7 @@ The update-through-proxy configuration varies by the type of shared data. } ``` -- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\** component. +- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\** component. ```ts let storage = new LocalStorage(); @Entry(storage) @@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data. } ``` -- In the widget page code file (generally the .ets file in the **pages** folder under the widget directory of the project), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\** component. +- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\** component. ```ts let storage = new LocalStorage(); @Entry(storage) @@ -215,4 +215,4 @@ The update-through-proxy configuration varies by the type of shared data. ## Data Provider Development -For details, see [Data Management](../database/data-mgmt-overview.md). +For details, see [Data Management](../database/share-data-by-silent-access.md). 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 b1b09dc409380da8e530f571b2e5711ec63edd10..25cb66f1b05eaf845c11ab05350f2e705de6cec8 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 @@ -15,10 +15,11 @@ - Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host. - **Figure 2** Working principles of the ArkTS widget rendering service -![WidgetRender](figures/WidgetRender.png) + **Figure 2** Working principles of the ArkTS widget rendering service -Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. + ![WidgetRender](figures/WidgetRender.png) + +Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. ## Advantages of ArkTS Widgets @@ -57,6 +58,8 @@ In addition, ArkTS widgets do not support the following features: - Instant preview -- Breakpoint debugging. +- Breakpoint debugging - Hot reload + +- **setTimeOut** diff --git a/en/application-dev/application-test/arkxtest-guidelines.md b/en/application-dev/application-test/arkxtest-guidelines.md index 00c733c7c37676511ccab4d53dc9992b01456ff8..aaec95077225a4d761eff173a2ef4bfdf46abdc3 100644 --- a/en/application-dev/application-test/arkxtest-guidelines.md +++ b/en/application-dev/application-test/arkxtest-guidelines.md @@ -3,42 +3,48 @@ ## Overview -To accelerate test automation of OpenHarmony, arkXtest — an automated unit and UI test framework that supports both the JavaScript (JS) and TypeScript (TS) programming languages — is provided. +arkXtest is an automated test framework that supports both the JavaScript (JS) and TypeScript (TS) programming languages. It consists of JsUnit and UiTest. -In this document you will learn about the key functions of arkXtest and how to use it to perform unit testing on application or system APIs and to write UI automated test scripts. +JsUnit is a unit test framework that provides basic APIs for compiling test cases and generating test reports for testing system and application APIs. +UiTest is a UI test framework that provides the UI component search and operation capabilities through simple and easy-to-use APIs, and allows you to develop automated test scripts based on GUI operations. -### Introduction +This document describes the main functions, implementation principles, environment setup, and test script compilation and execution of arkXtest. -arkXtest is part of the OpenHarmony toolkit and provides basic capabilities of writing and running OpenHarmony automated test scripts. In terms of test script writing, arkXtest offers a wide range of APIs, including basic process APIs, assertion APIs, and APIs related to UI operations. In terms of test script running, arkXtest offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results. - -### Implementation +## Implementation arkXtest is divided into two parts: unit test framework and UI test framework. -- Unit Test Framework +As the backbone of arkXtest, the unit test framework offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results. + +The UI test framework provides UiTest APIs for you to call in different test scenarios. The UI test scripts are executed on top of the unit test framework. + +### Unit Test Framework - As the backbone of arkXtest, the unit test framework offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results. The figure below shows the main functions of the unit test framework. +Figure 1 Main functions of the unit test framework - ![](figures/UnitTest.PNG) +![](figures/UnitTest.PNG) - The following figure shows the basic unit test process. To start the unit test framework, run the **aa test** command. - - ![](figures/TestFlow.PNG) +Figure 2 Basic script process -- UI Test Framework +![](figures/TestFlow.PNG) - The UI test framework provides [UiTest APIs](../reference/apis/js-apis-uitest.md) for you to call in different test scenarios. The UI test scripts are executed on top of the aformentioned unit test framework. +> **NOTE** +> +> For details about the API in the unit test framework, see [Function Definition](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md#how-to-use). - The figure below shows the main functions of the UI test framework. +### UI Test Framework - ![](figures/Uitest.PNG) +Figure 3 Main functions of the UI test framework +![](figures/Uitest.PNG) -### Constraints -- The features of the UI test framework are available only in OpenHarmony 3.1 and later versions. +## Constraints + +- The features of the UI test framework are available only in OpenHarmony 3.1 Release and later versions. + - The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md). @@ -54,13 +60,24 @@ Hardware: PC connected to an OpenHarmony device, such as the RK3568 development [Download DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download) and set it up as instructed on the official website. +## Creating and Compiling a Test Script -## Creating a Test Script +### Creating a Test Script 1. Open DevEco Studio and create a project, in which the **ohos** directory is where the test script is located. 2. Open the .ets file of the module to be tested in the project directory. Move the cursor to any position in the code, and then right-click and choose **Show Context Actions** > **Create Ohos Test** or press **Alt+Enter** and choose **Create Ohos Test** to create a test class. -## Writing a Unit Test Script +### Writing a Unit Test Script + + The unit test script must contain the following basic elements: + +1. Import of the dependencies so that the dependent test APIs can be used. + +2. Test code, mainly about the related logic, such as API invoking. + +3. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete. + +The following sample code is used to start the test page to check whether the page displayed on the device is the expected page. ```TS import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; @@ -93,25 +110,17 @@ export default function abilityTest() { } ``` -The unit test script must contain the following basic elements: - -1. Import of the dependencies so that the dependent test APIs can be used. +### Writing a UI Test Script -2. Test code, mainly about the related logic, such as API invoking. +The UI test is based on the unit test. The UI test script adds the invoking of the UiTest interface (providing a link) to the unit test script to complete the corresponding test activities. In this example, the UI test script is written based on the preceding unit test script. It implements the click operation on the started application page and checks whether the page changes as expected. -3. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete. - -## Writing a UI Test Script - -You write a UI test script based on the unit test framework, adding the invoking of APIs provided by the UI test framework to implement the corresponding test logic. - -In this example, the UI test script is written based on the preceding unit test script. First, import the dependency, as shown below: +1. Import the dependency. ```js import {Driver,ON,Component,MatchPattern} from '@ohos.uitest' ``` -Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases. +2. Write test code. ```js export default function abilityTest() { @@ -125,21 +134,21 @@ export default function abilityTest() { console.info('Uitest, start ability failed: ' + err) }) await sleep(1000); - //check top display ability + // Check the top display ability. await delegator.getCurrentTopAbility().then((Ability)=>{ console.info("get top ability"); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); }) - //ui test code - //init driver + // UI test code + // Initialize the driver. var driver = await Driver.create(); await driver.delayMs(1000); - //find button on text 'Next' + // Find the button on text 'Next'. var button = await driver.findComponent(ON.text('Next')); - //click button + // Click the button. await button.click(); await driver.delayMs(1000); - //check text + // Check text. await driver.assertComponentExist(ON.text('after click')); await driver.pressBack(); done(); @@ -158,9 +167,11 @@ export default function abilityTest() { You can run a test script in DevEco Studio in any of the following modes: -- Test package level: All test cases in the test package are executed. -- Test suite level: All test cases defined in the **describe** method are executed. -- Test method level: The specified **it** method, that is, a single test case, is executed. +1. Test package level: All test cases in the test package are executed. + +2. Test suite level: All test cases defined in the **describe** method are executed. + +3. Test method level: The specified **it** method, that is, a single test case, is executed. ![](figures/Execute.PNG) @@ -170,9 +181,17 @@ After the test is complete, you can view the test result in DevEco Studio, as sh ![](figures/TestResult.PNG) +**Viewing the Test Case Coverage** + +After the test is complete, you can view the test case coverage. + ### In the CLI -To run a test script in the CLI, execute **aa** commands with different execution control keywords. +Install the application test package on the test device and run the **aa** command with different execution control keywords in the CLI. + +> **NOTE** +> +> Before running commands in the CLI, make sure hdc-related environment variables have been configured. The table below lists the keywords in **aa** test commands. @@ -196,15 +215,13 @@ The framework supports multiple test case execution modes, which are triggered b | random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true | | testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | | level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | -| size | Size of the test case to be executed. | small, medium, large | -s size small +| size | Size of the test case to be executed. | small, medium, large | -s size small | | stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | **Running Commands** -> Before running commands in the CLI, make sure hdc-related environment variables have been configured. - -- Open the CLI. -- Run the **aa test** commands. +1. Open the CLI. +2. Run the **aa test** commands. Example 1: Execute all test cases. @@ -303,8 +320,8 @@ OHOS_REPORT_STATUS: consuming=4 | OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.| | OHOS_REPORT_STATUS: stream | Error information of the current test case.| | OHOS_REPORT_STATUS: test| Name of the current test case.| -| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. The options are as follows:
**0**: pass
**1**: error
**2**: fail| -| OHOS_REPORT_STATUS: consuming | Time spent in executing the current test case.| +| OHOS_REPORT_STATUS_CODE | Execution result of the current test case.
**0**: pass.
**1**: error.
**2**: fail. | +| OHOS_REPORT_STATUS: consuming | Time spent in executing the current test case, in milliseconds.| - After the commands are executed, the log information similar to the following is displayed: @@ -323,10 +340,69 @@ OHOS_REPORT_STATUS: taskconsuming=16029 | Error | Number of test cases whose execution encounters errors. | | Pass | Number of passed test cases.| | Ignore | Number of test cases not yet executed.| -| taskconsuming| Total time spent in executing the current test case.| +| taskconsuming| Total time spent in executing the current test case, in milliseconds.| > When an error occurs in break-on-error mode, check the **Ignore** and interrupt information. +## Recording User Operations +### Using the Recording Feature +> You can record the operations performed on the current page to **/data/local/tmp/layout/record.csv**. To end the recording, press **Ctrl+C**. + +```shell + hdc shell uitest uiRecord record +``` +### Viewing Recording Data +You can view the recording data in either of the following ways. + +#### Reading and Printing Recording Data + +```shell + hdc shell uitest uiRecord read +``` +#### Exporting the record.csv File +```shell +hdc file recv /data/local/tmp/layout/record.csv D:\tool # D:\tool indicates the local save path, which can be customized. +``` +- The following describes the fields in the recording data: +``` +{ + "ABILITY": "com.ohos.launcher.MainAbility", // Foreground application page. + "BUNDLE": "com.ohos.launcher", // Application. + "CENTER_X": "", // X-coordinate of the center of the pinch gesture. + "CENTER_Y": "", // Y-coordinate of the center of the pinch gesture. + "EVENT_TYPE": "pointer", // + "LENGTH": "0", // Total length. + "OP_TYPE": "click", // Event type. Currently, click, double-click, long-press, drag, pinch, swipe, and fling types are supported. + "VELO": "0.000000", // Hands-off velocity. + "direction.X": "0.000000",// Movement along the x-axis. + "direction.Y": "0.000000", // Movement along the y-axis. + "duration": 33885000.0, // Gesture duration. + "fingerList": [{ + "LENGTH": "0", // Total length. + "MAX_VEL": "40000", // Maximum velocity. + "VELO": "0.000000", // Hands-off velocity. + "W1_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Starting component bounds. + "W1_HIER": "ROOT,3,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0", // Starting component hierarchy. + "W1_ID": "", // ID of the starting component. + "W1_Text": "", // Text of the starting component. + "W1_Type": "Image", // Type of the starting component. + "W2_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Ending component bounds. + "W2_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Ending component hierarchy. + "W2_ID": "", // ID of the ending component. + "W2_Text": "", // Text of the ending component. + "W2_Type": "Image", // Type of the ending component. + "X2_POSI": "47", // X coordinate of the ending point. + "X_POSI": "47", // X coordinate of the starting point. + "Y2_POSI": "301", // Y coordinate of the ending point. + "Y_POSI": "301", // Y coordinate of the starting point. + "direction.X": "0.000000", // Movement along the x-axis. + "direction.Y": "0.000000" // Movement along the y-axis. + }], + "fingerNumber": "1" // Number of fingers. +} +``` + + ## FAQs ### FAQs About Unit Test Cases @@ -404,7 +480,7 @@ hdc shell param set persist.ace.testmode.enabled 1 **Problem** -The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently". +The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently." **Possible Causes** @@ -415,7 +491,6 @@ The UI test case fails to be executed. The HiLog file contains the error message **Solution** 1. Check the case implementation and add the **await** operator to the asynchronous API. - 2. Do not execute UI test cases in multiple processes. #### The failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object" diff --git a/en/application-dev/arkts-utils/Readme-EN.md b/en/application-dev/arkts-utils/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..a574b494aea8d5bc7b62a000044fa81ae269b43e --- /dev/null +++ b/en/application-dev/arkts-utils/Readme-EN.md @@ -0,0 +1,23 @@ +# ArkTS Common Library + +- [Overview of ArkTS Common Library](arkts-commonlibrary-overview.md) +- Concurrency + - [Concurrency Overview](concurrency-overview.md) + - Using Asynchronous Concurrency for Development + - [Asynchronous Concurrency Overview](async-concurrency-overview.md) + - [Single I/O Task Development](single-io-development.md) + - Using Multithread Concurrency for Development + - [Multithread Concurrency Overview](multi-thread-concurrency-overview.md) + - [Comparison Between TaskPool and Worker](taskpool-vs-worker.md) + - [CPU Intensive Task Development](cpu-intensive-task-development.md) + - [I/O Intensive Task Development](io-intensive-task-development.md) + - [Synchronous Task Development](sync-task-development.md) +- Container + - [Container Overview](container-overview.md) + - [Linear Containers](linear-container.md) + - [Nonlinear Containers](nonlinear-container.md) +- XML Generation, Parsing, and Conversion + - [XML Overview](xml-overview.md) + - [XML Generation](xml-generation.md) + - [XML Parsing](xml-parsing.md) + - [XML Conversion](xml-conversion.md) diff --git a/en/application-dev/arkts-utils/arkts-commonlibrary-overview.md b/en/application-dev/arkts-utils/arkts-commonlibrary-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..708f14c78da7c7bd53d66cd62826ff01c5d6e212 --- /dev/null +++ b/en/application-dev/arkts-utils/arkts-commonlibrary-overview.md @@ -0,0 +1,31 @@ +# Overview of ArkTS Common Library + + +The ArkTS common library provides common basic capabilities, as illustrated in the figure below. + + +**Figure 1** Capabilities of the ArkTS common library + +![arkts-commonlibrary](figures/arkts-commonlibrary.png) + + +- Supporting [asynchronous concurrency and multithread concurrency](concurrency-overview.md) + - Supports standard JavaScript asynchronous concurrency capabilities such as Promise and async/await. + - Uses **TaskPool** to provide a multithread running environment for applications. The use of **TaskPool** helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. + - Uses **Worker** to support multithread concurrency. The worker thread can communicate with the host thread. You need to proactively create and close a worker thread. + +- Providing common capabilities of [adding, deleting, modifying, and querying elements in containers](container-overview.md) + +- Constructing and parsing XML files, URLs, and URIs + - Extensible Markup Language (XML) is designed for data transmission and storage. The common library provides APIs for [XML generation, parsing, and conversion](xml-overview.md). + - [URI](../reference/apis/js-apis-uri.md) is a uniform resource identifier that uniquely identifies a resource. [URL](../reference/apis/js-apis-url.md) is a uniform resource locator that provides a path for locating a resource. + +- Supporting common [string and binary data processing](../reference/apis/js-apis-util.md) and [logging](../reference/apis/js-apis-logs.md) + - Provides APIs to encode and decode strings. + - Provides APIs to encode and decode Base64-encoded bytes. + - Supports common rational number operations, including comparing rational numbers and obtaining numerators and denominators. + - Provides **Scope** APIs to define the valid range of a field. + - Provides APIs to process binary data in scenarios such as TCP flows or file system operations. + - Supports logging using the console. + +- Providing the capability of [obtaining process information and operating processes](../reference/apis/js-apis-process.md) \ No newline at end of file diff --git a/en/application-dev/arkts-utils/async-concurrency-overview.md b/en/application-dev/arkts-utils/async-concurrency-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..32bed2f143b9dbf32369fb439290d762269e055a --- /dev/null +++ b/en/application-dev/arkts-utils/async-concurrency-overview.md @@ -0,0 +1,87 @@ +# Asynchronous Concurrency Overview + + +Promise and async/await are standard JavaScript syntax that provides asynchronous concurrency. Asynchronous code ensures that actions initiated now finish later. It allows the execution of only one segment of code at a time and is therefore applicable to the development of a single I/O task, for example, a network request or a file read/write operation. + + +Promise and async/await allow an application to perform other operations without waiting for the completion of certain actions. + + +## Promise + +Promise is an object used to process asynchronous operations. It converts asynchronous operations into a style similar to synchronous operations for easier code writing and maintenance. Promise provides a state mechanism to manage different phases of asynchronous operations. It also provides methods to register callback functions to handle the success or failure of these operations. + +Promise has three states: pending, fulfilled, and rejected. After being created, a Promise object is in the pending state and changes to the fulfilled or rejected state when the asynchronous operation is complete. + +The most common usage for Promise is to instantiate a Promise object through a constructor and pass in a function (usually named **executor**) with two parameters. The **executor** function receives two parameters: **resolve** and **reject**, which represent the callback functions that should be called when the asynchronous operation succeeds and fails, respectively. The code snippet below creates a Promise object and simulates an asynchronous operation: + + +```js +const promise = new Promise((resolve, reject) => { + setTimeout(() => { + const randomNumber = Math.random(); + if (randomNumber > 0.5) { + resolve(randomNumber); + } else { + reject(new Error('Random number is too small')); + } + }, 1000); +}); +``` + +In the preceding code, the **setTimeout** function simulates an asynchronous operation that randomly generates a number one second later. If the random number is greater than 0.5, the **resolve** callback function is executed and the generated random number is passed in as a parameter. Otherwise, the **reject** callback function is executed and an error object is passed in as a parameter. + +After the Promise object is created, you can use the **then** and **catch** methods to register the callback functions for the fulfilled and rejected states. The **then** method can receive two parameters: one for processing the fulfilled state and the other for processing the rejected state. If only one parameter is passed in, the callback function is executed as long as the state changes. The **catch** method receives a callback function to process the failure result, that is, capture the exception thrown when the Promise state changes to **rejected** or the operation fails. The code snippet below shows the use of **then** and **catch** methods: + + +```js +promise.then(result => { + console.info(`Random number is ${result}`); +}).catch(error => { + console.error(error.message); +}); +``` + +In the preceding code, the callback function of the **then** method receives the success result of the Promise object as a parameter and outputs it to the console. If the Promise object enters the rejected state, the callback function of the **catch** method receives the error object as a parameter and outputs it to the console. + + +## Async/Await + +Async/Await is a Promise syntax sugar used to process asynchronous operations, making it easier to read and write asynchronous code. The async keyword is used to declare an asynchronous function, and the await keyword is used to wait for Promise parsing (fulfilled or rejected). In this way, the asynchronous operation logic is coded as a synchronous operation. + +The **async** function returns a Promise object to represent an asynchronous operation. Inside the **async** function, you can use the await keyword to wait for the parsing of the Promise object and return its parsed value. If an **async** function throws an exception, the Promise object returned by the function is rejected, and the exception information is passed to the **onRejected()** method of the Promise object. + +The code snippet below uses async/await to simulate an asynchronous operation that returns a string three seconds later. + + +```js +async function myAsyncFunction() { + const result = await new Promise((resolve) => { + setTimeout(() => { + resolve('Hello, world!'); + }, 3000); + }); + console.info(String(result)); // Output: Hello, world! +} + +myAsyncFunction(); +``` + +In the preceding code, the await keyword is used to wait for the parsing of the Promise object and store its parsed value in the **result** variable. + +Note that the entire operation must be packaged in the **async** function because the code needs to wait for the asynchronous operation to complete. In addition to **await**, you can use the try/catch block to capture exceptions in asynchronous operations. + + +```js +async function myAsyncFunction() { + try { + const result = await new Promise((resolve) => { + resolve('Hello, world!'); + }); + } catch (e) { + console.error(`Get exception: ${e}`); + } +} + +myAsyncFunction(); +``` diff --git a/en/application-dev/arkts-utils/concurrency-overview.md b/en/application-dev/arkts-utils/concurrency-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..3f091f42ea1257468aba5ba9ed94e64c92f661bb --- /dev/null +++ b/en/application-dev/arkts-utils/concurrency-overview.md @@ -0,0 +1,15 @@ +# Concurrency Overview + +Concurrency refers to the capability of processing multiple tasks in the same period. To improve the response speed and frame rate of applications and prevent time-consuming tasks from blocking the main thread, OpenHarmony provides two policies: asynchronous concurrency and multithread concurrency. + +- Asynchronous concurrency means that an action in asynchronous code is suspended and will continue later. Only one segment of code is being executed at a time. + +- Multithread concurrency allows multiple segments of code to be executed at a time. When the main thread continues to respond to user operations and update the UI, time-consuming operations are performed in the background to avoid application freezing. + +Concurrency is used in a variety of scenarios, including a single I/O task, CPU intensive task, I/O intensive task, synchronous task, and the like. You can select a concurrency policy based on your scenario. + +ArkTS provides the following mechanisms to support asynchronous concurrency and multithread concurrency: + +- Promise and async/await: provide asynchronous concurrency and apply to the development of a single I/O task. For details, see [Asynchronous Concurrency Overview](async-concurrency-overview.md). + +- **TaskPool** and **Worker**: provide multithread concurrency and apply to the development of CPU intensive tasks, I/O intensive tasks, and synchronous tasks. For details, see [Multithread Concurrency Overview](multi-thread-concurrency-overview.md). diff --git a/en/application-dev/arkts-utils/container-overview.md b/en/application-dev/arkts-utils/container-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..8a317e23167644ad72287c05672c3aa4a641cd29 --- /dev/null +++ b/en/application-dev/arkts-utils/container-overview.md @@ -0,0 +1,7 @@ +# Overview of Containers + +The container classes provide a set of methods to process elements of various data types stored in containers. + +The container classes are implemented in a way similar to static languages. By restricting storage locations and attributes, they remove redundant logic for each type of data while providing the complete functionalities, ensuring efficient data access and improving application performance. + +Currently, OpenHarmony provides 14 types of linear and non-linear containers, each of which has its own features and uses cases. For details, see [Linear Containers](linear-container.md) and [Nonlinear Containers](nonlinear-container.md). diff --git a/en/application-dev/arkts-utils/cpu-intensive-task-development.md b/en/application-dev/arkts-utils/cpu-intensive-task-development.md new file mode 100644 index 0000000000000000000000000000000000000000..80ecd66bb86f11bb4b0dace92e8e6924bdbd8b4f --- /dev/null +++ b/en/application-dev/arkts-utils/cpu-intensive-task-development.md @@ -0,0 +1,191 @@ +# CPU Intensive Task Development + + +CPU intensive tasks occupy lots of system computing resources for a long period of time, during which other events of the thread are blocked. Example CPU intensive tasks are image processing, video encoding, and data analysis. + + +OpenHarmony uses multithread concurrency to process CPU intensive tasks. This improves CPU utilization and application response speed. + + +If a task does not need to occupy a background thread for a long time (3 minutes), you are advised to use **TaskPool**. Otherwise, use **Worker**. The following uses histogram processing and a time-consuming model prediction task in the background as examples. + + +## Using TaskPool to Process Histograms + +1. Implement the logic of image processing. + +2. Segment the data, and initiate associated task scheduling through task groups. + Create a [task group](../reference/apis/js-apis-taskpool.md#taskgroup10), call [addTask()](../reference/apis/js-apis-taskpool.md#addtask10) to add tasks, call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute10) to execute the tasks in the task group, and set [a high priority](../reference/apis/js-apis-taskpool.md#priority) for the task group. After all the tasks in the task group are complete, the histogram processing result is returned simultaneously. + +3. Summarize and process the result arrays. + + +```ts +import taskpool from '@ohos.taskpool'; + +@Concurrent +function imageProcessing(dataSlice: ArrayBuffer) { + // Step 1: Perform specific image processing operations and other time-consuming operations. + return dataSlice; +} + +function histogramStatistic(pixelBuffer: ArrayBuffer) { + // Step 2: Perform concurrent scheduling for data in three segments. + let number = pixelBuffer.byteLength / 3; + let buffer1 = pixelBuffer.slice(0, number); + let buffer2 = pixelBuffer.slice(number, number * 2); + let buffer3 = pixelBuffer.slice(number * 2); + + let group = new taskpool.TaskGroup(); + group.addTask(imageProcessing, buffer1); + group.addTask(imageProcessing, buffer2); + group.addTask(imageProcessing, buffer3); + + taskpool.execute(group, taskpool.Priority.HIGH).then((ret: ArrayBuffer[]) => { + // Step 3: Summarize and process the result arrays. + }) +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let data: ArrayBuffer; + histogramStatistic(data); + }) + } + .width('100%') + } + .height('100%') + } +} +``` + + +## Using Worker for Time-Consuming Data Analysis + +The following uses the training of a region-specific house price prediction model as an example. This model can be used to predict house prices in the region based on the house area and number of rooms. The model needs to run for a long time, and the prediction will use the previous running result. Due to these considerations, **Worker** is used for the development. + +1. Add the worker creation template provided on DevEco Studio to your project, and name it **MyWorker**. + + ![newWorker](figures/newWorker.png) + +2. In the main thread, call [ThreadWorker()](../reference/apis/js-apis-worker.md#threadworker9) to create a **Worker** object. The calling thread is the host thread. + + ```js + import worker from '@ohos.worker'; + + const workerInstance = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + ``` + +3. In the host thread, call [onmessage()](../reference/apis/js-apis-worker.md#onmessage9) to receive messages from the worker thread, and call [postMessage()](../reference/apis/js-apis-worker.md#postmessage9) to send messages to the worker thread. + + For example, the host thread sends training and prediction messages to the worker thread, and receives messages sent back by the worker thread. + + + ```js + // Receive the result of the worker thread. + workerInstance.onmessage = function(e) { + // data carries the information sent by the main thread. + let data = e.data; + console.info('MyWorker.ts onmessage'); + // Perform time-consuming operations in the worker thread. + } + + workerInstance.onerror = function (d) { + // Receive error information of the worker thread. + } + + // Send a training message to the worker thread. + workerInstance.postMessage({ 'type': 0 }); + // Send a prediction message to the worker thread. + workerInstance.postMessage({ 'type': 1, 'value': [90, 5] }); + ``` + +4. Bind the **Worker** object in the **MyWorker.ts** file. The calling thread is the worker thread. + + ```js + import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; + + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; + ``` + +5. In the worker thread, call [onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1) to receive messages sent by the host thread, and call [postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2) to send messages to the host thread. + + For example, the prediction model and its training process are defined in the worker thread, and messages are exchanged with the main thread. + + + ```js + import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; + + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; + + // Define the training model and result. + let result; + + // Define the prediction function. + function predict(x) { + return result[x]; + } + + // Define the optimizer training process. + function optimize() { + result = {}; + } + + // onmessage logic of the worker thread. + workerPort.onmessage = function (e: MessageEvents) { + let data = e.data + // Perform operations based on the type of data to transmit. + switch (data.type) { + case 0: + // Perform training. + optimize(); + // Send a training success message to the main thread after training is complete. + workerPort.postMessage({ type: 'message', value: 'train success.' }); + break; + case 1: + // Execute the prediction. + const output = predict(data.value); + // Send the prediction result to the main thread. + workerPort.postMessage({ type: 'predict', value: output }); + break; + default: + workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); + break; + } + } + ``` + +6. After the task is completed in the worker thread, destroy the worker thread. The worker thread can be destroyed by itself or the host thread. Then, call [onexit()](../reference/apis/js-apis-worker.md#onexit9) in the host thread to define the processing logic after the worker thread is destroyed. + + + ```js + // After the worker thread is destroyed, execute the onexit() callback. + workerInstance.onexit = function() { + console.info("main thread terminate"); + } + ``` + + In the host thread, call [terminate()](../reference/apis/js-apis-worker.md#terminate9) to destroy the worker thread and stop the worker thread from receiving messages. + + + ```js + // Destroy the worker thread. + workerInstance.terminate(); + ``` + + In the worker thread, call [close()](../reference/apis/js-apis-worker.md#close9) to destroy the worker thread and stop the worker thread from receiving messages. + + ```js + // Destroy the worker thread. + workerPort.close(); + ``` diff --git a/en/application-dev/arkts-utils/figures/arkts-commonlibrary.png b/en/application-dev/arkts-utils/figures/arkts-commonlibrary.png new file mode 100644 index 0000000000000000000000000000000000000000..e8590f0115429b7857e3d7d44b7dceb821857515 Binary files /dev/null and b/en/application-dev/arkts-utils/figures/arkts-commonlibrary.png differ diff --git a/en/application-dev/arkts-utils/figures/newWorker.png b/en/application-dev/arkts-utils/figures/newWorker.png new file mode 100644 index 0000000000000000000000000000000000000000..c1b47bb4a885cf793ed467db43151a99720ea48d Binary files /dev/null and b/en/application-dev/arkts-utils/figures/newWorker.png differ diff --git a/en/application-dev/arkts-utils/figures/taskpool.png b/en/application-dev/arkts-utils/figures/taskpool.png new file mode 100644 index 0000000000000000000000000000000000000000..f5ae190d4dece65d196fd635b08ae6b420b6033b Binary files /dev/null and b/en/application-dev/arkts-utils/figures/taskpool.png differ diff --git a/en/application-dev/arkts-utils/figures/worker.png b/en/application-dev/arkts-utils/figures/worker.png new file mode 100644 index 0000000000000000000000000000000000000000..5feb2f6e5a01e4686a3cb3fe2451d72ae80c8685 Binary files /dev/null and b/en/application-dev/arkts-utils/figures/worker.png differ diff --git a/en/application-dev/arkts-utils/io-intensive-task-development.md b/en/application-dev/arkts-utils/io-intensive-task-development.md new file mode 100644 index 0000000000000000000000000000000000000000..562f749fd99daff42359af2598bc42483dc5595c --- /dev/null +++ b/en/application-dev/arkts-utils/io-intensive-task-development.md @@ -0,0 +1,51 @@ +# I/O Intensive Task Development + + +Asynchronous concurrency can solve the problem of a single blocking I/O operation. In the case of I/O intensive tasks, the execution of other tasks in the thread is still blocked. To resolve this issue, multithread concurrency is introduced. + + +The performance focus of I/O intensive tasks is not the CPU processing capability, but the speed and efficiency of I/O operations, since such a task usually requires frequent operations such as disk read/write and network communication. The following uses frequent read/write operations on a system file to simulate concurrency processing of I/O intensive tasks. + + +1. Define a concurrency function that internally calls I/O capabilities intensively. + + ```ts + import fs from '@ohos.file.fs'; + + // Define a concurrency function that internally calls I/O capabilities intensively. + @Concurrent + async function concurrentTest(fileList: string[]) { + // Implement file writing. + async function write(data, filePath) { + let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); + await fs.write(file.fd, data); + fs.close(file); + } + // Write the file cyclically. + for (let i = 0; i < fileList.length; i++) { + write('Hello World!', fileList[i]).then(() => { + console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); + }).catch((err) => { + console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) + return false; + }) + } + return true; + } + ``` + +2. Use **TaskPool** to execute the concurrency function that contains the intensive I/O operations. Specifically, call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute) to execute the tasks and process the scheduling result in a callback. For details about how to obtain **filePath1** and **filePath2** in the example, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). + + ```ts + import taskpool from '@ohos.taskpool'; + + let filePath1 =...; // Application file path + let filePath2 = ...; + + // Use TaskPool to execute the concurrency function that contains the intensive I/O operations. + // In the case of a large array, the distribution of I/O intensive tasks also preempts the main thread. Therefore, multiple threads are required. + taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => { + // Process the scheduling result. + console.info(`The result: ${ret}`); + }) + ``` diff --git a/en/application-dev/arkts-utils/linear-container.md b/en/application-dev/arkts-utils/linear-container.md new file mode 100644 index 0000000000000000000000000000000000000000..2a160f113f68e3257278e5a18168bb811a8efe30 --- /dev/null +++ b/en/application-dev/arkts-utils/linear-container.md @@ -0,0 +1,253 @@ +# Linear Containers + + +Linear containers implement a data structure that enables sequential access. The bottom layer of linear containers is implemented through arrays. OpenHarmony provides the following linear containers: **ArrayList**, **Vector**, **List**, **LinkedList**, **Deque**, **Queue**, and **Stack**. + + +Fully considering the data access speed, linear containers support Create, Read, Update, and Delete (CRUD) through a bytecode instruction at runtime. + + +## ArrayList + +[ArrayList](../reference/apis/js-apis-arraylist.md) is a dynamic array that can be used to construct a global array object. You are advised to use **ArrayList** when elements in a container need to be frequently read. + +**ArrayList** uses generics and must be stored in a contiguous memory space. Its initial capacity is 10, and it increases capacity 1.5-fold in each dynamic expansion. + +**ArrayList** provides the following CRUD APIs. + +| Operation| Description| +| --------- | ------- | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(element: T, index: number)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **arr\[index]** to obtain the value at a given position (specified by **index**).| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **arr\[index] = xxx** to change the value at a given position (specified by **index**).| +| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.| +| Deleting elements| Use **removeByRange(fromIndex: number, toIndex: number)** to remove all of the elements within a range.| + + +## Vector + +[Vector](../reference/apis/js-apis-vector.md) is a continuous storage structure that can be used to construct a global array object. **Vector** uses generics and must be stored in a contiguous memory space. Its initial capacity is 10, and it has capacity doubled in each dynamic expansion. + +Both **Vector** and [ArrayList](../reference/apis/js-apis-arraylist.md) are implemented based on arrays, but **Vector** provides more interfaces for operating the arrays. In addition to operator access, **Vector** provides the getter and setter to provide a more complete verification and error tolerance mechanism. + +The APIs provided by **Vector** are deprecated since API version 9. You are advised to use [ArrayList](../reference/apis/js-apis-arraylist.md). + +**Vector** provides the following CRUD APIs. + +| Operation| Description| +| --------- | ------- | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(element: T, index: number)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **vec\[index]** to obtain the value at a given position (specified by **index**).| +| Accessing elements| Use **get(index: number)** to obtain the element at a given position (specified by **index**).| +| Accessing elements| Use **getLastElement()** to obtain the last element in this container.| +| Accessing elements| Use **getlndexOf(element: T)** to obtain the index of the first occurrence of the specified element.| +| Accessing elements| Use **getLastlndexOf(element: T)** to obtain the index of the last occurrence of the specified element.| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, Vector?: Vector<T>) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **vec\[index]=xxx** to change the value at a given position (specified by **index**).| +| Modifying elements| Use **set(index: number, element: T)** to replace an element at a given position (specified by **index**) with a given element.| +| Modifying elements| Use **setLength(newSize: number)** to set the size of this container.| +| Deleting elements| Use **removeBylndex(index: number)** to remove the value at a given position (specified by **index**).| +| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.| +| Deleting elements| Use **removeByRange(fromIndex: number, toIndex: number)** to remove all of the elements within a range.| + + +## List + +[List](../reference/apis/js-apis-list.md) can be used to construct a singly linked list, which supports access only through the head node to the tail node. **List** uses generics and can be stored in a non-contiguous memory space. + +Unlike [LinkedList](../reference/apis/js-apis-linkedlist.md), which is a doubly linked list, **List** is a singly linked list that does not support insertion or removal at both ends. + +You are advised to use **List** for frequent insertion and removal operations. + +**List** provides the following CRUD APIs. + +| Operation| Description| +| --------- | ------ | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(element: T, index: number)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **list\[index]** to obtain the value at a given position (specified by **index**).| +| Accessing elements| Use **get(index: number)** to obtain the element at a given position (specified by **index**).| +| Accessing elements| Use **getFirst()** to obtain the first element in this container.| +| Accessing elements| Use **getLast()** to obtain the last element in this container.| +| Accessing elements| Use **getlndexOf(element: T)** to obtain the index of the first occurrence of the specified element.| +| Accessing elements| Use **getLastlndexOf(element: T)** to obtain the index of the last occurrence of the specified element.| +| Accessing elements| Use **forEach(callbackfn: (value: T, index?: number, list?: List<T>)=> void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **list\[index] = xxx** to change the value at a given position (specified by **index**).| +| Modifying elements| Use **set(index: number, element: T)** to replace an element at a given position (specified by **index**) with a given element.| +| Modifying elements| Use **replaceAllElements(callbackFn:(value: T,index?: number,list?: List<T>)=>T,thisArg?: Object)** to replace all elements in this container with new elements.| +| Deleting elements| Use **removeBylndex(index: number)** to remove the value at a given position (specified by **index**).| +| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.| + + +## LinkedList + +[LinkedList](../reference/apis/js-apis-linkedlist.md) can be used to construct a doubly linked list, which can be traversed at both ends. **LinkedList** uses generics and can be stored in a non-contiguous memory space. + +Unlike [List](../reference/apis/js-apis-list.md), which is a singly linked list, **LinkedList** is a doubly linked list that supports insertion and removal at both ends. + +**LinkedList** is more efficient in data insertion than [ArrayList](../reference/apis/js-apis-arraylist.md), but less efficient in data access. + +You are advised to use **LinkedList** for frequent insertion and removal operations. + +**LinkedList** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Adding elements| Use **insert(index: number, element: T)** to insert an element at a given position (specified by **index**).| +| Accessing elements| Use **list\[index]** to obtain the value at a given position (specified by **index**).| +| Accessing elements| Use **get(index: number)** to obtain the element at a given position (specified by **index**).| +| Accessing elements| Use **getFirst()** to obtain the first element in this container.| +| Accessing elements| Use **getLast()** to obtain the last element in this container.| +| Accessing elements| Use **getlndexOf(element: T)** to obtain the index of the first occurrence of the specified element.| +| Accessing elements| Use **getLastlndexOf(element: T)** to obtain the index of the last occurrence of the specified element.| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, list?: LinkedList<T>) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **list\[index]=xxx** to change the value at a given position (specified by **index**).| +| Modifying elements| Use **set(index: number, element: T)** to replace an element at a given position (specified by **index**) with a given element.| +| Deleting elements| Use **removeBylndex(index: number)** to remove the value at a given position (specified by **index**).| +| Deleting elements| Use **remove(element: T)** to remove the first occurrence of the specified element.| + + +## Deque + +[Deque](../reference/apis/js-apis-deque.md) can be used to construct a double-ended queue (deque) that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. + +**Deque** uses generics and must be stored in a contiguous memory space. Its initial capacity is 8, and it has capacity doubled in each dynamic expansion. The bottom layer of **Deque** is implemented by cyclic queues, delivering a high efficiency in enqueuing and dequeuing. + +[Queue](../reference/apis/js-apis-queue.md) follows the principle of FIFO only and allows element removal at the front and insertion at the rear. + +[Vector](../reference/apis/js-apis-vector.md) supports insertion and deletion of elements in between, as well as at both the ends. When compared with **Vector**, **Deque** is more efficient in inserting and removing header elements, but less efficient in accessing elements. + +You are advised to use **Deque** when you need to frequently insert or remove elements at both the ends of a container. + +**Deque** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **insertFront(element: T)** to insert an element at the front of this container.| +| Adding elements| Use **insertEnd(element: T)** to insert an element at the end of this container.| +| Accessing elements| Use **getFirst()** to obtain the value of the first element in this container, without removing it from the container.| +| Accessing elements| Use **getLast()** to obtain the value of the last element in this container, without removing it from the container.| +| Accessing elements| Use **popFirst()** to obtain the value of the first element in this container and remove it from the container.| +| Accessing elements| Use **popLast()** to obtain the value of the last element in this container and remove it from the container.| +| Accessing elements| Use **forEach(callbackFn:(value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **forEach(callbackFn:(value: T, index?: number, deque?: Deque<T>)=> void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **popFirst()** to remove the first element from this container.| +| Deleting elements| Use **popLast()** to remove the last element from this container.| + + +## Queue + +[Queue](../reference/apis/js-apis-queue.md) can be used to construct a queue that follows the FIFO principle. + +**Queue** uses generics and must be stored in a contiguous memory space. Its initial capacity is 8, and it has capacity doubled in each dynamic expansion. + +The bottom layer of **Queue** is implemented by cyclic queues, delivering a high efficiency in enqueuing and dequeuing. + +Unlike [Deque](../reference/apis/js-apis-deque.md), which supports insertion and removal at both the ends, **Queue** supports insertion at one end and removal at the other end. + +You are advised to use **Queue** in FIFO scenarios. + +**Queue** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **add(element: T)** to add an element at the end of this container.| +| Accessing elements| Use **getFirst()** to obtain the value of the first element in this container, without removing it from the container.| +| Accessing elements| Use **pop()** to obtain the value of the first element in this container and remove it from the container.| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, queue?: Queue<T>) => void,thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **forEach(callbackFn:(value: T, index?: number, queue?: Queue<T>) => void,thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **pop()** to remove the first element from this container.| + + +## Stack + +[Stack](../reference/apis/js-apis-stack.md) can be used to construct a stack that follows the Last Out First In (LOFI) principle. + +**Stack** uses generics and must be stored in a contiguous memory space. Its initial capacity is 8, and it increases capacity 1.5-fold in each dynamic expansion. The bottom layer of **Stack** is implemented based on arrays. It supports data insertion and removal at one end. + +Unlike [Queue](../reference/apis/js-apis-queue.md), which is implemented based on the queue data structure and supports insertion at one end and removal at the other end, **Stack** supports insertion and removal at the same end. + +You are advised to use **Stack** in LOFI scenarios. + +**Stack** provides the following CRUD APIs. + +| Operation| Description| +| ---------- | ------ | +| Adding elements| Use **push(item: T)** to add an element at the top of this container.| +| Accessing elements| Use **peek()** to obtain the value of the top element in this container, without removing it from the container.| +| Accessing elements| Use **pop()** to obtain the value of the top element in this container and remove it from the container.| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Accessing elements| Use **locate(element: T)** to obtain the index of the first occurrence of the specified element.| +| Modifying elements| Use **forEach(callbackFn:(value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **pop()** to remove the top element from this container.| + + +## Use of Linear Containers + +Refer to the code snippet below to add, access, and modify elements in **ArrayList**, **Vector**, **Deque**, **Stack**, and **List**. + + +```js +// ArrayList +import ArrayList from '@ohos.util.ArrayList'; // Import the ArrayList module. + +let arrayList = new ArrayList(); +arrayList.add('a'); +arrayList.add(1); // Add an element. +console.info(`result: ${arrayList[0]}`); // Access an element. +arrayList[0] = 'one'; // Modify an element. +console.info(`result: ${arrayList[0]}`); + +// Vector +import Vector from '@ohos.util.Vector'; // Import the Vector module. + +let vector = new Vector(); +vector.add('a'); +let b1 = [1, 2, 3]; +vector.add(b1); +vector.add(false); // Add an element. +console.info(`result: ${vector[0]}`); // Access an element. +console.info(`result: ${vector.getFirstElement()}`); // Access an element. + +// Deque +import Deque from '@ohos.util.Deque'; // Import the Deque module. + +let deque = new Deque; +deque.insertFront('a'); +deque.insertFront(1); // Add an element. +console.info(`result: ${deque[0]}`); // Access an element. +deque[0] = 'one'; // Modify an element. +console.info(`result: ${deque[0]}`); + +// Stack +import Stack from '@ohos.util.Stack'; // Import the Stack module. + +let stack = new Stack(); +stack.push('a'); +stack.push(1); // Add an element. +console.info(`result: ${stack[0]}`); // Access an element. +stack.pop(); // Remove an element. +console.info(`result: ${stack.length}`); + +// List +import List from '@ohos.util.List'; // Import the List module. + +let list = new List; +list.add('a'); +list.add(1); +let b2 = [1, 2, 3]; +list.add(b2); // Add an element. +console.info(`result: ${list[0]}`); // Access an element. +console.info(`result: ${list.get(0)}`); // Access an element. +``` diff --git a/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..2d42ea1a56cd56eb06cd1e8394735e17fed70a2b --- /dev/null +++ b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -0,0 +1,53 @@ +# Multithread Concurrency Overview + + +## Overview + +Concurrency models are used to implement concurrent tasks in different scenarios. Common concurrency models are classified into shared memory models and message passing models. + +A typical message passing model is actor. It provides a relatively high degree of concurrency while eliminating a series of complex and occasional issues caused by locks. For these reasons, ArkTS chooses the actor model. + +Due to the memory isolation feature of the actor model, cross-thread serialization is required. + + +## Data Transfer Objects + +Data objects that can be transferred are classified into three types: [common objects](#common-objects), [transferable objects](#transferable-objects), and [shared objects](#shared-objects). + + +### Common Objects + +The structured clone algorithm is used for serialization of common objects. This algorithm recursively transfers an object by clone. It supports more object types than other serialization algorithms. + +The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and typedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.) + + +### Transferable Objects + +Transferable objects are serialized through address transfer. It transfers the ownership of an object of the ArrayBuffer type object, rather than the content in it. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver. + + +```js +// Define a transferable object. +let buffer = new ArrayBuffer(100); +``` + + +### Shared Objects + +A shared object is of the **SharedArrayBuffer** type, has a fixed length, and can store any type of data including numbers and strings. + +An object of the SharedArrayBuffer type can be transferred between multiple threads. The objects before and after the transfer point to the same memory block, achieving memory sharing. + +If multiple operations are simultaneously performed to modify data stored in an object of the SharedArrayBuffer type, you must use atomics to ensure data synchronization. Atomics ensure that the current operation is complete before the next operation starts. + + +```js +// Define a shared object, which uses atomics to ensure data synchronization. +let sharedBuffer = new SharedArrayBuffer(1024); +``` + + +## TaskPool and Worker + +ArkTS provides two multithread concurrency capabilities: **TaskPool** and **Worker**, which differ in their implementation features and use cases. For details, see [Comparison Between TaskPool and Worker](taskpool-vs-worker.md). diff --git a/en/application-dev/arkts-utils/nonlinear-container.md b/en/application-dev/arkts-utils/nonlinear-container.md new file mode 100644 index 0000000000000000000000000000000000000000..3287d2675528cd73c0e43c562263b5af07bfaf46 --- /dev/null +++ b/en/application-dev/arkts-utils/nonlinear-container.md @@ -0,0 +1,253 @@ +# Nonlinear Containers + + +Nonlinear containers implement a data structure that enables quick search. The bottom layer of nonlinear containers is implemented through hash tables or red-black trees. OpenHarmony provides the following nonlinear containers: **HashMap**, **HashSet**, **TreeMap**, **TreeSet**, **LightWeightMap**, **LightWeightSet**, and **PlainArray**. The types of **key** and **value** in nonlinear containers must meet the ECMA standard. + + +## HashMap + +[HashMap](../reference/apis/js-apis-hashmap.md) is used to store a set of associated key-value (KV) pairs. In a hash map, each key is unique and corresponds to a value. + +**HashMap** uses generics. In a hash map, a key is located based on its hash code. The initial capacity of a hash map is 16, and it has capacity doubled in each dynamic expansion. The bottom layer of **HashMap** is implemented based on a hash table. It uses chaining to avoid collisions in hash tables. + +**HashMap** is faster in accessing data than [TreeMap](../reference/apis/js-apis-treemap.md), because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order. + +[HashSet](../reference/apis/js-apis-hashset.md) is implemented based on **HashMap**. The input parameter of **HashMap** consists of **key** and **value**. In **HashSet**, only the **value** object is processed. + +You are advised to use **HashMap** when you need to quickly access, remove, and insert KV pairs. + +**HashMap** provides the following Create, Read, Update, and Delete (CRUD) APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **set(key: K, value: V)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: K)** to obtain the value of the specified key.| +| Accessing elements| Use **keys()** to return an iterator that contains all the keys in this container.| +| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.| +| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.| +| Accessing elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<[K,V]>** for data access.| +| Modifying elements| Use **replace(key: K, newValue: V)** to change the value of the specified key.| +| Modifying elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.| +| Deleting elements| Use **clear()** to clear this container.| + + +## HashSet + +[HashSet](../reference/apis/js-apis-hashset.md) is used to store a set of values, each of which is unique in a hash set. + +**HashSet** uses generics. In a hash set, a value is located based on its hash code. The initial capacity of a hash set is 16, and it has capacity doubled in each dynamic expansion. The type of **value** must comply with the ECMA standard. The bottom layer of **HashSet** is implemented based on a hash table. It uses chaining to avoid collisions in hash tables. + +**HashSet** is implemented based on [HashMap](../reference/apis/js-apis-hashmap.md). In **HashSet**, only the **value** object is processed. + +Unlike [TreeSet](../reference/apis/js-apis-treeset.md), which stores and accesses data in sorted order, **HashSet** stores data in a random order. This means that **HashSet** may use a different order when storing and accessing elements. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**. + +You are advised to use **HashSet** when you need a set that has only unique elements or need to deduplicate a set. + +**HashSet** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **add(value: T)** to add a value to this container.| +| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.| +| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.| +| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: HashSet) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: HashSet) => void, thisArg?: Object)** to change a value in this container.| +| Deleting elements| Use **remove(value: T)** to remove a value.| +| Deleting elements| Use **clear()** to clear this container.| + + +## TreeMap + +[TreeMap](../reference/apis/js-apis-treemap.md) is used to store a set of associated KV pairs. In a tree map, each key is unique and corresponds to a value. + +**TreeMap** uses generics, and the keys in a tree map are ordered. The bottom layer of **TreeMap** is a binary tree, which supports quick search of KV pairs through the children (left child and right child) of the tree. The type of **key** must comply with the ECMA standard. Keys in a tree map are stored in order. The bottom layer of **TreeMap** is implemented based on the red-black tree and supports quick insertion and removal. + +[HashMap](../reference/apis/js-apis-hashmap.md) is faster in accessing data than **TreeMap**, because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order. + +You are advised to use **TreeMap** when you need to store KV pairs in sorted order. + +**TreeMap** provides the following CRUD APIs. + +| Operation| Description| +| ------- | ------ | +| Adding elements| Use **set(key: K, value: V)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: K)** to obtain the value of the specified key.| +| Accessing elements| Use **getFirstKey()** to obtain the first key in this container.| +| Accessing elements| Use **getLastKey()** to obtain the last key in this container.| +| Accessing elements| Use **keys()** to return an iterator that contains all the keys in this container.| +| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.| +| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.| +| Accessing elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator\<[K,V]>** for data access.| +| Modifying elements| Use **replace(key: K, newValue: V)** to change the value of the specified key.| +| Modifying elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.| +| Deleting elements| Use **clear()** to clear this container.| + + +## TreeSet + +[TreeSet](../reference/apis/js-apis-treeset.md) is used to store a set of values, each of which is unique in a tree set. + +**TreeSet** uses generics, and the values in a tree set are ordered. The bottom layer of **TreeSet** is a binary tree, which supports quick search of a value through the children (left child and right child) of the tree. The type of **value** must meet the ECMA standard. Values in a tree set are stored in order. The bottom layer of **TreeSet** is implemented based on the red-black tree and supports quick insertion and removal. + +**TreeSet** is implemented based on [TreeMap](../reference/apis/js-apis-treemap.md). In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique. + +[HashSet](../reference/apis/js-apis-hashset.md) stores data in a random order, whereas **TreeSet** stores data in sorted order. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**. + +You are advised to use **TreeSet** when you need to store data in sorted order. + +**TreeSet** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **add(value: T)** to add a value to this container.| +| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.| +| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.| +| Accessing elements| Use **getFirstValue()** to obtain the first value in this container.| +| Accessing elements| Use **getLastValue()** to obtain the last value in this container.| +| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: TreeSet) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: TreeSet) => void, thisArg?: Object)** to change a value in this container.| +| Deleting elements| Use **remove(value: T)** to remove a value.| +| Deleting elements| Use **clear()** to clear this container.| + + +## LightWeightMap + +[LightWeightMap](../reference/apis/js-apis-lightweightmap.md) is used to store a set of associated KV pairs. In a lightweight map, each key is unique and corresponds to a value. **LightWeightMap** uses generics and a more lightweight structure. It uses the hash code to uniquely identify a key at the bottom layer. It uses linear probing to avoid collisions. In a lightweight map, a key is located by using the hash code and binary search algorithm. The hash code is stored in an array and mapped to a key and its value in another array. The type of **key** must comply with the ECMA standard. + +The default initial capacity of a lightweight map is 8, and it has capacity doubled in each expansion. + +Compared with [HashMap](../reference/apis/js-apis-hashmap.md), which can also store KV pairs, **LightWeightMap** occupies less memory. + +You are advised to use **LightWeightMap** when you need to store and access **KV pairs**. + +**LightWeightMap** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **set(key: K, value: V)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: K)** to obtain the value of the specified key.| +| Accessing elements| Use **getIndexOfKey(key: K)** to obtain the index of the specified key.| +| Accessing elements| Use **getIndexOfValue(value: V)** to obtain the index of the first occurrence of the specified value.| +| Accessing elements| Use **keys()** to return an iterator that contains all the keys in this container.| +| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.| +| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.| +| Accessing elements| Use **getKeyAt(index: number)** to obtain the key of an element at a given position (specified by **index**).| +| Accessing elements| Use **getValueAt(index: number)** to obtain the value of an element at a given position (specified by **index**).| +| Accessing elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<[K,V]>** for data access.| +| Modifying elements| Use **setValueAt(index: number, newValue: V)** to change the value of an element at a given position (specified by **index**).| +| Modifying elements| Use **forEach(callbackFn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.| +| Deleting elements| Use **removeAt(index: number)** to remove an element at a given position (specified by **index**).| +| Deleting elements| Use **clear()** to clear this container.| + + +## LightWeightSet + +[LightWeightSet](../reference/apis/js-apis-lightweightset.md) is used to store a set of values, each of which is unique in a lightweight set. + +**LightWeightSet** uses generics and a lightweight structure. Its default initial capacity is 8, and it has capacity doubled in each expansion. In a lightweight set, a value is located by using the hash code and binary search algorithm. The hash code is stored in an array and mapped to a value in another array. The type of **value** must comply with the ECMA standard. + +**LightWeightSet** uses the hash code to uniquely identify a value at the bottom layer. It uses linear probing to avoid collisions and adopts the binary search algorithm. + +Compared with [HashSet](../reference/apis/js-apis-hashset.md), which can also store values, **LightWeightSet** occupies less memory. + +You are advised to use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set. + +**LightWeightSet** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **add(obj: T)** to add a value to this container.| +| Accessing elements| Use **getIndexOf(key: T)** to obtain the index of a key.| +| Accessing elements| Use **values()** to return an iterator that contains all the values in this container.| +| Accessing elements| Use **entries()** to return an iterator that contains all the elements in this container.| +| Accessing elements| Use **getValueAt(index: number)** to obtain the value of an element at a given position (specified by **index**).| +| Accessing elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<T>** for data access.| +| Modifying elements| Use **forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet) => void, thisArg?: Object)** to change a value in this container.| +| Deleting elements| Use **remove(key: K)** to remove an element with the specified key.| +| Deleting elements| Use **removeAt(index: number)** to remove an element at a given position (specified by **index**).| +| Deleting elements| Use **clear()** to clear this container.| + + +## PlainArray + +[PlainArray](../reference/apis/js-apis-plainarray.md) is used to store a set of associated KV pairs. In a plain array, each key is unique, corresponds to a value, and is of the number type. **PlainArray** uses generics and a more lightweight structure. In a plain array, a key is located by using the binary search algorithm and is mapped to a value in another array. + +The default initial capacity of a plain array is 16, and it has capacity doubled in each expansion. + +Both **PlainArray** and [LightWeightMap](../reference/apis/js-apis-lightweightmap.md) are used to store KV pairs in the lightweight structure. However, the key type of **PlainArray** can only be **number**. + +You are advised to use PlainArray when you need to store KV pairs whose keys are of the number type. + +**PlainArray** provides the following CRUD APIs. + +| Operation| Description| +| -------- | ------ | +| Adding elements| Use **add(key: number,value: T)** to add an element (a KV pair) to this container.| +| Accessing elements| Use **get(key: number)** to obtain the value of the specified key.| +| Accessing elements| Use **getIndexOfKey(key: number)** to obtain the index of the specified key.| +| Accessing elements| Use **getIndexOfValue(value: T)** to obtain the index of the specified value.| +| Accessing elements| Use **getKeyAt(index: number)** to obtain the key of an element at a given position (specified by **index**).| +| Accessing elements| Use **getValueAt(index: number)** to obtain the value of an element at a given position (specified by **index**).| +| Accessing elements| Use **forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object)** to traverse the elements in this container.| +| Accessing elements| Use **\[Symbol.iterator]():IterableIterator<[number, T]>** for data access.| +| Modifying elements| Use **setValueAt(index:number, value: T)** to change the value of an element at a given position (specified by **index**).| +| Modifying elements| Use **forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object)** to modify an element in this container.| +| Deleting elements| Use **remove(key: number)** to remove an element with the specified key.| +| Deleting elements| Use **removeAt(index: number)** to remove an element at a given position (specified by **index**).| +| Deleting elements| Use **removeRangeFrom(index: number, size: number)** to remove elements in a specified range.| +| Deleting elements| Use **clear()** to clear this container.| + + +## Use of Nonlinear Containers + +Refer to the code snippet below to add, access, and modify elements in **HashMap**, **TreeMap**, **LightWeightMap**, **Stack**, and **PlainArray**. + + +```js +// HashMap +import HashMap from '@ohos.util.HashMap'; // Import the HashMap module. + +let hashMap = new HashMap(); +hashMap.set('a', 123); +hashMap.set (4, 123);// Add an element. +console.info(`result: ${hashMap.hasKey(4)}`); // Check whether an element is contained. +console.info(`result: ${hashMap.get('a')}`); // Access an element. + +// TreeMap +import TreeMap from '@ohos.util.TreeMap'; // Import the TreeMap module. + +let treeMap = new TreeMap(); +treeMap.set('a', 123); +treeMap.set('6', 356); // Add an element. +console.info(`result: ${treeMap.get('a')}`); // Access an element. +console.info(`result: ${treeMap.getFirstKey()}`); // Access the first element. +console.info(`result: ${treeMap.getLastKey()}`); // Access the last element. + +// LightWeightMap +import LightWeightMap from '@ohos.util.LightWeightMap'; // Import the LightWeightMap module. + +let lightWeightMap = new LightWeightMap(); +lightWeightMap.set('x', 123); +lightWeightMap.set('8', 356); // Add an element. +console.info(`result: ${lightWeightMap.get('a')}`); // Access an element. +console.info(`result: ${lightWeightMap.get('x')}`); // Access an element. +console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // Access an element. + +// PlainArray +import PlainArray from '@ohos.util.PlainArray' // Import the PlainArray module. + +let plainArray = new PlainArray(); +plainArray.add(1, 'sdd'); +plainArray.add(2,'sff'); // Add an element. +console.info(`result: ${plainArray.get(1)}`); // Access an element. +console.info(`result: ${plainArray.getKeyAt(1)}`); // Access an element. +``` diff --git a/en/application-dev/arkts-utils/single-io-development.md b/en/application-dev/arkts-utils/single-io-development.md new file mode 100644 index 0000000000000000000000000000000000000000..b488890b42c9cb5849077fd1f00815f1a3f5ddf8 --- /dev/null +++ b/en/application-dev/arkts-utils/single-io-development.md @@ -0,0 +1,29 @@ +# Single I/O Task Development + + +Asynchronous concurrency provided by Promise and async/await is applicable to the development of a single I/O task. The following uses the asynchronous concurrency capability to write a file as an example. + + +1. Implement the logic of a single I/O task. + + ```js + import fs from '@ohos.file.fs'; + + async function write(data: string, filePath: string) { + let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); + fs.write(file.fd, data).then((writeLen) => { + fs.close(file); + }).catch((err) => { + console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); + }) + } + ``` + +2. Use the asynchronous capability to invoke the single I/O task. For details about how to obtain **filePath** in the example, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). + + ```js + let filePath = ...; // Application file path + write('Hello World!', filePath).then(() => { + console.info('Succeeded in writing data.'); + }) + ``` diff --git a/en/application-dev/arkts-utils/sync-task-development.md b/en/application-dev/arkts-utils/sync-task-development.md new file mode 100644 index 0000000000000000000000000000000000000000..8ce4290a5122b30955c94a1e9116c92f53e0ea7b --- /dev/null +++ b/en/application-dev/arkts-utils/sync-task-development.md @@ -0,0 +1,173 @@ +# Synchronous Task Development + + +Synchronous tasks are executed in order among multiple threads. For example, as a synchronization primitive, locks prevent data contention. + + +To implement synchronous tasks, you must consider the collaboration and synchronization between multiple threads and ensure the correctness of data and the correct execution of programs. + +If synchronous tasks are independent of each other, you are advised to use **TaskPool**, since it focuses on single independent tasks. For example, a series of imported static methods or methods implemented in singletons are independent. If synchronous tasks are associated with each other, use **Worker**, for example, methods implemented in class objects (not singleton class objects). + + +## Using TaskPool to Process Independent Synchronous Tasks + +**TaskPool** is recommended for scheduling independent synchronous tasks. Typical synchronous tasks are those using static methods. If a unique handle or class object constructed using a singleton points to multiple tasks and these tasks can be used between different worker threads, you can also use **TaskPool**. + +1. Define a concurrency function that internally calls the synchronous methods. + +2. Create a task, execute the task through **TaskPool**, and perform operations on the asynchronous result. Create a [task](../reference/apis/js-apis-taskpool.md#task) and call [execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute-1) to execute the task synchronously. + +3. Perform concurrent operations. + +Simulate a singleton class that contains synchronous calls. + + +```ts +// handle.ts code +export default class Handle { + static getInstance() { + // Return a singleton object. + } + + static syncGet() { + // Synchronous getter. + return; + } + + static syncSet(num: number) { + // Synchronous setter. + return; + } +} +``` + +Use **TaskPool** to call the related synchronous methods. + + +```ts +// Index.ets code +import taskpool from '@ohos.taskpool'; +import Handle from './Handle'; // Return a static handle. + +// Step 1: Define a concurrency function that internally calls the synchronous methods. +@Concurrent +function func(num: number) { + // Call the synchronous wait implemented in a static class object. + Handle.syncSet(num); + // Alternatively, call the synchronous wait implemented in a singleton object. + Handle.getInstance().syncGet(); + return true; +} + +// Step 2: Create and execute a task. +async function asyncGet() { + // Create a task and pass in the function func. + let task = new taskpool.Task(func, 1); + // Execute the task and obtain the result res. + let res = await taskpool.execute(task); + // Perform operations on the synchronous result. + console.info(String(res)); +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + // Step 3: Perform concurrent operations. + asyncGet(); + }) + } + .width('100%') + .height('100%') + } + } +} +``` + + +## Using Worker to Process Associated Synchronous Tasks + +Use **Worker** when you want to schedule a series of synchronous tasks using the same handle or depending on the same class object. + +1. Create a **Worker** object in the main thread and receive messages from the worker thread. + + ```js + import worker from '@ohos.worker'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let w = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + w.onmessage = function (d) { + // Receive the result of the worker thread. + } + w.onerror = function (d) { + // Receive error information of the worker thread. + } + // Send a Set message to the worker thread. + w.postMessage({'type': 0, 'data': 'data'}) + // Send a Get message to the worker thread. + w.postMessage({'type': 1}) + // Destroy the worker thread. + w.terminate() + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +2. Bind the **Worker** object in the worker thread and process the synchronous task logic. + + ```js + // handle.ts code + export default class Handle { + syncGet() { + return; + } + + syncSet(num: number) { + return; + } + } + + // Worker.ts code + import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; + import Handle from './handle.ts' // Return a handle. + + var workerPort : ThreadWorkerGlobalScope = worker.workerPort; + + // Handle that cannot be transferred. All operations depend on this handle. + var handler = new Handle() + + // onmessage() logic of the worker thread. + workerPort.onmessage = function(e : MessageEvents) { + switch (e.data.type) { + case 0: + handler.syncSet(e.data.data); + workerPort.postMessage('success set'); + case 1: + handler.syncGet(); + workerPort.postMessage('success get'); + } + } + ``` diff --git a/en/application-dev/arkts-utils/taskpool-vs-worker.md b/en/application-dev/arkts-utils/taskpool-vs-worker.md new file mode 100644 index 0000000000000000000000000000000000000000..4a3dcd0557a3afbdcfba515752eeea5780f872ab --- /dev/null +++ b/en/application-dev/arkts-utils/taskpool-vs-worker.md @@ -0,0 +1,164 @@ +# Comparison Between TaskPool and Worker + +**TaskPool** and **Worker** provide a multithread running environment for applications to process time-consuming computing tasks or resource intensive tasks, preventing these tasks from blocking the main thread. This maximizes system utilization, reduces overall resource consumption, and improves overall system performance. + + +This topic compares **TaskPool** with **Worker** from two aspects: [implementation features](#implementation-feature-comparison) and [use cases](#use-case-comparison). It also describes their operating mechanisms and precautions. + + +## Implementation Feature Comparison + +**Table 1** Comparison between TaskPool and Worker in implementation features + +| Item| TaskPool | Worker | +| -------- | -------- | -------- | +| Memory model| Threads are isolated from each other, and memory is not shared.| Threads are isolated from each other, and memory is not shared.| +| Parameter passing mechanism| The structured clone algorithm is used for serialization and deserialization.
ArrayBuffer and SharedArrayBuffer are used for parameter passing and sharing.| The structured clone algorithm is used for serialization and deserialization.
ArrayBuffer and SharedArrayBuffer are used for parameter passing and sharing.| +| Parameter passing| Parameters are directly passed in, without being encapsulated.| Only one parameter can be carried in a message object. Therefore, you must encapsulate excess parameters.| +| Method invocation| Methods are directly passed in and called.| Messages are passed in the worker thread and the corresponding methods are called.| +| Return value| A value is returned by default after asynchronous calling.| Messages proactively sent must be parsed and assigned by calling **onmessage()**.| +| Lifecycle| The task pool manages its own lifecycle, without considering the load.| You are required to manage the number and lifecycle of worker threads.| +| Maximum number of task pools| The number is automatically managed, rather than being manually configured.| A maximum of eight worker threads are supported.| +| Maximum task execution duration| 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, the time consumed by I/O tasks such as network download and file read/write)| There is no restriction.| +| Task priority setting| Setting the task priority is supported.| Setting the task priority is not supported.| +| Task cancellation| Tasks that have been initiated can be canceled.| Tasks that have been initiated cannot be canceled.| + + +## Use Case Comparison + +Both **TaskPool** and **Worker** support multithread concurrency. **TaskPool** worker threads are bound to the system scheduling priority and support load balancing (automatic scaling). **Worker** threads are manually created and do not support scheduling priority setting. Therefore, **TaskPool** provides better performance than **Worker** and is recommended in most scenarios. + +**TaskPool** is oriented to thread-level independent tasks, and tasks running for more than 3 minutes are automatically reclaimed by the system. **Worker** is oriented to threads and supports thread execution for a long time. + +Common use cases are as follows: + +- Use **Worker** for a task that runs for more than 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, I/O tasks such as network download and file read/write). For example, use **Worker** for a 1-hour prediction algorithm training job in the background. + +- Use **Worker** for a series of associated synchronous tasks. For example, use **Worker** for a series of database operations, since the same handle is required. + +- Use **TaskPool** for a task for which the priority needs to be set. For example, in the histogram rendering scenario in Gallery, histogram data calculated in the background is used for UI display on the foreground. This requires high-priority processing. In this case, use **TaskPool**. + +- Use **TaskPool** for a task that needs to be canceled frequently. For example, in the large image browsing scenario in Gallery, both images on the left and right sides of the current image are cached. When the user slides to the next image, a cache task on one side needs to be canceled. In this case, use **TaskPool**. + +- Use **TaskPool** for a large number of tasks or tasks with scattered scheduling points. For example, a large-scale application with multiple modules has multiple time-consuming tasks, and it is inconvenient to use eight worker threads to manage load. In this case, **TaskPool** is recommended. + + +## TaskPool Operating Mechanism + +**Figure 1** TaskPool operating mechanism + +![taskpool](figures/taskpool.png) + +With **TaskPool**, you can encapsulate tasks in the main thread and throw the tasks to the task queue. The system selects proper worker threads to distribute and execute the tasks, and then returns the result to the main thread. **TaskPool** provides APIs to execute and cancel tasks, and set the task priority. It also minimizes system resource usage through unified thread management, dynamic scheduling, and load balancing algorithms. By default, the system starts a worker thread and increases the thread quantity as the number of tasks increases. The maximum number of worker threads that can be created depends on the number of physical cores of the device. The formula is max(3, Number of physical cores – 1). If no task is distributed for a long period of time, the system reduces the number of worker threads. + + +## Worker Operating Mechanism + +**Figure 2** Worker operating mechanism + +![worker](figures/worker.png) + +The thread that creates the worker thread is referred to as the host thread (not necessarily the main thread, since a worker thread can also create a worker subthread). A worker thread is also named an actor thread. Each worker thread has an independent instance from the host thread, including the infrastructure, object, and code segment. The worker thread communicates with the host thread by means of message exchange. They use the serialization technique to exchange commands and data. + + +## Precautions for TaskPool + +- A task function must be decorated with **\@Concurrent** and can be used only in .ets files. + +- A task function must be a common function or async function, but not a class member function or anonymous function. + +- A task function can use imported variables and input parameter variables only in a project created on the stage model. In a project created on the FA model, it can use input parameter variables only. + +- A task function in the **TaskPool** worker thread must finish the execution within 3 minutes (excluding the time used for Promise or async/await asynchronous call, for example, the duration of I/O tasks such as network download and file read/write). Otherwise, it forcibly exits. + +- Input parameter types in a task function must be those supported by serialization. For details, see [Common Objects](multi-thread-concurrency-overview.md#common-objects). + +- Parameters of the ArrayBuffer type are transferred in **TaskPool** by default. You can set the transfer list by calling [setTransferList()](../reference/apis/js-apis-taskpool.md#settransferlist10). + +- The context objects in different threads are different. Therefore, **TaskPool** worker threads can use only thread-safe libraries, rather than UI-related non-thread-safe libraries. + +- A maximum of 16 MB data can be serialized. + + +## Precautions for Worker + +- The rules for passing in the **Worker.ts** path during the worker creation vary in different API versions. For details, see [Precautions for File Paths](#precautions-for-file-paths). + +- After a worker thread is created, you must manually manage its lifecycle. A maximum of eight worker threads can run simultaneously. For details, see [Lifecycle Precautions](#lifecycle-precautions). + +- Modules of the [ability type](../quick-start/application-package-structure-stage.md) support **Worker**, but modules of the [library type](../quick-start/application-package-structure-stage.md) do not support **Worker**. + +- When creating a worker thread, the **Worker.ts** file of another module cannot be used. This means that a worker cannot be called across modules. + +- The context objects in different threads are different. Therefore, **Worker** threads can use only thread-safe libraries, rather than UI-related non-thread-safe libraries. + +- A maximum of 16 MB data can be serialized. + + +### Precautions for File Paths + +Before calling an API of the **Worker** module, you must create a **Worker** instance. The constructor function varies in different API versions. + +```js +// Use the following function in API version 9 and later versions: +const worker1 = new worker.ThreadWorker(scriptURL); +// Use the following function in API version 8 and earlier versions: +const worker1 = new worker.Worker(scriptURL); +``` + +The **Worker.ts** file path (specified by **scriptURL**) must be passed in the constructor function. By default, the **workers** directory (upper-level directory of the **Worker.ts** file) is at the same level as the **pages** directory. + +**Stage Model** + + +The following is an example of **scriptURL** in the constructor function: + +```js +// Method 1 +// In the stage model, the workers directory is at the same level as the pages directory in the entry module. +const worker1 = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); +// In the stage model, the workers directory is a child directory of the pages directory in the entry module. +const worker2 = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); + +// Method 2 +// In the stage model, the workers directory is at the same level as the pages directory in the entry module, and bundlename is com.example.workerdemo. +const worker3 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); +// In the stage model, the workers directory is a child directory of the pages directory in the entry module, and bundlename is com.example.workerdemo. +const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); +``` + + +- Based on the directory structure of the stage model project, the field meanings in method 1 are as follows: + - **entry**: value of the **name** attribute under **module** in the **module.json5** file. + - **ets**: directory for storing the ArkTS source code. It is fixed. + - **workers/MyWorker.ts**: path of the worker source file in the **ets** directory. + +- Based on the directory structure of the stage model project, the field meanings in method 2 are as follows: + - **\@bundle**: fixed label. + - **bundlename**: bundle name of the current application. + - **entryname**: value of the **name** attribute under **module** in the **module.json5** file. + - **ets**: directory for storing the ArkTS source code. It is fixed. + - **workerdir/workerfile**: path of the worker source file in the **ets** directory. + + +**FA Model** + + +The following is an example of **scriptURL** in the constructor function: + +```js +// In the FA model, the workers directory is at the same level as the pages directory in the entry module. +const worker1 = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); +// In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module. +const worker2 = new worker.ThreadWorker('../workers/worker.js'); +``` + + +### Lifecycle Precautions + +- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. The worker threads keep running even when they are idle. Therefore, when a worker thread is not required, call [terminate()](../reference/apis/js-apis-worker.md#terminate9) interface or [parentPort.close()](../reference/apis/js-apis-worker.md#close9) to destroy it. If a worker thread is destroyed or being destroyed, an error is thrown when it is called. + + +- A maximum of eight worker threads can co-exist. + - In API version 8 and earlier versions, when the number of worker threads exceeds the upper limit, the error "Too many workers, the number of workers exceeds the maximum." is thrown. + - Since API version 9, when the number of worker threads exceeds the upper limit, the error "Worker initialization failure, the number of workers exceeds the maximum." is thrown. diff --git a/en/application-dev/arkts-utils/xml-conversion.md b/en/application-dev/arkts-utils/xml-conversion.md new file mode 100644 index 0000000000000000000000000000000000000000..96dc727635ea4449edd3bdc41e5ec016b268eca9 --- /dev/null +++ b/en/application-dev/arkts-utils/xml-conversion.md @@ -0,0 +1,92 @@ +# XML Conversion + + +Converting XML text into JavaScript objects makes it easier to process and manipulate data. In addition, JavaScript objects are more suitable than XML text for JavaScript applications. + + +The common library provides the **ConvertXML** class to convert XML text into JavaScript objects. The input is XML strings and conversion options, and the output is a JavaScript object. For details about the conversion options, see the API reference [@ohos.convertxml (XML-to-JavaScript Conversion)](../reference/apis/js-apis-convertxml.md). + + +## Precautions + +To ensure successful XML parsing and conversion, the input XML data must comply with the standard format. + + +## How to Develop + +The following steps walk you through on how to convert an XML file into a JavaScript object to obtain the tag values. + +1. Import the **convertxml** module. + + ```js + import convertxml from '@ohos.convertxml'; + ``` + +2. Pass in an XML file to be converted and set conversion options. + + ```js + let xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + let options = { + // trim: false, indicating that spaces before and after the text are not deleted after conversion. + // declarationKey: "_declaration", indicating that _declaration is used to identify the file declaration after conversion. + // instructionKey: "_instruction", indicating that _instruction is used to identify instructions after conversion. + // attributesKey: "_attributes", indicating that _attributes is used to identify attributes after conversion. + // textKey: "_text", indicating that _text is used to identify tag values after conversion. + // cdataKey: "_cdata", indicating that _cdata is used to identify unparsed data after conversion. + // docTypeKey: "_doctype", indicating that _doctype is used to identify documents after conversion. + // commentKey: "_comment", indicating that _comment is used to identify comments after conversion. + // parentKey: "_parent", indicating that _parent is used to identify parent classes after conversion. + // typeKey: "_type", indicating that _type is used to identify types after conversion. + // nameKey: "_name", indicating that _name is used to identify tag names after conversion. + // elementsKey: "_elements", indicating that _elements is used to identify elements after conversion. + trim: false, + declarationKey: "_declaration", + instructionKey: "_instruction", + attributesKey: "_attributes", + textKey: "_text", + cdataKey: "_cdata", + docTypeKey: "_doctype", + commentKey: "_comment", + parentKey: "_parent", + typeKey: "_type", + nameKey: "_name", + elementsKey: "_elements" + } + ``` + +3. Call the conversion function and print the result. + + ```js + let conv = new convertxml.ConvertXML(); + let result = conv.convertToJSObject(xml, options); + let strRes = JSON.stringify(result); // Convert the JavaScript object into a JSON string for explicit output. + console.info(strRes); + // Alternatively, directly process the JavaScript object to obtain the tag values. + let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // Parse the value of the tag. + let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // Parse the value of the <todo> tag. + let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // Parse the value of the <todo> tag. + console.info(title); // Happy + console.info(todo); // Work + console.info(todo2); // Play + ``` + + The output is as follows: + + + ```js + strRes: + {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", + "_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title", + "_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo", + "_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo", + "_elements":[{"_type":"text","_text":"Play"}]}]}]} + title:Happy + todo:Work + todo2:Play + ``` diff --git a/en/application-dev/arkts-utils/xml-generation.md b/en/application-dev/arkts-utils/xml-generation.md new file mode 100644 index 0000000000000000000000000000000000000000..d05cd9779255c6dfa51a9d4bb4556e2467c92c1c --- /dev/null +++ b/en/application-dev/arkts-utils/xml-generation.md @@ -0,0 +1,82 @@ +# XML Generation + + +XML can be used as a data exchange format, which is supported by a wealth of systems and applications. For example, web services can transfer structured data in XML format. + + +XML can also be used as a message passing format for communication between nodes in a distributed system. + + +## Precautions + +- XML tags must appear in pairs: one start tag and one end tag. + +- XML tags are case sensitive. The start tag and end tag must use the same case. + + +## How to Develop + +The **xml** module provides the **XmlSerializer** class to generate XML files. The input is an object of the ArrayBuffer or DataView type with a fixed length, which is used to store the output XML data. + +You can call different to write different types of content. For example, call **startElement(name: string)** to write the start tag and **setText(text: string)** to write a tag value. + +For details about the APIs of the **XML** module, see [@ohos.xml (XML Parsing and Generation)](../reference/apis/js-apis-xml.md). + +The following steps walk you through on how to generate an XML file. + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; + ``` + +2. Create a buffer and create an **XmlSerializer** object, either based on an object of the ArrayBuffer or DataView type. + + ```js + // 1. Create an XmlSerializer object based on an object of the ArrayBuffer type. + let arrayBuffer = new ArrayBuffer(2048); // Create a 2048-byte object of the ArrayBuffer type. + let thatSer = new xml.XmlSerializer (arrayBuffer); // Create an XmlSerializer object based on the object of the ArrayBuffer type. + + // 2. Create an XmlSerializer object based on an object of the DataView type. + let arrayBuffer = new ArrayBuffer(2048); // Create a 2048-byte object of the ArrayBuffer type. + let dataView = new DataView(arrayBuffer); // Use an object of the DataView type to operate the object of the ArrayBuffer type. + let thatSer = new xml.XmlSerializer (dataView); // Create an XmlSerializer object based on the object of the DataView type. + ``` + +3. Call the functions to generate an XML file. + + ```js + thatSer.setDeclaration(); // Write the XML file declaration. + thatSer.startElement('bookstore'); // Write the start flag. + thatSer.startElement('book'); // Write the start tag of a nested element. + thatSer.setAttributes('category', 'COOKING'); // Write the attributes and attribute values. + thatSer.startElement('title'); + thatSer.setAttributes('lang', 'en'); + thatSer.setText('Everyday'); // Write the tag value. + thatSer.endElement(); // Write the end flag. + thatSer.startElement('author'); + thatSer.setText('Giada'); + thatSer.endElement(); + thatSer.startElement('year'); + thatSer.setText('2005'); + thatSer.endElement(); + thatSer.endElement(); + thatSer.endElement(); + ``` + +4. Use **Uint8Array** to operate the object of the ArrayBuffer type, and use **TextDecoder** to decode the Uint8Array. + + ```js + let view = new Uint8Array(arrayBuffer); // Use Uint8Array to read data from the object of the ArrayBuffer type. + let textDecoder = util.TextDecoder.create(); // Call the TextDecoder class of the util module. + let res = textDecoder.decodeWithStream (view); // Decode the view. + console.info(res); + ``` + + The output is as follows: + + + ```js + <?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore>\r\n <book category=\"COOKING\">\r\n <title lang=\"en\">Everyday\r\n Giada\r\n 2005\r\n \r\n + ``` diff --git a/en/application-dev/arkts-utils/xml-overview.md b/en/application-dev/arkts-utils/xml-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d376fea2134fbdac8a02d5a4c8e4ffdfdb99eb4d --- /dev/null +++ b/en/application-dev/arkts-utils/xml-overview.md @@ -0,0 +1,23 @@ +# XML Overview + + +Extensible Markup Language (XML) is a markup language used to describe data. It aims to provide a common way to transmit and store data, especially data frequently used in web applications. XML does not predefine tags. As a result, it is more flexible and widely used. + + +An XML file consists of elements, attributes, and content. + + +- An element refers to a tag pair that contains text, attributes, or other elements. + +- Attributes provide additional information about an element. + +- Content is the data or sub-element contained in an element. + + +XML supports the use of XML Schema Definition (XSD) or Document Type Definition (DTD) for defining the document structure. This allows you to customize rules to verify whether an XML document is in the expected format. + + +XML also supports features such as namespaces, entity references, comments, and processing instructions, making it easy to adapt to diverse data requirements. + + +The common library provides XML-related basic capabilities, including [XML generation](xml-generation.md), [XML parsing](xml-parsing.md), and [XML conversion](xml-conversion.md). diff --git a/en/application-dev/arkts-utils/xml-parsing.md b/en/application-dev/arkts-utils/xml-parsing.md new file mode 100644 index 0000000000000000000000000000000000000000..dd3e46517b3eec6aafce6d6566a2da982bbd8d6c --- /dev/null +++ b/en/application-dev/arkts-utils/xml-parsing.md @@ -0,0 +1,271 @@ +# XML Parsing + + +Data transferred in XML format must be parsed in actual use. Generally, three types of elements need to be parsed, as described in [Parsing XML Tags and Tag Values](#parsing-xml-tags-and-tag-values), [Parsing XML Attributes and Attribute Values](#parsing-xml-attributes-and-attribute-values), and [Parsing XML Event Types and Element Depths](#parsing-xml-event-types-and-element-depths). + + +The **xml** module provides the **XmlPullParser** class to parse XML files. The input is an object of the ArrayBufffer or DataView type containing XML text, and the output is the parsed information. + + +**Table 1** XML parsing options + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| supportDoctype | boolean | No| Whether to ignore the document type. The default value is **false**, indicating that the document type is parsed.| +| ignoreNameSpace | boolean | No| Whether to ignore the namespace. The default value is **false**, indicating that the namespace is parsed.| +| tagValueCallbackFunction | (name: string, value: string) => boolean | No| Callback used to return **tagValue**, which consists of a tag and its value. The default value is **null**, indicating that XML tags and tag values are not parsed.| +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No| Callback used to return **attributeValue**, which consists of an attribute and its value. The default value is **null**, indicating that XML attributes and attribute values are not parsed.| +| tokenValueCallbackFunction | (eventType: EventType, value: ParseInfo) => boolean | No| Callback used to return **tokenValue**, which consists of the event type and the attributes of **parseInfo**. The default value is **null**, indicating that the event type and the attributes of **parseInfo** are not parsed.| + + +## Precautions + +- To ensure successful XML parsing and conversion, the input XML data must comply with the standard format. + +- Currently, parsing a given node is not supported. + + +## Parsing XML Tags and Tag Values + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; // Use the API provided by the util module to encode the file. + ``` + +2. Create an **XmlPullParser** object. + + The **XmlPullParser** object can be created based on an object of the ArrayBuffer or DataView type. + + + ```js + let strXml = + '' + + '' + + 'Play' + + 'Work' + + ''; + let textEncoder = new util.TextEncoder(); + let arrBuffer = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters. + // 1. Create an XmlPullParser object based on an object of the ArrayBuffer type. + let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + + // 2. Create an XmlPullParser object based on an object of the DataView type. + let dataView = new DataView(arrBuffer.buffer); + let that = new xml.XmlPullParser(dataView, 'UTF-8'); + ``` + +3. Customize a callback function. In this example, the tag and tag value are directly printed. + + ```js + let str = ''; + function func(name, value){ + str = name + value; + console.info(str); + return true; // The value true means to continue parsing, and false means to stop parsing. + } + ``` + +4. Set parsing options and call the **parse()** function. + + ```js + let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; + that.parse(options); + ``` + + The output is as follows: + + + ```js + note + title + Play + title + lens + Work + lens + note + ``` + + +## Parsing XML Attributes and Attribute Values + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; // Use the API provided by the util module to encode the file. + ``` + +2. Create an **XmlPullParser** object. + + ```js + let strXml = + '' + + '' + + ' Play' + + ' Happy' + + ' Work' + + ''; + let textEncoder = new util.TextEncoder(); + let arrBuffer = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters. + let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` + +3. Customize a callback function. In this example, the attribute and attribute value are directly printed. + + ```js + let str = ''; + function func(name, value){ + str += name + ' ' + value + ' '; + return true; // The value true means to continue parsing, and false means to stop parsing. + } + ``` + +4. Set parsing options and call the **parse()** function. + + ```js + let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; + that.parse(options); + console.info(str); // Print all attributes and their values at a time. + ``` + + The output is as follows: + + + ```js + importance high logged true // Attributes and attribute values of the note node + ``` + + +## Parsing XML Event Types and Element Depths + +1. Import the modules. + + ```js + import xml from '@ohos.xml'; + import util from '@ohos.util'; // Use the API provided by the util module to encode the file. + ``` + +2. Create an **XmlPullParser** object. + + ```js + let strXml = + '' + + '' + + 'Play' + + ''; + let textEncoder = new util.TextEncoder(); + let arrBuffer = textEncoder.encodeInto(strXml); // Encode the data to prevent garbled characters. + let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` + +3. Customize a callback function. In this example, the event type and element depth are directly printed. + + ```js + let str = ''; + function func(name, value){ + str = name +' ' + value.getDepth(); // getDepth is called to obtain the element depth. + console.info(str) + return true; // The value true means to continue parsing, and false means to stop parsing. + } + ``` + +4. Set parsing options and call the **parse()** function. + + ```js + let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; + that.parse(options); + ``` + + The output is as follows: + + + ```js + 0 0 // 0: . The event type value of START_DOCUMENT is 0. 0: The depth is 0. + 2 1 // 2: . The event type value of START_TAG is 2. 1: The depth is 1. + 2 2 // 2: . The event type value of START_TAG is 2. 2: The depth is 2. + 4 2 // 4: Play. The event type value of TEXT is 4. 2: The depth is 2. + 3 2 // 3: . The event type value of END_TAG is 3. 2: The depth is 2. + 3 1 // 3: . The event type value of END_TAG is 3. 1: The depth is 1 (corresponding to ). + 1 0 // 1: The event type value of END_DOCUMENT is 1. 0: The depth is 0. + ``` + + +## Example Scenario + +The following uses invoking all parsing options as an example to describe how to parse XML tags, attributes, and event types. + + +```js +import xml from '@ohos.xml'; +import util from '@ohos.util'; + +let strXml = + '' + + '' + + 'Everyday' + + 'Giada' + + ''; +let textEncoder = new util.TextEncoder(); +let arrBuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); +let str = ''; + +function tagFunc(name, value) { + str = name + value; + console.info('tag-' + str); + return true; +} + +function attFunc(name, value) { + str = name + ' ' + value; + console.info('attri-' + str); + return true; +} + +function tokenFunc(name, value) { + str = name + ' ' + value.getDepth(); + console.info('token-' + str); + return true; +} + +let options = { + supportDocType: true, + ignoreNameSpace: true, + tagValueCallbackFunction: tagFunc, + attributeValueCallbackFunction: attFunc, + tokenValueCallbackFunction: tokenFunc +}; +that.parse(options); + +``` + +The output is as follows: + + +```js +tag- +token-0 0 +tag-book +attri-category COOKING +token-2 1 +tag-title +attri-lang en +token-2 2 +tag-Everyday +token-4 2 +tag-title +token-3 2 +tag-author +token-2 2 +tag-Giada +token-4 2 +tag-author +token-3 2 +tag-book +token-3 1 +tag- +token-1 0 +``` diff --git a/en/application-dev/connectivity/net-mdns.md b/en/application-dev/connectivity/net-mdns.md index 16aa29609d0826388b244a7daebbcb1f849ed27e..de7982a5c03908a70e4005bdc5fbea3584c435f5 100644 --- a/en/application-dev/connectivity/net-mdns.md +++ b/en/application-dev/connectivity/net-mdns.md @@ -94,7 +94,7 @@ mdns.removeLocalService(context, localServiceInfo, function (error, data) { 1. Connect the device to the Wi-Fi network. 2. Import the **mdns** namespace from **@ohos.net.mdns**. -3. Create a **DiscoveryService** object, which is used to discover mDNS services of the specified type. +3. Creates a **DiscoveryService** object, which is used to discover mDNS services of the specified type. 4. Subscribe to mDNS service discovery status changes. 5. Enable discovery of mDNS services on the LAN. 6. Stop searching for mDNS services on the LAN. @@ -116,20 +116,6 @@ class EntryAbility extends UIAbility { } let context = globalThis.context; -// Create a LocalService object. -let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] -} - // Create a DiscoveryService object, which is used to discover mDNS services of the specified type. let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); diff --git a/en/application-dev/connectivity/net-statistics.md b/en/application-dev/connectivity/net-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..47ec62ff156448b3214885176c30b2f76d77b76c --- /dev/null +++ b/en/application-dev/connectivity/net-statistics.md @@ -0,0 +1,155 @@ +# Traffic Management + +## Introduction + +The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID). + +Its functions include: + +- Obtaining real-time traffic data by NIC or UID +- Obtaining historical traffic data by NIC or UID +- Subscribing to traffic change events by NIC or UID + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-statistics.md). + +The following describes the development procedure specific to each application scenario. + +## Available APIs + +For the complete list of APIs and example code, see [Traffic Management](../reference/apis/js-apis-net-statistics.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.statistics | getIfaceRxBytes(nic: string, callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the specified NIC. | +| ohos.net.statistics | getIfaceTxBytes(nic: string, callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the specified NIC. | +| ohos.net.statistics | getCellularRxBytes(callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the cellular network.| +| ohos.net.statistics | getCellularTxBytes(callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the cellular network.| +| ohos.net.statistics | getAllRxBytes(callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the all NICs. | +| ohos.net.statistics | getAllTxBytes(callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the all NICs. | +| ohos.net.statistics | getUidRxBytes(uid: number, callback: AsyncCallback\): void; |Obtains the real-time downlink data traffic of the specified application. | +| ohos.net.statistics | getUidTxBytes(uid: number, callback: AsyncCallback\): void; |Obtains the real-time uplink data traffic of the specified application. | +| ohos.net.statistics | getTrafficStatsByIface(ifaceInfo: IfaceInfo, callback: AsyncCallback\): void; |Obtains the historical data traffic of the specified NIC. | +| ohos.net.statistics | getTrafficStatsByUid(uidInfo: UidInfo, callback: AsyncCallback\): void; |Obtains the historical data traffic of the specified application. | +| ohos.net.statistics | on(type: 'netStatsChange', callback: Callback\<{ iface: string, uid?: number }>): void |Subscribes to traffic change events.| +| ohos.net.statistics | off(type: 'netStatsChange', callback?: Callback\<{ iface: string, uid?: number }>): void; |Unsubscribes from traffic change events.| + +## Obtaining Real-Time Traffic Data by NIC or UID + +1. Obtain the real-time data traffic of the specified NIC. +2. Obtain the real-time data traffic of the cellular network. +3. Obtain the real-time data traffic of all NICs. +4. Obtain the real-time data traffic of the specified application. + +```js +// Import the statistics namespace from @ohos.net.statistics. +import statistics from '@ohos.net.statistics' + +// Obtain the real-time downlink data traffic of the specified NIC. +statistics.getIfaceRxBytes("wlan0", (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the specified NIC. +statistics.getIfaceTxBytes("wlan0", (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time downlink data traffic of the cellular network. +statistics.getCellularRxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the cellular network. +statistics.getCellularTxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time downlink data traffic of the all NICs. +statistics.getAllRxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the all NICs. +statistics.getAllTxBytes((error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time downlink data traffic of the specified application. +let uid = 20010038; +statistics.getUidRxBytes(uid, (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) + +// Obtain the real-time uplink data traffic of the specified application. +let uid = 20010038; +statistics.getUidTxBytes(uid, (error, stats) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(stats)) +}) +``` + +## Obtaining Historical Traffic Data by NIC or UID + +1. Obtain the historical data traffic of the specified NIC. +2. Obtain the historical data traffic of the specified application. + +```js +let ifaceInfo = { + iface: "wlan0", + startTime: 1685948465, + endTime: 16859485670 +} +// Obtain the historical data traffic of the specified NIC. +statistics.getTrafficStatsByIface(ifaceInfo), (error, statsInfo) => { + console.log(JSON.stringify(error)) + console.log("getTrafficStatsByIface bytes of received = " + JSON.stringify(statsInfo.rxBytes)); + console.log("getTrafficStatsByIface bytes of sent = " + JSON.stringify(statsInfo.txBytes)); + console.log("getTrafficStatsByIface packets of received = " + JSON.stringify(statsInfo.rxPackets)); + console.log("getTrafficStatsByIface packets of sent = " + JSON.stringify(statsInfo.txPackets)); +}); + +let uidInfo = { + ifaceInfo: { + iface: "wlan0", + startTime: 1685948465, + endTime: 16859485670 + }, + uid: 20010037 +} +// Obtain the historical data traffic of the specified application. +statistics.getTrafficStatsByUid(uidInfo), (error, statsInfo) => { + console.log(JSON.stringify(error)) + console.log("getTrafficStatsByUid bytes of received = " + JSON.stringify(statsInfo.rxBytes)); + console.log("getTrafficStatsByUid bytes of sent = " + JSON.stringify(statsInfo.txBytes)); + console.log("getTrafficStatsByUid packets of received = " + JSON.stringify(statsInfo.rxPackets)); + console.log("getTrafficStatsByUid packets of sent = " + JSON.stringify(statsInfo.txPackets)); +}); + +``` + +## Subscribing to Traffic Change Events + +1. Subscribe to traffic change events. +2. Unsubscribe from traffic change events. + +```js + +let callback = data => { + console.log("on netStatsChange, data:" + JSON.stringify(data)); +} +// Subscribe to traffic change events. +statistics.on('netStatsChange', callback); + +// Unsubscribe from traffic change events. You can pass the callback of the **on** function if you want to unsubscribe from a certain type of event. If you do not pass the callback, you will unsubscribe from all events. +statistics.off('netStatsChange', callback); +statistics.off('netStatsChange'); + +``` diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index 77e1d8f9738d949ce9b0f0396bf66f99b9bf924e..74a44f63945d867ff76bb783e2ef0a6feb35861c 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -16,7 +16,11 @@ - [Database Backup and Restoration](data-backup-and-restore.md) - [Database Encryption](data-encryption.md) - [Access Control by Device and Data Level](access-control-by-device-and-data-level.md) -- Cross-Application Data Sharing (for System Applications Only) - - [Cross-Application Data Sharing Overview](share-device-data-across-apps-overview.md) - - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) - - [Sharing Data in Silent Access](share-data-by-silent-access.md) +- Cross-Application Data Sharing + - [Data Sharing Overview](data-share-overview.md) + - [Unified Data Definition](unified-data-definition.md) + - One-to-Many Data Sharing (for System Applications Only) + - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) + - [Silent Access via the DatamgrService](share-data-by-silent-access.md) + - Many-to-Many Data Sharing + - [Sharing Data Using Unified Data Channels](unified-data-channels.md) \ No newline at end of file diff --git a/en/application-dev/database/data-mgmt-overview.md b/en/application-dev/database/data-mgmt-overview.md index aa98d97da5acdce3a382a70d383e140463a5399a..e6b77c1d89c5cc31e6e1fb9db05e7ab8d2607a7e 100644 --- a/en/application-dev/database/data-mgmt-overview.md +++ b/en/application-dev/database/data-mgmt-overview.md @@ -3,7 +3,7 @@ ## Function -Data management provides data storage, management, and synchronization capabilities. For example, you can store the Contacts application data in database for secure management and shared access, and synchronize the contacts information with a smart watch. +Data management provides data storage, management, and synchronization capabilities. For example, you can store the Contacts application data in database for secure management and shared access, and synchronize the Contacts information with a smart watch. - Data storage: provides data persistence capabilities, which can be classified into user preferences, key-value (KV) stores, and relational database (RDB) stores by data characteristics. @@ -16,9 +16,9 @@ The database stores created by an application are saved to the application sandb ## Working Principles -The data management module includes user preferences (**Preferences**), KV data management (**KV-Store**), RDB data management (**RelationalStore**), distributed data object (**DataObject**), and cross-application data management (**DataShare**). The interface layer provides standard JavaScript APIs for application development. The Frameworks&System service layer implements storage and synchronization of component data, and provides dependencies for SQLite and other subsystems. +The data management module includes preferences, KV data management (KV-Store), relational data management (RelatoinalStore), distributed data object (DataObject), cross-application data management (DataShare), and unified data management framework (UDMF). The interface layer provides standard JavaScript APIs for application development. The Frameworks&System service layer implements storage and synchronization of component data, and provides dependencies for SQLite and other subsystems. - **Figure 1** Data management architecture +**Figure 1** Data management architecture ![dataManagement](figures/dataManagement.jpg) @@ -33,4 +33,7 @@ The data management module includes user preferences (**Preferences**), KV data - **DataShare**: provides the data provider-consumer mode to implement addition, deletion, modification, and query of cross-application data on a device, and notification subscription. **DataShare** is not bound to any database and can interact with RDB and KV stores. You can also encapsulate your own databases for C/C++ applications.
In addition to the provider-consumer mode, **DataShare** provides silent access, which allows direct access to the provider's data via the DatamgrService proxy instead of starting the provider. Currently, only the RDB stores support silent access. +- **UDMF**: defines the data language and standards for cross-application and cross-device data interaction, improving data interaction efficiency. The UDMF provides secure and standard data transmission channels and supports different levels of data access permissions and lifecycle management policies. It helps implement efficient data sharing across applications and devices. + - **DatamgrService**: implements synchronization and cross-application sharing for other components, including cross-device synchronization of **RelationalStore** and **KV-Store**, silent access to provider data of **DataShare**, and temporary storage of **DataObject** synchronization object data. + diff --git a/en/application-dev/database/data-persistence-by-rdb-store.md b/en/application-dev/database/data-persistence-by-rdb-store.md index f2bb5e2d4098bbb19b3c791ed61307ffd78f0ec3..ff37d0fdce056ca143015f39c81892c990f6545d 100644 --- a/en/application-dev/database/data-persistence-by-rdb-store.md +++ b/en/application-dev/database/data-persistence-by-rdb-store.md @@ -18,7 +18,7 @@ A relational database (RDB) store is used to store data in complex relational mo **RelationalStore** provides APIs for applications to perform data operations. With SQLite as the underlying persistent storage engine, **RelationalStore** provides SQLite database features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more. **Figure 1** Working mechanism - + ![relationStore_local](figures/relationStore_local.jpg) @@ -37,15 +37,15 @@ A relational database (RDB) store is used to store data in complex relational mo The following table lists the APIs used for RDB data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). -| API| Description| +| API| Description| | -------- | -------- | -| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains a **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| -| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| -| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| -| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** instance.| -| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** instance.| -| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| -| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| +| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains a **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| +| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| +| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| +| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** instance.| +| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** instance.| +| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| +| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| ## How to Develop @@ -53,7 +53,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP 1. Obtain an **RdbStore** instance.
Example: Stage model: - + ```js import relationalStore from '@ohos.data.relationalStore'; // Import the module. import UIAbility from '@ohos.app.ability.UIAbility'; @@ -65,7 +65,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP securityLevel: relationalStore.SecurityLevel.S1 // Database security level. }; - // The current RDB store version is 3, and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES). + // The RDB store version is 3, and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES). const SQL_CREATE_TABLE ='CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'; // SQL statement for creating a data table. relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => { @@ -106,7 +106,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP FA model: - + ```js import relationalStore from '@ohos.data.relationalStore'; // Import the module. import featureAbility from '@ohos.ability.featureAbility'; @@ -160,10 +160,12 @@ The following table lists the APIs used for RDB data persistence. Most of the AP > > - The RDB store created by an application varies with the context. Multiple RDB stores are created for the same database name with different application contexts. For example, each UIAbility has its own context. > - > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. If you want to move the files of an RDB store to another place for view, you must also move the temporary files with finename extensions **-wal** or **-shm** in the same directory. Once an application is uninstalled, the database files and temporary files generated by the application on the device are also removed. + > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. When the RDB store is used, temporary files ended with **-wal** and **-shm** may be generated in the same directory as the database file. If you want to move the database files to other places, you must also move these temporary files. After the application is uninstalled, the database files and temporary files generated on the device are also removed. -2. Use **insert()** to insert data to the RDB store. Example: - +2. Use **insert()** to insert data to the RDB store. + + Example: + ```js const valueBucket = { 'NAME': 'Lisa', @@ -177,13 +179,13 @@ The following table lists the APIs used for RDB data persistence. Most of the AP return; } console.info(`Succeeded in inserting data. rowId:${rowId}`); - }) +}) ``` - + > **NOTE** - > +> > **RelationalStore** does not provide explicit flush operations for data persistence. Data inserted by **insert()** is stored in files persistently. - + 3. Modify or delete data based on the specified **Predicates** instance. Use **update()** to modify data and **delete()** to delete data. @@ -254,13 +256,15 @@ The following table lists the APIs used for RDB data persistence. Most of the AP 5. Delete the RDB store. - Use **deleteRdbStore()** to delete the RDB store and related database files. + Use **deleteRdbStore()** to delete the RDB store and related database files. - Example: + > **NOTE** + > + > After the deletion, you are advised to set the database object to null. Stage model: - + ```js import UIAbility from '@ohos.app.ability.UIAbility'; @@ -271,6 +275,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`); return; } + store = null; console.info('Succeeded in deleting RdbStore.'); }); } @@ -279,7 +284,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP FA model: - + ```js import featureAbility from '@ohos.ability.featureAbility'; @@ -291,6 +296,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`); return; } + store = null; console.info('Succeeded in deleting RdbStore.'); }); ``` diff --git a/en/application-dev/database/data-share-overview.md b/en/application-dev/database/data-share-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..4a163dcc56a5592038cd497bddafa572a90628f7 --- /dev/null +++ b/en/application-dev/database/data-share-overview.md @@ -0,0 +1,71 @@ +# Cross-Application Data Sharing + +## Introduction + +OpenHarmony provides APIs for an application to manage its own data and share data with other applications. + +Data needs to be shared in a wealth of scenarios. For example, the Contacts, short message service (SMS), and Gallery data always needs to be shared with other applications. However, certain data, such as accounts and passwords, cannot be shared. Some data, such as SMS messages, can be queried but not modified by other applications. Therefore, a secure and efficient cross-application data sharing mechanism for different data sharing scenarios and data privacy protection is very important. + +Currently, OpenHarmony supports one-to-many and many-to-many cross-application data sharing, based on the number of the data provider applications involved. + +## Basic Concepts + +Before you start, understand the following concepts: + +- **Data provider**: an application that provides data and implements related services. It is also called the producer or server. + +- **Data consumer**: an application that accesses the data or services provided by the data provider. It is also called the client. + +- **ValuesBucket**: a set of data to be inserted. It can be one or more data records in key-value (KV) pairs. In each KV pair, the key must be of the string type, and the value can be a number, a string, a Boolean value, or an unsigned integer array. + +- **ResultSet**: a set of query results. It provides flexible modes for users to obtain various data. + +- **Predicates**: an object that specifies the conditions for updating, deleting, or querying data in a database. + +## Unified Data Definition + +When data needs to be shared among multiple applications, a large amount of data needs to be converted for data interaction because the data definition and format vary with applications. To reduce application/service data interaction costs, OpenHarmony uses the unified data definition as the unified data language to build cross-application data interaction standards. + +The unified data definition defines common data types. Applications can use the APIs provided by the Unified Data Management Framework (UDMF) to create and use these data types. For details, see [Unified Data Definition](unified-data-definition.md). + +## One-to-Many Cross-Application Data Sharing + +You can use **DataShare** to implement one-to-many data sharing across applications. Two implementation modes are provided, depending on whether the data provider is started in the cross-application data sharing. + +### Implementation + +The data provider can directly use **DataShare** to share data with other applications without complex encapsulation. The data consumer only needs to use a set of APIs because the **DataShare** access mode does not vary with the data provision mode. This greatly reduces the learning time and development difficulty. + +**DataShare** implements cross-application data sharing in either of the following ways: + +- [Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) + + You need to implement an ExtensionAbility with callbacks in the HAP. When the data consumer calls an API, the ExtensionAbility of the data provider will be automatically started to invoke the registered callback. + + You can use **DataShareExtensionAbility** when the cross-application data access involves service operations other than mere addition, deletion, modification, and query of data in databases. + +- [Using Silent Access via the DatamgrService](share-data-by-silent-access.md) + + You need to configure database access rules in the HAP. When the data consumer calls an API, the system ability automatically obtains the access rules in the HAP and returns data without starting the data provider. + + You can use this mode when the cross-application data access involves only database operations (data addition, deletion, modification, and query) or data hosted to the DatamgrService. + +If your application is signed with a system signature, you can use both methods. When data is created for the first time, use **DataShareExtensionAbility**. When data is accessed and modified later, use the **DatamgrService** to share data. That is, the data provider is started only when the data is accessed for the first time. + +### Restrictions + +- **DataShare** is subject to the limitations on the database used by the data provider. For example, the supported data models, length of the keys and values, and maximum number of databases that can be accessed at a time by each application vary with the database in use. + +- The payloads of **ValuesBucket**, **Predicates**, and **ResultSet** are restricted by IPC. + +- Currently, **dataShare** supports development based on the stage model only. + +## Many-to-Many Cross-Application Data Sharing + +In one-to-many cross-application data sharing, there is only one data provider. In many-to-many cross-application data sharing, you need to consider data definition, data exchange, and permission management. The UDMF provides a new data sharing and interaction mode to implement many-to-many cross-application data sharing. + +### Implementation + +[Sharing Data via Unified Data Channels](unified-data-channels.md) + +Applications can call the APIs provided by the UDMF to write data that complies with the unified data definition to different data sharing channels of the UDMF. The data in these channels can be read by other applications. The data written into the UDMF is managed based on the permissions of the application, permissions of the data channels, and the permission management logic of the UDMF. Lifecycle management is also performed on the data written into the channels in the same way. In this way, the data scattered in each application is aggregated via different channels of the UDMF, improving the development efficiency and data experience of users. diff --git a/en/application-dev/database/figures/dataManagement.jpg b/en/application-dev/database/figures/dataManagement.jpg index a43ca576222ad1da550242ed34c5f82700d52392..6555d34202927dc202fcb0ab233bc42740f39dbe 100644 Binary files a/en/application-dev/database/figures/dataManagement.jpg and b/en/application-dev/database/figures/dataManagement.jpg differ diff --git a/en/application-dev/database/figures/udmf_type_ADT.png b/en/application-dev/database/figures/udmf_type_ADT.png new file mode 100644 index 0000000000000000000000000000000000000000..2eb1e7b94080b6d611b1ed7abaceda31b04442e7 Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_ADT.png differ diff --git a/en/application-dev/database/figures/udmf_type_File.png b/en/application-dev/database/figures/udmf_type_File.png new file mode 100644 index 0000000000000000000000000000000000000000..80bbec073de7e4e75da239a8a073453545260cc1 Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_File.png differ diff --git a/en/application-dev/database/figures/udmf_type_SDT.png b/en/application-dev/database/figures/udmf_type_SDT.png new file mode 100644 index 0000000000000000000000000000000000000000..026ce5bd7ae68f4dbabdcf5bac63e721454e17f5 Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_SDT.png differ diff --git a/en/application-dev/database/figures/udmf_type_Text.png b/en/application-dev/database/figures/udmf_type_Text.png new file mode 100644 index 0000000000000000000000000000000000000000..d12a2390dce2d08417e7024d15ee431dde66756b Binary files /dev/null and b/en/application-dev/database/figures/udmf_type_Text.png differ diff --git a/en/application-dev/database/share-data-by-datashareextensionability.md b/en/application-dev/database/share-data-by-datashareextensionability.md index 7f70ab30d4c04c421c1e18032a0da13e590f80a7..d3c28e31c20f0aa3d6720359aa28e84af2061a63 100644 --- a/en/application-dev/database/share-data-by-datashareextensionability.md +++ b/en/application-dev/database/share-data-by-datashareextensionability.md @@ -16,8 +16,7 @@ There are two roles in **DataShare**: - Data consumer: accesses the data provided by the provider using [createDataShareHelper()](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper). -**Figure 1** Data sharing mechanism - +**Figure 1** Data sharing mechanism ![dataShare](figures/dataShare.jpg) - The **DataShareExtensionAbility** module, as the data provider, implements services related to data sharing between applications. @@ -32,7 +31,7 @@ There are two roles in **DataShare**: ## How to Develop -### Data Provider Application Development (Only for System Applications) +### Data Provider Application (Only for System Applications) [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required. @@ -146,7 +145,7 @@ override the service implementation as required. For example, if the data provid "icon": "$media:icon", "description": "$string:description_datashareextability", "type": "dataShare", - "uri": "datashare://com.samples.datasharetest.DataShare", + "uri": "datashareproxy://com.samples.datasharetest.DataShare", "exported": true, "metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}] } @@ -155,11 +154,11 @@ override the service implementation as required. For example, if the data provid **Table 2** Fields in the data_share_config.json file - | Field| Description | Mandatory| - | ------------ | ------------------------------------------------------------ | --- | - | tableConfig | Label configuration.| Yes| - | uri | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:
1. *****: indicates all databases and tables.
2. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}**: specifies a database.
3. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}/{*tableName*}**: specifies a table.
If URIs of different formats are configured, only the URI with higher priority takes effect. | Yes| - | crossUserMode | Whether data is shared by multiple users. The value **1** means to share data between multiple users, and the value **2** means the opposite. | Yes| + | Field | Description | Mandatory | + | ------------- | ---------------------------------------- | ---- | + | tableConfig | Label configuration. | Yes | + | uri | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:
- *****: indicates all databases and tables.
- **datashareproxy://{bundleName}/{moduleName}/{storeName}**: specifies a database.
- **datashareproxy://{bundleName}/{moduleName}/{storeName}/{tableName}**: specifies a table. | Yes | + | crossUserMode | Whether data is shared by multiple users.
The value **1** means to share data between multiple users, and the value **2** means the opposite. | Yes | **data_share_config.json Example** @@ -170,18 +169,18 @@ override the service implementation as required. For example, if the data provid "crossUserMode": 1 }, { - "uri": "datashare:///com.acts.datasharetest/entry/DB00", + "uri": "datashareproxy://com.acts.datasharetest/entry/DB00", "crossUserMode": 1 }, { - "uri": "datashare:///com.acts.datasharetest/entry/DB00/TBL00", + "uri": "datashareproxy://com.acts.datasharetest/entry/DB00/TBL00", "crossUserMode": 2 } ] ``` -### Data Consumer Application Development +### Data Consumer Application 1. Import the dependencies. @@ -195,7 +194,7 @@ override the service implementation as required. For example, if the data provid ```js // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). - let dseUri = ('datashare:///com.samples.datasharetest.DataShare'); + let dseUri = ('datashareproxy://com.samples.datasharetest.DataShare'); ``` 3. Create a **DataShareHelper** instance. @@ -239,3 +238,4 @@ override the service implementation as required. For example, if the data provid console.info(`dsHelper delete result:${data}`); }); ``` + diff --git a/en/application-dev/database/share-data-by-silent-access.md b/en/application-dev/database/share-data-by-silent-access.md index 50ff03f084c889a807c6caf4d7c369bfbe0d2a51..046d78b9eac73717cd16b4218f108c1a7979e54f 100644 --- a/en/application-dev/database/share-data-by-silent-access.md +++ b/en/application-dev/database/share-data-by-silent-access.md @@ -1,19 +1,40 @@ -# Data Sharing Through Silent Access +# Silent Access via the DatamgrService ## When to Use -In a typical cross-application data access scenario, an application may be started multiple times. +In a typical cross-application data access scenario, the data provider may be started multiple times. -To reduce the number of application startup times and improve the access speed, OpenHarmony provides the silent access feature, which allows direct access to the database without starting the data provider. +To reduce the number of startup times of the data provider and improve the access speed, OpenHarmony provides the silent access feature, which allows access to the database without starting the data provider. -Silent access supports only basic database access. If service processing is required, implement service processing in the data consumer. +In silent data access, the DatamgrService accesses and modifies data without starting the data provider. -If the service processing is complex, use **DataShareExtensionAbility** to start the data provider. +The DatamgrService supports basic database access or data hosting only. If service processing is required, the service processing needs to be encapsulated into APIs for the data consumer to call. + +If the service processing is too complex to be processed by the data consumer, use **DataShareExtensionAbility** to start the data provider. ## Working Principles +The DatamgrService can serve as a proxy to access the following types of data: + +- Persistent data + + Persistent data belongs to the database of the data provider. It is stored in the sandbox of the data provider and can be shared in declaration mode by the data provider. Persistent data is configured as data tables for access. + + +- Process data + + The process data managed by the **DatamgrService** is stored in the DatamgrService sandbox in JSON or byte format. This type of data is automatically deleted 10 days after no subscription. + + +| Type | Storage Location | Data Format | Validity Period | Application Scenario | +| ----- | --------- | ----------- | ------------ | --------------------------------- | +| Persistent data| Sandbox of the data provider | Tables in the database | Permanent storage | RDB data applications, such as schedules and conferences. | +| Process data | DatamgrService sandbox| JSON or byte| Automatically deleted 10 days after no subscription| Applications featuring simple and time-sensitive data, such as step count, weather, and heart rate.| + + + **Figure 1** Silent access ![silent_dataShare](figures/silent_dataShare.jpg) @@ -21,26 +42,271 @@ If the service processing is complex, use **DataShareExtensionAbility** to start - In silent access, **DatamgrService** obtains the access rules configured by the data provider through directory mapping, performs preprocessing based on rules, and accesses the database. - To use silent access, the URIs must be in the following format: - datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}?Proxy=true + +datashareproxy://{bundleName}/{dataPath} + +The **DatamgrService** obtains the data provider application based on **bundleName**, reads the configuration, verifies the permission, and accesses data. + + **dataPath** identifies the data. It can be customized and must be unique in the same data provider application. + - "Proxy=true" means to access data without starting the data provider. If **Proxy** is not set to **true**, the data provider is started. +## Constraints - The **DatamgrService** obtains the data provider application based on **bundleName**, reads the configuration, verifies the permission, and accesses data. +- Currently, only the RDB stores support silent data access. +- The system supports a maximum of 16 concurrent query operations. Excess query requests need to be queued for processing. +- The proxy is not allowed to create a database for persistent data. To create a database, you must start the data provider. +- If the data provider is an application with a normal signature, the data read/write permission must be system_basic or higher. -## Constraints +## Available APIs -- Currently, only RDB stores support silent access. +The following table lists the APIs for silent data access. Most of the APIs are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [Data Sharing](../reference/apis/js-apis-data-dataShare.md). -- The system supports a maximum of 16 concurrent query operations. Excess query requests need to be queued for processing. +### Common API + +| API | Description | +| ---------------------------------------- | -------------------- | +| createDataShareHelper(context: Context, uri: string, options: DataShareHelperOptions, callback: AsyncCallback<DataShareHelper>): void | Creates a **DataShareHelper** instance.| + +### APIs for Persistent Data + +| API | Description | +| ---------------------------------------- | -------------------- | +| insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | Inserts a row of data into a table. | +| delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database. | +| query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data in the database. | +| update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database. | +| addTemplate(uri: string, subscriberId: string, template: Template): void | Adds a data template with the specified subscriber. | +| on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult | Subscribes to the changes of the data corresponding to the specified URI and template.| + +### APIs for Process Data + +| API | Description | +| ---------------------------------------- | ------------------ | +| publish(data: Array<PublishedItem>, bundleName: string, version: number, callback: AsyncCallback<Array<OperationResult>>): void | Publish data to the **DatamgrService**.| +| on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> | Subscribes to changes of the published data. | + + + +## Implementation of the Persistence Data + +The following describes how to share an RDB store. + +### Data Provider Application + +1. In the **module.json5** file, set the ID, read/write permissions, and basic information of the table to be shared under **proxyDatas**. + + **Table 1** Fields of proxyDatas in module.json5 + + | Field | Description | Mandatory | + | ----------------------- | ---------------------------------------- | ---- | + | uri | URI of the data, which is the unique identifier for cross-application data access. | Yes | + | requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md). | No | + | requiredWritePermission | Permission required for modifying data from the data proxy. If this parameter is not set, other applications are not allowed to modify the data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md). | No | + | metadata | Data source information, including the **name** and **resource** fields.
The **name** field identifies the configuration, which has a fixed value of **dataProperties**.
The value of **resource** is **$profile:{fileName}**, indicating that the name of the configuration file is **{fileName}.json**.| Yes | + + **module.json5 example** + + ```json + "proxyDatas":[ + { + "uri": "datashareproxy://com.acts.ohos.data.datasharetest/test", + "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "metadata": { + "name": "dataProperties", + "resource": "$profile:my_config" + } + } + ] + ``` + **Table 2** Fields in my_config.json + + | Field | Description | Mandatory | + | ----- | ---------------------------------------- | ---- | + | path | Data source path, in the **Database_name/Table_name** format. Currently, only RDB stores are supported. | Yes | + | type | Database type. Currently, only **rdb** is supported. | Yes | + | scope | Scope of the database.
- **module** indicates that the database is located in this module.
- **application** indicates that the database is located in this application.| No | + + **my_config.json example** + + ```json + { + "path": "DB00/TBL00", + "type": "rdb", + "scope": "application" + } + ``` + +### Data Consumer Application + + +1. Import dependencies. + + ```js + import dataShare from '@ohos.data.dataShare'; + import dataSharePredicates from '@ohos.data.dataSharePredicates'; + ``` + +2. Define the URI string for communicating with the data provider. + + ```js + let dseUri = ('datashareproxy://com.acts.ohos.data.datasharetest/test'); + ``` + +3. Create a **DataShareHelper** instance. + + ```js + let dsHelper; + let abilityContext; + + export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + abilityContext = this.context; + dataShare.createDataShareHelper(abilityContext, "", { + isProxy: true + }, (err, data) => { + dsHelper = data; + }); + } + } + ``` + +4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. + + ```js + // Construct a piece of data. + let valuesBucket = { + 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) + }; + let updateBucket = { + 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) + }; + let predicates = new dataSharePredicates.DataSharePredicates(); + let valArray = ['*']; + // Insert a piece of data. + dsHelper.insert(dseUri, valuesBucket, (err, data) => { + console.info(`dsHelper insert result:${data}`); + }); + // Update data. + dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { + console.info(`dsHelper update result:${data}`); + }); + // Query data. + dsHelper.query(dseUri, predicates, valArray, (err, data) => { + console.info(`dsHelper query result:${data}`); + }); + // Delete data. + dsHelper.delete(dseUri, predicates, (err, data) => { + console.info(`dsHelper delete result:${data}`); + }); + ``` + +5. Subscribe to the specified data. + + ```js + function onCallback(err, node: dataShare.RdbDataChangeNode) { + console.info("uri " + JSON.stringify(node.uri)); + console.info("templateId " + JSON.stringify(node.templateId)); + console.info("data length " + node.data.length); + for (let i = 0; i < node.data.length; i++) { + console.info("data " + node.data[i]); + } + } + + let template = { + predicates: { + "p1": "select * from TBL00", + "p2": "select name from TBL00", + }, + scheduler: "" + } + dsProxyHelper.addTemplate(dseUri, "111", template); + let templateId: dataShare.TemplateId = { + subscriberId: "111", + bundleNameOfOwner: "com.acts.ohos.data.datasharetestclient" + } + // When the DatamgrService modifies data, onCallback is invoked to return the data queried based on the rules in the template. + let result: Array = dsProxyHelper.on("rdbDataChange", [dseUri], templateId, onCallback); + ``` + +## Implementation of the Process Data + +The following describes how to host process data. + +### (Optional) Data Provider Application + +In the **module.json5** file of the data provider, set the process data ID, read/write permissions, and basic information under **proxyDatas**. + +> **NOTE** +> +> - This step is optional. +> - If **proxyDatas** is not configured, the hosted data cannot be accessed by other applications. +> - If **proxyDatas** is not configured, you do not need to use the full data path. For example, you can use **weather** instead of **datashareproxy://com.acts.ohos.data.datasharetest/weather** when publishing, subscribing to, and querying data. + +**Table 3** Fields of proxyDatas in module.json5 + +| Field | Description | Mandatory | +| ----------------------- | ----------------------------- | ---- | +| uri | URI of the data, which is the unique identifier for cross-application data access. | Yes | +| requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md).| No | +| requiredWritePermission | Permission required for modifying data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the supported permissions, see [Application Permission List](../security/permission-list.md).| No | + +**module.json5 example** + +```json +"proxyDatas": [ + { + "uri": "datashareproxy://com.acts.ohos.data.datasharetest/weather", + "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } +] +``` + +### Data Consumer Application + +1. Import dependencies. + + ```js + import dataShare from '@ohos.data.dataShare'; + ``` + +2. Create a **DataShareHelper** instance. + + ```js + let dsHelper; + let abilityContext; -- A proxy cannot be used to create a database. If a database needs to be created, the data provider must be started. + export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + abilityContext = this.context; + dataShare.createDataShareHelper(abilityContext, "", {isProxy : true}, (err, data) => { + dsHelper = data; + }); + } + } + ``` +3. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. -## How to Develop + ```js + // Construct two pieces of data. The first data is not configured with proxyDatas and cannot be accessed by other applications. + let data : Array = [ + {key:"city", subscriberId:"11", data:"xian"}, + {key:"datashareproxy://com.acts.ohos.data.datasharetest/weather", subscriberId:"11", data:JSON.stringify("Qing")}]; + // Publish data. + let result: Array = await dsProxyHelper.publish(data, "com.acts.ohos.data.datasharetestclient"); + ``` -The URI must be in the following format: +4. Subscribe to the specified data. -datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}?Proxy=true + ```js + function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) { + console.info("onPublishCallback"); + } + let uris:Array = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/weather"]; + let result: Array = dsProxyHelper.on("publishedDataChange", uris, "11", onPublishCallback); + ``` -For details about the development procedure and implementation, see [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md). + diff --git a/en/application-dev/database/sync-app-data-across-devices-overview.md b/en/application-dev/database/sync-app-data-across-devices-overview.md index c2f6361786325ccd753aa8fa4afa3446d37b6e89..4a3543a44c2b9e6e7fa9a4248010254c6ce1b035 100644 --- a/en/application-dev/database/sync-app-data-across-devices-overview.md +++ b/en/application-dev/database/sync-app-data-across-devices-overview.md @@ -7,7 +7,7 @@ The distributed application data synchronization allows the data of an applicati For example, when data is added, deleted, or modified for an application on a device, the same application on another device can obtain the updated data. You can use this feature in the distributed Gallery, Notepad, Contacts, and File Manager. -For details about how to subscribe to database change notifications between different applications, see [Sharing Application Data with Other Applications](share-device-data-across-apps-overview.md). +For details about how to subscribe to database change notifications between different applications, see [Cross-Application Data Sharing](data-share-overview.md). The data storage modes vary depending on the lifecycle of data to be synchronized: @@ -24,7 +24,7 @@ In a distributed scenario, cross-device collaboration demands consistent data be The data consistency can be classified into the following types: -- Strong consistency: When data is inserted, deleted, or modified on a device, other devices in the same network can obtain the updates eventually, but may not immediately. +- Strong consistency: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately. Once data is modified, the devices can read the updated data eventually, but may not read the updated data immediately. - Weak consistency: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the updates. The data on these devices may be inconsistent after a certain period of time. diff --git a/en/application-dev/database/unified-data-channels.md b/en/application-dev/database/unified-data-channels.md new file mode 100644 index 0000000000000000000000000000000000000000..b31b9532eafb700da67c2dbcc5464f8f58867d23 --- /dev/null +++ b/en/application-dev/database/unified-data-channels.md @@ -0,0 +1,165 @@ +# Sharing Data via Unified Data Channels + + +## When to Use + +In many-to-many data sharing across applications, a data channel needs to be provided to access data of different applications and share the data with other applications. + +The Unified Data Management Framework (UDMF) provides unified data channels and standard data access interfaces for different service scenarios of many-to-many cross-application data sharing. + +## Definition and Implementation of Unified Data Channels + +The unified data channel provides cross-application data access for various service scenarios. It can temporarily store the unified data objects to be shared by an application, and manage the access permissions and lifecycle of the data according to certain policies. + +The unified data channel is implemented by the system ability provided by the UDMF. When an application (data provider) needs to share data, it calls the **insert()** method provided by the UDMF to write the data to the UDMF data channel, and calls UDMF **update()** or **delete()** to update or delete the data. After passing the permission verification, the target application (data consumer) calls the UDMF **read()** to access the data. After the data is read, the UDMF performs lifecycle management of the data. + +The unified data object (**UnifiedData**) is uniquely identified by a URI in the UDMF data channel. The URI is in the **udmf://*intention*/*bundleName*/*groupId*** format, where: + ++ **udmf**: protocol used to provide the data channel. + ++ *intention*: an enum of the data channel types supported by the UDMF. + ++ *bundleName*: bundle name of the data source application. + ++ *groupId*: group ID used for batch data management. + +Currently, the UDMF provides the public data channel for cross-application data sharing. + +**Public data channel**: allows applications to write and read data. The corresponding **intention** is **DATA_HUB**. + +## Available APIs + +The following table lists the UDMF APIs. All of them are executed asynchronously in callback or promise mode. In the following table, callback-based APIs are used as an example. For more information about the APIs, see [UDMF](../reference/apis/js-apis-data-udmf.md). + +| API | Description | +|-----------------------------------------------------------------------------------------|---------------------------------------------| +| insertData(options: Options, data: UnifiedData, callback: AsyncCallback\): void | Inserts data to the UDMF public data channel. A unique data identifier is returned.| +| updateData(options: Options, data: UnifiedData, callback: AsyncCallback\): void | Updates the data in the UDMF public data channel. | +| queryData(options: Options, callback: AsyncCallback\>): void | Queries data in the UDMF public data channel. | +| deleteData(options: Options, callback: AsyncCallback\>): void | Deletes data from the UDMF public data channel. The deleted data set is returned.| + + +## How to Develop + +The following example describes how to implement many-to-many data sharing. The data provider writes data to the UMDF public data channel, and updates and deletes the data. The data consumer obtains the data shared by the data provider. + +### Data Provider + +1. Import the **@ohos.data.UDMF** module. + + ```ts + import UDMF from '@ohos.data.UDMF'; + ``` +2. Create a **UnifiedData** object and insert it into the UDMF public data channel. + + ```ts + let plainText = new UDMF.PlainText(); + plainText.textContent = 'hello world!'; + let unifiedData = new UDMF.UnifiedData(plainText); + + // Specify the type of the data channel to which the data is to be inserted. + let options = { + intention: UDMF.Intention.DATA_HUB + } + try { + UDMF.insertData(options, unifiedData, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in inserting data. key = ${data}`); + } else { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` +3. Update the **UnifiedData** object inserted. + + ```ts + let plainText = new UDMF.PlainText(); + plainText.textContent = 'How are you!'; + let unifiedData = new UDMF.UnifiedData(plainText); + + // Specify the URI of the UnifiedData object to update. + let options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' + }; + + try { + UDMF.updateData(options, unifiedData, (err) => { + if (err === undefined) { + console.info('Succeeded in updating data.'); + } else { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` +4. Delete the **UnifiedData** object from the UDMF public data channel. + + ```ts + // Specify the type of the data channel whose data is to be deleted. + let options = { + intention: UDMF.Intention.DATA_HUB + }; + + try { + UDMF.deleteData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { + let text = (records[j]); + console.info(`${i + 1}.${text.textContent}`); + } + } + } + } else { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` + +### Data Consumer + +1. Import the **@ohos.data.UDMF** module. + + ```ts + import UDMF from '@ohos.data.UDMF'; + ``` +2. Query the **UnifiedData** object in the UDMF public data channel. + + ```ts + // Specify the type of the data channel whose data is to be queried. + let options = { + intention: UDMF.Intention.DATA_HUB + }; + + try { + UDMF.queryData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) { + let text = (records[j]); + console.info(`${i + 1}.${text.textContent}`); + } + } + } + } else { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + } + }); + } catch(e) { + console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + } + ``` diff --git a/en/application-dev/database/unified-data-definition.md b/en/application-dev/database/unified-data-definition.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a3c100b5dadff7ef56a0938cde5b4d98b489d4 --- /dev/null +++ b/en/application-dev/database/unified-data-definition.md @@ -0,0 +1,125 @@ +# Unified Data Definition + + +## When to Use + +To streamline cross-application data interaction of OpenHarmony and minimize the application/service data interaction costs, the Unified Data Management Framework (UDMF) provides standard data definitions to define common data types. Applications can use the APIs provided by the UDMF to create and use these data types. + + +## Unified Data Types + +The UDMF provides the following unified data types: + +**Basic data types**
Basic data types include File and Text, which can be used for cross-application and cross-platform data interaction. Figure 1 and Figure 2 illustrate the basic data types. + +**Figure 1** UDMF File + +![UDMF_FILE](figures/udmf_type_File.png) + +Figure 2 UDMF Text + +![UDMF_TEXT](figures/udmf_type_Text.png) + +**System Defined Types (SDTs)**
The SDTs are specific to the platform or operating system, such as Form (UI card information), AppItem (app description information), and PixelMap (thumbnail). This type of data can be used for cross-application data interaction in a system or platform. Figure 3 illustrates the SDT data. + +**Figure 3** UDMF SDT data + +![UDMF_SDT](figures/udmf_type_SDT.png) + +**App Defined Type (ADT)**
The SDT data is application-specific. This type of data can be used for across-platform data interaction for an application. As shown in Figure 4, the MyFile file format can be defined for use in an application ecosystem. + +**Figure 4** UDMF ADT data + +![UDMF_ADT](figures/udmf_type_ADT.png) + +## Restrictions + +- The size of each data record in the UDMF cannot exceed 2 MB. +- The UDMF supports data group management. The size of each group cannot exceed 4 MB. + +## Available APIs + +The UDMF provides the unified data object **UnifiedData** to encapsulate a group of data records **UnifiedRecord**. **UnifiedRecord** is an abstract definition of data content supported by the UDMF, for example, a text record or an image record. The data content type in a data record corresponds to **UnifiedDataType**. + +The following table describes common UDMF APIs. For more information, see [UDMF](../reference/apis/js-apis-data-udmf.md). + +| Class | API | Description | +|---------------|-------------------|-----------------------------------------------------------------------------------------------| +| UnifiedRecord | getType(): string | Obtains the data type of this data record.| +| UnifiedData | constructor(record: UnifiedRecord) | A constructor used to create a **UnifiedData** object with a data record. | +| UnifiedData | addRecord(record: UnifiedRecord): void | Adds a data record to this **UnifiedRecord** object. | +| UnifiedData | getRecords(): Array\ | Obtains all data records from this **UnifiedData** object. The data obtained is of the **UnifiedRecord** type. You need to obtain the data type by using **getType** and convert the data type to a child class before using it.| + + +## How to Develop + +The following describes how to create a **UnifiedData** object containing two data records: image and plain text. + +1. Import the **@ohos.data.UDMF** module. + + ```ts + import UDMF from '@ohos.data.UDMF'; + ``` +2. Create an image data record and initialize the **UnifiedData** object with the image data record. + + (1) Create an image data record. + + ```ts + let image = new UDMF.Image(); + ``` + + (2) Modify object attributes. + + ```ts + // The Image object contains the imageUri attribute. + image.imageUri = '...'; + ``` + + (3) Access the object attributes. + + ```ts + console.info(`imageUri = ${image.imageUri}`); + ``` + + (4) Create a **UnifiedData** instance. + + ```ts + let unifiedData = new UDMF.UnifiedData(image); + ``` +3. Create a plain text data record and add it to the **UnifiedData** instance created. + + ```ts + let plainText = new UDMF.PlainText(); + plainText.textContent = 'this is textContent of plainText'; + plainText.abstract = 'abstract of plainText'; + plainText.details = { + plainKey1: 'plainValue1', + plainKey2: 'plainValue2', + }; + unifiedData.addRecord(plainText); + ``` +4. Obtain all data records in this **UnifiedData** instance. + + ```ts + let records = unifiedData.getRecords(); + ``` +5. Traverse each record, determine the data type of the record, and convert the record into a child class object to obtain the original data record. + + ```ts + for (let i = 0; i < records.length; i ++) { + // Read the type of the data record. + let type = records[i].getType(); + switch (type) { + case UDMF.UnifiedDataType.IMAGE: + // Convert the data to obtain the original image data record. + let image = (records[i]); + break; + case UDMF.UnifiedDataType.PLAIN_TEXT: + // Convert the data to obtain the original text record. + let plainText = (records[i]); + break; + default: + break; + } + } + ``` diff --git a/en/application-dev/device/Readme-EN.md b/en/application-dev/device/Readme-EN.md index 6ce8d1b16951d5fb739d97c102cb8d3be3f628d7..54b4e3d3da968f496f1a0a5ff6698e8459dcb58c 100644 --- a/en/application-dev/device/Readme-EN.md +++ b/en/application-dev/device/Readme-EN.md @@ -19,3 +19,5 @@ - [Sample Server Development](sample-server-guidelines.md) - Stationary - [Stationary Development](stationary-guidelines.md) +- Peripheral + - [Peripheral Management Development](externaldevice-guidelines.md) diff --git a/en/application-dev/device/externaldevice-guidelines.md b/en/application-dev/device/externaldevice-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..134f402f3b163d641746fec177a5b99709299279 --- /dev/null +++ b/en/application-dev/device/externaldevice-guidelines.md @@ -0,0 +1,103 @@ +# Peripheral Management Development + + +## When to Use + +Peripheral devices (or simply peripherals) are auxiliary devices connected to a device through physical ports, such as handwriting tablets, printers, and scanners. Applications can query and bind peripherals by using the peripheral management capabilities, so that the device can use the customized capabilities provided by the peripheral drivers, such as the printer software. + + +## Available APIs + +The following table lists the open capabilities of peripheral management. For more information, see [Peripheral Management](../reference/apis/js-apis-driver-deviceManager.md). + +**Table 1** Open APIs for peripheral management + +| API | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| queryDevices(busType?: number): Array<Readonly<Device>> | Queries the peripheral list. | +| bindDevice(deviceId: number, onDisconnect: AsyncCallback<number>, callback: AsyncCallback<{deviceId: number, remote: rpc.IRemoteObject}>): void | Binds a peripheral device. This API uses an asynchronous callback to return the result. If the peripheral device is bound, the **IRemoteObject** of the device driver is returned for subsequent interaction with the device driver.| +| bindDevice(deviceId: number, onDisconnect: AsyncCallback<number>): Promise<{deviceId: number, remote: rpc.IRemoteObject}> | Binds a peripheral device. This API uses a promise to return the result. | +| unbindDevice(deviceId: number, callback: AsyncCallback<number>): void | Unbinds a peripheral device. This API uses an asynchronous callback to return the result. | +| unbindDevice(deviceId: number): Promise<number> | Unbinds a peripheral device. This API uses a promise to return the result. | + + +## How to Develop + +You can use the APIs to query and bind peripheral devices so as to use the customized driver capabilities of the peripherals. The development procedure is as follows: + + +1. Query the peripheral device list. + + ```js + var matchDevice; + try { + let devices = deviceManager.queryDevices(deviceManager.BusType.USB); + for (let item of devices) { + let device = item as deviceManager.USBDevice; + // Match the USB device based on productId and vendorId. + if (device.productId == 1234 && device.vendorId === 2345) { + matchDevice = device; + break; + } + } + } catch (error) { + console.error('Failed to query device. Code is ${error.code}, message is ${error.message}'); + } + if (!matchDevice) { + console.error('No match device'); + return; + } + ``` + +2. Bind a peripheral device. + + ```js + var remoteObject; + try { + deviceManager.bindDevice(matchDevice.deviceId, (error, data) => { + console.error('Device is disconnected'); + }, (error, data) => { + if (error) { + console.error('bindDevice async fail. Code is ${error.code}, message is ${error.message}'); + return; + } + console.info('bindDevice success'); + remoteObject = data.remote; + }); + } catch (error) { + console.error('bindDevice fail. Code is ${error.code}, message is ${error.message}'); + } + ``` + +3. Use the capabilities provided by the peripheral device driver. + + ```js + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let repy = rpc.MessageSequence.create(); + data.writeString('hello'); + let code = 1; + // The code and data content varies depending on the interface provided by the driver. + remoteObject.sendMessageRequest(code, data, reply, option) + .then(result => { + console.info('sendMessageRequest finish.'); + }).catch(error => { + console.error('sendMessageRequest fail. code:' + error.code); + }); + ``` + +4. Unbind the peripheral device after the device is used. + + ```js + try { + deviceManager.unbindDevice(matchDevice.deviceId, (error, data) => { + if (error) { + console.error('unbindDevice async fail. Code is ${error.code}, message is ${error.message}'); + return; + } + console.info('unbindDevice success'); + }); + } catch (error) { + console.error('unbindDevice fail. Code is ${error.code}, message is ${error.message}'); + } + ``` diff --git a/en/application-dev/faqs/faqs-arkui-arkts.md b/en/application-dev/faqs/faqs-arkui-arkts.md index 30372ac1e4f810f87e225b397b2aa5f95208ed0c..4cae24c691f9dab62d4c3452f32f69d3cf5b0da0 100644 --- a/en/application-dev/faqs/faqs-arkui-arkts.md +++ b/en/application-dev/faqs/faqs-arkui-arkts.md @@ -760,147 +760,6 @@ Text in the **\** component is centered by default. You do not need to set [Text](../reference/arkui-ts/ts-basic-components-text.md#example-1) -## How do I set the controlButton attribute for the \ component? - -Applicable to: OpenHarmony 3.2 Beta5 (API version 9) - -**Solution** - -The sample code is as follows: - -``` -@Entry -@Component -struct SideBarContainerExample { - normalIcon : Resource = $r("app.media.icon") - selectedIcon: Resource = $r("app.media.icon") - @State arr: number[] = [1, 2, 3] - @State current: number = 1 - - build() { - SideBarContainer(SideBarContainerType.Embed) - { - Column() { - ForEach(this.arr, (item, index) => { - Column({ space: 5 }) { - Image(this.current === item ? this.selectedIcon : this.normalIcon).width(64).height(64) - Text("Index0" + item) - .fontSize(25) - .fontColor(this.current === item ? '#0A59F7' : '#999') - .fontFamily('source-sans-pro,cursive,sans-serif') - } - .onClick(() => { - this.current = item - }) - }, item => item) - }.width('100%') - .justifyContent(FlexAlign.SpaceEvenly) - .backgroundColor('#19000000') - - - Column() { - Text('SideBarContainer content text1').fontSize(25) - Text('SideBarContainer content text2').fontSize(25) - } - .margin({ top: 50, left: 20, right: 30 }) - } - .sideBarWidth(150) - .minSideBarWidth(50) - .controlButton({left:32, - top:32, - width:32, - height:32, - icons:{shown: $r("app.media.icon"), - hidden: $r("app.media.icon"), - switching: $r("app.media.icon")}}) - .maxSideBarWidth(300) - .onChange((value: boolean) => { - console.info('status:' + value) - }) - } -} -``` - -## How do I implement the dragging feature for the \ component? - -Applicable to: OpenHarmony 3.2 Beta5 (API version 9) - -**Solution** - -1. Set the **editMode\(true\)** attribute of the **\** component to specify whether the component enters the editing mode. In the editing mode, you can drag grid items. -2. Set the image displayed during dragging in the [onItemDragStart](../reference/arkui-ts/ts-container-grid.md#events) callback. -3. Obtain the drag start position and drag insertion position from the [onItemDrop](../reference/arkui-ts/ts-container-grid.md#events) callback, and complete the array position exchange logic in the [onDrag](../reference/arkui-ts/ts-universal-events-drag-drop.md#events) callback. The sample code is as follows: - - ``` - @Entry - @Component - struct GridExample { - @State numbers: String[] = [] - scroller: Scroller = new Scroller() - @State text: string = 'drag' - - @Builder pixelMapBuilder () { // Drag style - Column() { - Text(this.text) - .fontSize(16) - .backgroundColor(0xF9CF93) - .width(80) - .height(80) - .textAlign(TextAlign.Center) - } - } - - aboutToAppear() { - for (let i = 1;i <= 15; i++) { - this.numbers.push(i + '') - } - } - - changeIndex(index1: number, index2: number) {// Exchange the array item position. - [this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]]; - } - - build() { - Column({ space: 5 }) { - Grid(this.scroller) { - ForEach(this.numbers, (day: string) => { - GridItem() { - Text(day) - .fontSize(16) - .backgroundColor(0xF9CF93) - .width(80) - .height(80) - .textAlign(TextAlign.Center) - .onTouch((event: TouchEvent) => { - if (event.type === TouchType.Up) { - this.text = day - } - }) - } - }) - } - .columnsTemplate('1fr 1fr 1fr') - .columnsGap(10) - .rowsGap(10) - .onScrollIndex((first: number) => { - console.info(first.toString()) - }) - .width('90%') - .backgroundColor(0xFAEEE0) - .height(300) - .editMode(true) // Set whether the grid enters the editing mode. In the editing mode, you can drag grid items. - .onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged. - return this.pixelMapBuilder() // Set the image displayed during dragging. - }) - .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid. - console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item; insertIndex indicates the index of the position to which the dragged item will be dropped. - this.changeIndex(itemIndex, insertIndex) - }) - }.width('100%').margin({ top: 5 }) - } - } - ``` - ## Which API is used for URL encoding? diff --git a/en/application-dev/faqs/faqs-arkui-component.md b/en/application-dev/faqs/faqs-arkui-component.md index 0bb884119bda149effc09337d957ccd2231bf1c7..a61d4cb828cc8cab4b8a4636adbf66729caba10b 100644 --- a/en/application-dev/faqs/faqs-arkui-component.md +++ b/en/application-dev/faqs/faqs-arkui-component.md @@ -1,10 +1,10 @@ # ArkUI Component Development (ArkTS) -## Can custom dialog boxes be defined or used in .ts files? +## Can custom dialog boxes be defined and used in .ts files? Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -Unfortunately, no. ArkTS syntax is required for defining and initializing custom dialog boxes. Therefore, they can be defined and used only in .ets files. +Unfortunately not. Custom dialog boxes require ArkTS syntax for definition and initialization. Therefore, they can be defined and used only in .ets files. **Reference** @@ -245,8 +245,8 @@ When a custom dialog box contains a child component whose area size can be chang **Solution** -- Method 1: Use the default style of the custom dialog box. In this case, the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height. -- Method 2: Use a custom style of the custom dialog box. In this case, the dialog box automatically adapts its width and height to the child components. +- Method 1: Set the custom dialog box to the default style. In this style, the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height. +- Method 2: Set the custom dialog box to a custom style. In this style, the dialog box automatically adapts its width and height to the child components. **Reference** @@ -685,3 +685,64 @@ You can use **focusControl.requestFocus** to control the focus of the text input **Reference** [Focus Control](../reference/arkui-ts/ts-universal-attributes-focus.md) + +## How do I set the controlButton attribute for the \ component? + +Applicable to: OpenHarmony 3.2 Beta5 (API version 9) + +**Solution** + +Refer to the following sample code: + +``` +@Entry +@Component +struct SideBarContainerExample { + normalIcon : Resource = $r("app.media.icon") + selectedIcon: Resource = $r("app.media.icon") + @State arr: number[] = [1, 2, 3] + @State current: number = 1 + + build() { + SideBarContainer(SideBarContainerType.Embed) + { + Column() { + ForEach(this.arr, (item, index) => { + Column({ space: 5 }) { + Image(this.current === item ? this.selectedIcon : this.normalIcon).width(64).height(64) + Text("Index0" + item) + .fontSize(25) + .fontColor(this.current === item ? '#0A59F7' : '#999') + .fontFamily('source-sans-pro,cursive,sans-serif') + } + .onClick(() => { + this.current = item + }) + }, item => item) + }.width('100%') + .justifyContent(FlexAlign.SpaceEvenly) + .backgroundColor('#19000000') + + + Column() { + Text('SideBarContainer content text1').fontSize(25) + Text('SideBarContainer content text2').fontSize(25) + } + .margin({ top: 50, left: 20, right: 30 }) + } + .sideBarWidth(150) + .minSideBarWidth(50) + .controlButton({left:32, + top:32, + width:32, + height:32, + icons:{shown: $r("app.media.icon"), + hidden: $r("app.media.icon"), + switching: $r("app.media.icon")}}) + .maxSideBarWidth(300) + .onChange((value: boolean) => { + console.info('status:' + value) + }) + } +} +``` diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md index f512a935bae109a31ae3ea1b530608c5dadf6864..f976a47e09917c74f143a5cd84f3e7824825dc47 100644 --- a/en/application-dev/file-management/Readme-EN.md +++ b/en/application-dev/file-management/Readme-EN.md @@ -19,6 +19,12 @@ - Selecting and Saving User Files (FilePicker) - [Selecting User Files](select-user-file.md) - [Saving User Files](save-user-file.md) + - Album Management (photoAccessHelper) + - [photoAccessHelper Overview](photoAccessHelper-overview.md) + - [Media Asset (Image and video) Management](photoAccessHelper-resource-guidelines.md) + - [User Album Management](photoAccessHelper-userAlbum-guidelines.md) + - [System Album Management](photoAccessHelper-systemAlbum-guidelines.md) + - [Media Asset Change Notification Management](photoAccessHelper-notify-guidelines.md) - [Developing a FileManager Application (for System Applications Only)](dev-user-file-manager.md) - [Managing External Storage Devices (for System Applications Only)](manage-external-storage.md) - Distributed File System diff --git a/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..6e85789e72b92b991a654482a232100017cc0cbd --- /dev/null +++ b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md @@ -0,0 +1,200 @@ +# Media Asset (Image, Video, and Album) Change Notification Management + +The **photoAccessHelper** module provides APIs for listening for media asset changes. + +> **NOTE** +> +> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. +> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. + +The APIs related to media asset change notifications can be called asynchronously only in callback mode. This topic describes how to use some APIs. For more information about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). +Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. + +## Listening for the Specified URI + +Use [registerChange](../reference/apis/js-apis-photoAccessHelper.md#registerchange) to listen for the specified URI. When the observed object changes, the value of the listener callback will be returned. + +### Registering a Listener for a File Asset + +Registers a listener for the specified file asset. When the observed file asset changes, the listener callback will be invoked to return the change. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Register a listener for an image. When the image is favorited, the listener callback will be invoked. + +**How to Develop** + +1. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). +2. Register a listener for the media asset obtained. +3. Add the media asset to **Favorites**. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + + let onCallback = (changeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(fileAsset.uri, false, onCallback); + + await fileAsset.favorite(true); + fetchResult.close(); +} catch (err) { + console.error('onCallback failed with err: ' + err); +} +``` + +### Registering a Listener for an Album + +Registers a listener for an album. When the observed album changes, the listener callback will be invoked to return the change. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Register a listener for a user album. When the album is renamed, the listener callback will be invoked. + +**How to Develop** + +1. [Obtain the user album](photoAccessHelper-userAlbum-guidelines.md#obtaining-a-use-album]. +2. Register a listener for the user album. +3. Rename the user album. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +predicates.equalTo(albumName, 'albumName'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); + console.info('getAlbums successfullyfully, albumName: ' + album.albumUri); + + let onCallback = (changeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(album.albumUri, false, onCallback); + + album.albumName = 'newAlbumName' + Date.now(); + await album.commitModify(); + fetchResult.close(); +} catch (err) { + console.error('onCallback failed with err: ' + err); +} +``` + +## Fuzzy Listening + +You can set **forChildUris** to **true** to register fuzzy listening. When **uri** is an album URI, the value **true** of **forChildUris** listens for the changes of the files in the album, and the value **false** listens for only the changes of the album itself.
If **uri** is the URI of a **fileAsset**, there is no difference between **true** and **false** for **forChildUris**.
If **uri** is **DefaultChangeUri**, **forChildUris** must be set to **true**. If **forChildUris** is **false**, the URI cannot be found and no message can be received. + +### Registering a Listener for All FileAssets + +Register listening for all FileAssets. When an observed FileAsset changes, the listener callback will be invoked. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Register a listener for all FileAssets. When an observed FileAsset is favorited, the listener callback will be invoked. + +**How to Develop** + +1. Register a listener for all FileAssets. +2. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). +3. Add the media asset obtained to **Favorites**. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let onCallback = (changeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); +} +phAccessHelper.registerChange(photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback); + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + await fileAsset.favorite(true); + fetchResult.close(); +} catch (err) { + console.error('onCallback failed with err: ' + err); +} +``` + +## Unregistering the Listening for a URI + +Use [unRegisterChange](../reference/apis/js-apis-photoAccessHelper.md#unregisterchange) to unregister the listening for the specified URI. Multiple listeners can be registered for a URI. If multiple listener callbacks exist, you can unregister a listener callback registered. If callback is not specified, all listeners of the URI will be unregistered. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Unregister the listening for an image. After that, the corresponding listener callback is not triggered when the image favorites status is changed. + +**How to Develop** + +1. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). +2. Unregister the listening for the URI of the media asset obtained. +3. Add the media asset obtained to **Favorites**. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + + let onCallback1 = (changeData) => { + console.info('onCallback1, changData: ' + JSON.stringify(changeData)); + } + let onCallback2 = (changeData) => { + console.info('onCallback2, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(fileAsset.uri, false, onCallback1); + phAccessHelper.registerChange(fileAsset.uri, false, onCallback2); + phAccessHelper.unRegisterChange(fileAsset.uri, onCallback1); + + await fileAsset.favorite(true); + fetchResult.close(); +} catch (err) { + console.error('onCallback failed with err: ' + err); +} +``` diff --git a/en/application-dev/file-management/photoAccessHelper-overview.md b/en/application-dev/file-management/photoAccessHelper-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..48bb753cf4c1b5d10132c4bb1b12e7cf9290fd4c --- /dev/null +++ b/en/application-dev/file-management/photoAccessHelper-overview.md @@ -0,0 +1,123 @@ +# PhotoAccessHelper Overview + +**PhotoAccessHelper** provides album management capabilities, including creating and accessing an album and accessing and modifying media data in albums. You can use the APIs provided by **PhotoAccessHelper** to manage: + +- [Media assets (images and videos)](photoAccessHelper-resource-guidelines.md), including: + - Obtaining the specified media assets. + - Obtaining an image or video thumbnail. + - Creating a media asset. + - Renaming a media asset. + - Moving a media asset to the trash. +- [User Albums](photoAccessHelper-userAlbum-guidelines.md), including: + - Creating a user album. + - Obtaining a user album. + - Renaming a user album. + - Adding images and videos to a user album. + - Obtaining images and videos from a user album. + - Removing images and videos from a user album. + - Deleting a user album. +- [System albums](photoAccessHelper-systemAlbum-guidelines.md), including: + - Favorites + - Video album + - Screenshot album +- [Media asset (image, video, and album) change notifications](photoAccessHelper-notify-guidelines.md), including: + - Registering listening for a specified URI. + - Unregistering the listening for a specified URI. + +> **NOTE** +> +> The **PhotoAccessHelper** development guides apply only to API version 10 based on the stage model. + +An application needs to obtain a **photoAccessHelper** instance before accessing and modifying the media data in an album. User personal data is involved in the **photoAccessHelper** module. Therefore, the application needs to apply for the related read and write permissions. Unless otherwise specified, the APIs of the **photoAccessHelper** module apply to **pages/index.ets** of the project or other customized .ets files by default. + +Before using the **PhotoAccessHelper** APIs, you need to: + +- [Obtain a **photoAccessHelper** instance.](#obtaining-a-photoaccesshelper-instance) +- [Apply for permissions.](#applying-for-permissions) + +## Obtaining a photoAccessHelper Instance + +The application needs to call [getPhotoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) to obtain a **photoAccessHelper** instance based on the application context. The instance obtained can be used to access or modify the media data (such as image and videos) in an album. + +**How to Develop** + +1. Import the **photoAccessHelper** module. +2. Use **getContext** to obtain the application context. +3. Obtain a **photoAccessHelper** instance. + +```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + +// The phAccessHelper instance obtained here is a global object. By default, the object obtained here is used in subsequent operations. If the code is not added, an undefined error will be reported. +const context = getContext(this); +let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); +``` + +## Applying for Permissions + +Before applying for permission, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are complied with. Apply for the following permissions. + +| Permission | Description | Authorization Mode | +| ------------------------------ | ------------------------------------------ | ---------- | +| ohos.permission.READ_IMAGEVIDEO | Allows an app to read image and video file information from a user's external storage.| user_grant | +| ohos.permission.WRITE_IMAGEVIDEO | Allows an app to read and write image and video file information on a user's external storage.| user_grant | + +The required permissions must be authorized by the user (user_grant). You need to add the permissions in the **module.json5** file, and use [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the required permissions are granted by the user. If yes, the application can access the data. Otherwise, a dialog box will be displayed to request user authorization. + +> **NOTE**
Even if the user has granted the permission, the permission will still be checked before an API protected by the permission is called. The permission granted status should not be persisted, because the user can revoke the permission through the system application **Settings**. + +**How to Develop** + +1. Declare the permissions in the **module.json5** file.
Add **requestPermissions** under **module** in the file, and add the required permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). + + ```json + { + "module": { + "requestPermissions": [ + { + "name": "ohos.permission.READ_IMAGEVIDEO", + "reason": "Permissions required for photoAccessHelper related operations", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.WRITE_IMAGEVIDEO", + "reason": "Permissions required for photoAccessHelper related operations", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + }, + ] + } + } + ``` + +2. Call **requestPermissionsFromUser** in the **onWindowStageCreate** callback of **Ability.ts** to check for the required permissions. If the permissions are not granted, display a dialog box to request user authorization dynamically. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; + + export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let list : Array = ['ohos.permission.READ_IMAGEVIDEO', 'ohos.permission.WRITE_IMAGEVIDEO']; + let permissionRequestResult; + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(this.context, list, (err, result) => { + if (err) { + console.error('requestPermissionsFromUserError: ' + JSON.stringify(err)); + } else { + permissionRequestResult = result; + console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + } + }); + } + } + ``` diff --git a/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..d145589c1ad96aa8c9e4cc11d3112e40f4772678 --- /dev/null +++ b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md @@ -0,0 +1,283 @@ +# Media Asset Management + +Applications can call **photoAccessHelper** APIs to manage media assets (images and videos). + +> **NOTE** +> +> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. +> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. + +To ensure application running efficiency, most **PhotoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). + +## Obtaining the Specified Media Assets + +You can query media assets by media type, date, or album name. + +Use [PhotoAccessHelper.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets) with the [FetchOptions](../reference/apis/js-apis-photoAccessHelper.md#fetchoptions) object to specify search criteria. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. + +To obtain the object at the specified position (for example, the first, the last, or object with the specified index) in the result set, use [FetchFileResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult). + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. +- The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported. + +### Obtaining an Image or Video by Name + +Example: Obtain the image **test.jpg**. + +**How to Develop** + +Create a **FetchOptions** object and specify **test.jpg**. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; +``` + +Call **PhotoAccessHelper.getAssets** to obtain the image asset. + +```ts +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + fetchResult.close(); +} catch (err) { + console.error('getAssets failed with err: ' + err); +} +``` + +### Obtaining an Image or Video by URI + +Example: Obtain the image with the file URI **file://media/Photo/1**. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo(photoAccessHelper.PhotoKeys.URI, 'file://media/Photo/1'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; +``` + +Call **PhotoAccessHelper.getAssets** to obtain the image asset. + +```ts +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + fetchResult.close(); +} catch (err) { + console.error('getAssets failed with err: ' + err); +} +``` + + +### Obtaining Images or Videos by Time + +Example: Obtain the media assets added from 2022-06-01 to 2023-06-01. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // The value of the start time is the number of seconds elapsed since the Epoch time. +let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. +let date_added = photoAccessHelper.PhotoKeys.DATE_ADDED; +predicates.between(date_added, startTime, endTime); +predicates.orderByDesc(date_added); // The query results are sorted in descending order. +let fetchOptions = { + fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added. + predicates: predicates +}; +``` + +Call **PhotoAccessHelper.getAssets** to obtain the image assets. + +```ts +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + console.info('getAssets count: ' + fetchResult.getCount()); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + fetchResult.close(); +} catch (err) { + console.error('getAssets failed with err: ' + err); +} +``` + +## Obtaining an Image or Video Thumbnail + +Use [FileAsset.getThumbnail](../reference/apis/js-apis-photoAccessHelper.md#getthumbnail) with the thumbnail size passed in to obtain the image or video thumbnail. The thumbnails offer a quick preview on images and videos. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. +- The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported. + +### Obtaining the Thumbnail of an Image + +Your application may need to obtain the thumbnail of an image or video for preview purposes. + +Example: Obtain the thumbnail of 720 x 720 of an image. + +**How to Develop** + +1. Set the fetch options. +2. Call **PhotoAccessHelper.getAssets** to obtain image assets. +3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image from the result set. +4. Call **getThumbnail** to obtain the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) of the thumbnail of the image. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + let size = { width: 720, height: 720 }; + let pixelMap = await fileAsset.getThumbnail(size); + let imageInfo = await pixelMap.getImageInfo() + console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); + fetchResult.close(); +} catch (err) { + console.error('getThumbnail failed with err: ' + err); +} +``` + +## Creating a Media Asset + +Use [createAsset](../reference/apis/js-apis-photoAccessHelper.md#createasset) to create a media asset. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission. + +### Creating an Image or Video Asset + +Example: Create an image asset. + +**How to Develop** + +1. Set the file name and create **createOption** for setting attributes for the image asset to create. +2. Call **createAsset** to create an image asset. + +```ts +try { + let displayName = 'testPhoto' + Date.now() + '.jpg'; + let createOption = { + subType: photoAccessHelper.PhotoSubtype.DEFAULT + }; + + let fileAsset = await phAccessHelper.createAsset(displayName, createOption); + console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); +} catch (err) { + console.error('createAsset failed, message = ', err); +} +``` + +## Renaming a Media Asset + +Set the **FileAsset.displayName** attribute to modify the file name (including the file name extension) displayed. + +After the modification, use [FileAsset.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify) to update the modification to the database. + +Before renaming a file, use [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) to obtain the file. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions. + +Example: Rename the first file in the obtained image assets. + +**How to Develop** + +1. Set the fetch options. +2. Call **getAssets** to obtain image assets. +3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image from the obtained file assets. +4. Call **FileAsset.set** to rename the image. +5. Call **FileAsset.commitModify** to update the modified image attributes to the database. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: ['title'], + predicates: predicates +}; +let newTitle = 'newTestPhoto'; + +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + let title = photoAccessHelper.PhotoKeys.TITLE; + let fileAssetTitle = fileAsset.get(title); + console.info('getAssets fileAsset.title : ' + fileAssetTitle); + fileAsset.set(title, newTitle); + await fileAsset.commitModify(); + fetchResult.close(); +} catch (err) { + console.error('commitModify failed with err: ' + err); +} +``` + +## Moving Media Assets to the Trash + +You can use [deleteAssets](../reference/apis/js-apis-photoAccessHelper.md#deleteassets) to move files to the trash. + +The files moved to the trash will be retained for 30 days, and deleted permanently after 30 days. Before a file is deleted permanently from the trash, the user can restore it using the system application **File Manager** or **Gallery**. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained +- The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions. + +Example: Move the first file in the result set to the trash. + +**How to Develop** + +1. Set the fetch options. +2. Call **PhotoAccessHelper.getAssets** to obtain image assets. +3. Call [**FetchResult.getFirstObject**](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image, that is, the image object to be moved to the trash. +4. Call **deleteAssets** to move the file to the trash. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + await phAccessHelper.deleteAssets([fileAsset.uri]); + fetchResult.close(); +} catch (err) { + console.error('deleteAssets failed with err: ' + err); +} +``` diff --git a/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..7c98b2f674aba77a5359179e2a56b56819784eb1 --- /dev/null +++ b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md @@ -0,0 +1,306 @@ +# System Album Management + +The **photoAccessHelper** module provides APIs for managing system albums, including the **Favorites**, video album, and screenshot album. + +> **NOTE** +> +> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. +> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. + +To ensure application running efficiency, most **photoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). +Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. + +## Favorites + +The **Favorites** is a system album. When you favorite a photo or video, the photo or video is added to **Favorites**. When you favorite a photo or video, the photo or video is removed from **Favorites**. + +### Obtaining a Favorites Object + +Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a **Favorites** object. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +**How to Develop** + +1. Set the album type to **photoAccessHelper.AlbumType.SYSTEM** and the album subtype to **photoAccessHelper.AlbumSubtype.FAVORITE**. +2. Call **getAlbums** to obtain a **Favorites** object. + +```ts +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album = await fetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); +} catch (err) { + console.error('get favorite Album failed with err: ' + err); +} +``` + +### Favoriting an Image or Video + +Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to add images or videos to **Favorites**. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Favorite an image. + +**How to Develop** + +1. [Obtain media assets](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). +2. Set **favoriteState** to **true** to favorite the image. +3. Use **FileAsset.setFavorite** to add the image to **Favorites**. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let photoFetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + let favoriteState = true; + await fileAsset.setFavorite(favoriteState); +} catch (err) { + console.error('setFavorite failed with err: ' + err); +} +``` + +### Obtaining Images and Videos in Favorites + +[Obtain a **Favorites** object](#obtaining-a-favorites-object), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the assets in **Favorites**. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +Example: Obtain an image from **Favorites**. + +**How to Develop** + +1. [Obtain a **Favorites** object](#obtaining-a-favorites-object). +2. Set **fetchOptions** for obtaining the image. +3. Call **Album.getAssets** to obtain the image assets. +4. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image from the result set. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album = await albumFetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + + let photoFetchResult = await album.getAssets(fetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); + photoFetchResult.close(); + albumFetchResult.close(); +} catch (err) { + console.error('favorite failed with err: ' + err); +} +``` + +### Unfavoriting an Image or Video + +Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to remove an image or video from **Favorites**. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Unfavorite an image. + +**How to Develop** + +1. [Obtain the image and videos in **Favorites**](#obtaining-images-and-videos-in-favorites). +2. Set **isFavorite** to **false**. +3. Use **FileAsset.favorite** to remove the image from **Favorites**. + + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album = await albumFetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + + let photoFetchResult = await album.getAssets(fetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); + let favoriteState = false; + await fileAsset.setFavorite(favoriteState); + photoFetchResult.close(); + albumFetchResult.close(); +} catch (err) { + console.error('setFavorite failed with err: ' + err); +} +``` + +## Video Album + +The video album is a system album. The media assets of the video type in user files are automatically added to the video album. + +### Obtaining a Video Album Object + +Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a video album object. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +**How to Develop** + +1. Set the album type to **photoAccessHelper.AlbumType.SYSTEM** and the album subtype to **photoAccessHelper.AlbumSubtype.VIDEO**. +2. Use **getAlbums** to obtain the video album object. + +```ts +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album = await fetchResult.getFirstObject(); + console.info('get video Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); +} catch (err) { + console.error('get video Album failed with err: ' + err); +} +``` + +### Obtaining Videos from the Video Album + +[Obtain a video album object](#obtaining-a-video-album-object). Use [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain video assets in the video album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +Example: Obtain a video in the video album. + +**How to Develop** + +1. [Obtain a video album object](#obtaining-a-video-album-object). +2. Set **fetchOptions** for obtaining the video. +3. Call **Album.getAssets** to obtain video assets. +4. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first video. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album = await albumFetchResult.getFirstObject(); + console.info('get video Album successfully, albumUri: ' + album.albumUri); + + let videoFetchResult = await album.getAssets(fetchOptions); + let fileAsset = await videoFetchResult.getFirstObject(); + console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); + videoFetchResult.close(); + albumFetchResult.close(); +} catch (err) { + console.error('video failed with err: ' + err); +} +``` + +## Screenshot Album + +The screenshot album is a system album. The user's screenshots and screen recording files are automatically added to this album. + +### Obtaining a Screenshot Album Object + +Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a screenshot album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +**How to Develop** + +1. Set the album type to **photoAccessHelper.AlbumType.SYSTEM** and the album subtype to **photoAccessHelper.AlbumSubtype.SCREENSHOT**. +2. Use **getAlbums** to obtain a screenshot album object. + +```ts +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album = await fetchResult.getFirstObject(); + console.info('get screenshot Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); +} catch (err) { + console.error('get screenshot Album failed with err: ' + err); +} +``` + +### Obtaining Media Assets in the Screenshot Album + +[Obtain a screenshot album object](#obtaining-a-screenshot-album-object), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +Example: Obtain a media asset from the screenshot album. + +**How to Develop** + +1. [Obtain a screenshot album object](#obtaining-a-screenshot-album-object). +2. Set **fetchOptions** for obtaining the media asset. +3. Call **Album.getAssets** to obtain media assets. +4. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first media asset. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album = await albumFetchResult.getFirstObject(); + console.info('get screenshot album successfully, albumUri: ' + album.albumUri); + + let screenshotFetchResult = await album.getAssets(fetchOptions); + let fileAsset = await screenshotFetchResult.getFirstObject(); + console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); + screenshotFetchResult.close(); + albumFetchResult.close(); +} catch (err) { + console.error('screenshot album failed with err: ' + err); +} +``` diff --git a/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..57bed20da0011c46f9172a87c121adc5f5c37f41 --- /dev/null +++ b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md @@ -0,0 +1,329 @@ +# User Album Management + +The **photoAccessHelper** module provides APIs for user album management, including creating or deleting a user album, adding images and videos to a user album, and deleting image and videos from a user album. + +> **NOTE** +> +> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. +> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. + +To ensure application running efficiency, most **PhotoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). +Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. + +## Creating a User Album + +Use [createAlbum](../reference/apis/js-apis-photoAccessHelper.md#createalbum) to create a user album. + +The album name must meet the following requirements: + +- The album name is a string of 1 to 255 characters. +- The album name cannot contain any of the following characters:
\ / : * ? " ' ` < > | { } [ ] +- The album name is case-insensitive. +- Duplicate album names are not allowed. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission. + +Example: Create a user album. + +**How to Develop** + +1. Set the name of the album to create. +2. Use **createAlbum** to create an album. + +```ts +try { + let albumName = 'albumName'; + let album = await phAccessHelper.createAlbum(albumName); + console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); +} catch (err) { + console.error('createAlbum failed with err: ' + err); +} +``` + +## Obtaining a User Album + +Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a user album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. + +Example: Obtain a user album named **albumName**. + +**How to Develop** + +1. Set **fetchOptions** for obtaining the user album. +2. Call **getAlbums** to obtain user albums. +3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +predicates.equalTo(albumName, 'albumName'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + fetchResult.close(); +} catch (err) { + console.error('getAlbums failed with err: ' + err); +} +``` + +## Renaming a User Album + +Modify the **Albums.albumName** attribute of the album, + +and use [Album.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify-2) to update the modification to the database. + +Before renaming a user album, you need to obtain an album object. You can use the [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) APIs to obtain the user album of the corresponding location. + +The new user album names must also comply with the user name requirements in [Creating a User Album](#creating-a-user-album). + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Rename an album named **albumName**. + +**How to Develop** + +1. Set **fetchOptions** for obtaining the user album. +2. Call **getAlbums** to obtain user albums. +3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album. +4. Set a new album name. +5. Call **Album.commitModify** to update the modified album attributes to the database. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +predicates.equalTo(albumName, 'albumName'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + album.albumName = 'newAlbumName'; + await album.commitModify(); + fetchResult.close(); +} catch (err) { + console.error('commitModify failed with err: ' + err); +} +``` + +## Adding Images and Videos to a User Album + +[Obtain a user album](#obtaining-a-user-album) and the array of the images or videos to be added to the album, and then call [Album.addAssets](../reference/apis/js-apis-photoAccessHelper.md#addassets) to add the images or videos to the user album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Add an image to the album named **albumName**. + +**How to Develop** + +1. Set **albumFetchOptions** for obtaining the user album. +2. Set **photoFetchOptions** for obtaining the image. +3. Call **getAlbums** to obtain user albums. +4. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album. +5. Call [PhotoAccessHelper.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets) to obtain image assets. +6. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image from the result set. +7. Call **Album.addAssets** to add the image to the user album. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let albumPredicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +albumPredicates.equalTo(albumName, 'albumName'); +let albumFetchOptions = { + fetchColumns: [], + predicates: albumPredicates +}; + +let photoPredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions = { + fetchColumns: [], + predicates: photoPredicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await phAccessHelper.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('getAssets successfully, albumName: ' + fileAsset.displayName); + await album.addAssets([fileAsset]); + albumFetchResult.close(); + photoFetchResult.close(); +} catch (err) { + console.error('addAssets failed with err: ' + err); +} +``` + +## Obtaining Images and Videos in a User Album + +[Obtain the user album](#obtaining-a-user-album) object, and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Obtain an image in a user album named **albumName**. + +**How to Develop** + +1. Set **albumFetchOptions** for obtaining the user album. +2. Set **photoFetchOptions** for obtaining the image. +3. Call **getAlbums** to obtain user albums. +4. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album. +5. Call **Album.getAssets** to obtain the image assets in the user album. +6. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image from the result set. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let albumPredicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +albumPredicates.equalTo(albumName, 'albumName'); +let albumFetchOptions = { + fetchColumns: [], + predicates: albumPredicates +}; + +let photoPredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions = { + fetchColumns: [], + predicates: photoPredicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await album.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); + albumFetchResult.close(); + photoFetchResult.close(); +} catch (err) { + console.error('album getAssets failed with err: ' + err); +} +``` + +## Removing Images and Videos from a User Album + +[Obtain the user album](#obtaining-a-user-album) object, and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album. + +Use [Album.removeAssets](../reference/apis/js-apis-photoAccessHelper.md#removeassets) to remove the specified images. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Remove an image from the album named **albumName**. + +**How to Develop** + +1. Set **albumFetchOptions** for obtaining the user album. +2. Set **photoFetchOptions** for obtaining the image. +3. Call **getAlbums** to obtain user albums. +4. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album. +5. Call **Album.getAssets** to obtain the image assets. +6. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first image from the result set. +7. Call **Album.removeAssets** to remove the image from the user album. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let albumPredicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +albumPredicates.equalTo(albumName, 'albumName'); +let albumFetchOptions = { + fetchColumns: [], + predicates: albumPredicates +}; + +let photoPredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions = { + fetchColumns: [], + predicates: photoPredicates +}; + +try { + let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await album.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); + await album.removeAssets([fileAsset]); + albumFetchResult.close(); + photoFetchResult.close(); +} catch (err) { + console.error('removeAssets failed with err: ' + err); +} +``` + +## Deleting a User Album + +[Obtain the user album](#obtaining-a-user-album) object, and call [deleteAlbums](../reference/apis/js-apis-photoAccessHelper.md#deletealbums) to delete the user album. + +**Prerequisites** + +- A **photoAccessHelper** instance is obtained. +- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. + +Example: Delete a user album named **albumName**. + +**How to Develop** + +1. Set **fetchOptions** for obtaining the user album. +2. Call **getAlbums** to obtain user albums. +3. Call **FetchResult.getFirstObject** to obtain the first user album. +4. Call **deleteAlbums** to delete the user album. + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let predicates = new dataSharePredicates.DataSharePredicates(); +let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +predicates.equalTo(albumName, '%albumName%'); +let fetchOptions = { + fetchColumns: [], + predicates: predicates +}; + +try { + let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + phAccessHelper.deleteAlbums([album]); + fetchResult.close(); +} catch (err) { + console.error('deleteAlbums failed with err: ' + err); +} +``` diff --git a/en/application-dev/file-management/save-user-file.md b/en/application-dev/file-management/save-user-file.md index db6ad37908be0a1fe1dd00e36c4553830bf03c72..d47592c74dff6211a7301516c8a76f07f648812e 100644 --- a/en/application-dev/file-management/save-user-file.md +++ b/en/application-dev/file-management/save-user-file.md @@ -4,6 +4,8 @@ When a user needs to download a file from the network to a local directory or sa The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. +The **save()** interface saves the file in the file manager, not in the Gallery. + ## Saving Images or Video Files @@ -23,14 +25,14 @@ The operations for saving images, audio or video clips, and documents are simila 3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned. -
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. + The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let URI = null; + let uri = null; const photoViewPicker = new picker.PhotoViewPicker(); photoViewPicker.save(photoSaveOptions).then((photoSaveResult) => { - URI = photoSaveResult[0]; - console.info('photoViewPicker.save to file succeed and URI is:' + URI); + uri = photoSaveResult[0]; + console.info('photoViewPicker.save to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) @@ -39,7 +41,7 @@ The operations for saving images, audio or video clips, and documents are simila 4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**. ```ts - let file = fs.openSync(URI, fs.OpenMode.READ_WRITE); + let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); console.info('file fd: ' + file.fd); ``` @@ -72,11 +74,11 @@ The operations for saving images, audio or video clips, and documents are simila The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let URI = null; + let uri = null; const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { - URI = documentSaveResult[0]; - console.info('documentViewPicker.save to file succeed and URI is:' + URI); + uri = documentSaveResult[0]; + console.info('documentViewPicker.save to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) @@ -85,7 +87,7 @@ The operations for saving images, audio or video clips, and documents are simila 4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**. ```ts - let file = fs.openSync(URI, fs.OpenMode.READ_WRITE); + let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); console.info('file fd: ' + file.fd); ``` @@ -118,11 +120,11 @@ The operations for saving images, audio or video clips, and documents are simila The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let URI = null; + let uri = null; const audioViewPicker = new picker.AudioViewPicker(); audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => { - URI = audioSelectResult[0]; - console.info('audioViewPicker.save to file succeed and URI is:' + URI); + uri = audioSelectResult[0]; + console.info('audioViewPicker.save to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) @@ -131,11 +133,11 @@ The operations for saving images, audio or video clips, and documents are simila 4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**. ```ts - let file = fs.openSync(URI, fs.OpenMode.READ_WRITE); + let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); console.info('file fd: ' + file.fd); ``` -5. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD. +5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD. ```ts let writeLen = fs.writeSync(file.fd, 'hello, world'); diff --git a/en/application-dev/file-management/select-user-file.md b/en/application-dev/file-management/select-user-file.md index 853aae60d7e73fa4238e388eefb19ded0ca59b1d..af4bae83b13b50eb64e0063012dcaea4a51234bd 100644 --- a/en/application-dev/file-management/select-user-file.md +++ b/en/application-dev/file-management/select-user-file.md @@ -35,14 +35,14 @@ The **FilePicker** provides the following interfaces by file type: 4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files. After the files are selected, [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) is returned. -
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. + The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let URI = null; + let uri = null; const photoViewPicker = new picker.PhotoViewPicker(); photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { - URI = photoSelectResult.photoUris[0]; - console.info('photoViewPicker.select to file succeed and URI is:' + URI); + uri = photoSelectResult.photoUris[0]; + console.info('photoViewPicker.select to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -51,7 +51,7 @@ The **FilePicker** provides the following interfaces by file type: 5. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**. ```ts - let file = fs.openSync(URI, fs.OpenMode.READ_ONLY); + let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); console.info('file fd: ' + file.fd); ``` @@ -81,20 +81,20 @@ The **FilePicker** provides the following interfaces by file type: 3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned. -
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. + The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. -
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md). + For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md). > **NOTE** > > Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected. ```ts - let URI = null; + let uri = null; const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { - URI = documentSelectResult[0]; - console.info('documentViewPicker.select to file succeed and URI is:' + URI); + uri = documentSelectResult[0]; + console.info('documentViewPicker.select to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -129,7 +129,7 @@ The **FilePicker** provides the following interfaces by file type: 4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**. ```ts - let file = fs.openSync(URI, fs.OpenMode.READ_ONLY); + let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); console.info('file fd: ' + file.fd); ``` @@ -160,20 +160,20 @@ The **FilePicker** provides the following interfaces by file type: 3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files. After the files are selected, a result set containing the URIs of the audio files selected is returned. -
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. + The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. -
For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md). + For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md). > **NOTE** > > Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected. ```ts - let URI = null; + let uri = null; const audioViewPicker = new picker.AudioViewPicker(); audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { - URI = audioSelectOptions[0]; - console.info('audioViewPicker.select to file succeed and URI is:' + URI); + uri = audioSelectOptions[0]; + console.info('audioViewPicker.select to file succeed and uri is:' + uri); }).catch((err) => { console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) @@ -182,7 +182,7 @@ The **FilePicker** provides the following interfaces by file type: 4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**. ```ts - let file = fs.openSync(URI, fs.OpenMode.READ_ONLY); + let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); console.info('file fd: ' + file.fd); ``` diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index e78bdb6437b26b8a30ee23f9fdec380087297b33..f2393be5fb12c8011d267f0df295acfaacaec607 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -610,8 +610,10 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to Call **transform** to obtain the transliterated string. ```js - let transliterator = I18n.Transliterator.getInstance("Any-Latn"); // Any-Latn means to convert any text to Latn text. + let transliterator = I18n.Transliterator.getInstance("Any-Latin"); // Any-Latin means to convert any text to Latin text. let transformText = transliterator.transform ("Hello"); // transformText = "nǐ hǎo" + let transliterator2 = I18n.Transliterator.getInstance("Latin-ASCII"); // Latin-ASCII means to convert Latin text to ASCII text. + transformText = transliterator2.transform(transformText); // transformText = "ni hao" ``` ## Obtaining the Character Type diff --git a/en/application-dev/media/audio-decoding.md b/en/application-dev/media/audio-decoding.md index 77631eefec952c5142d76680abd49bd694541ab1..2fc2d11ed4bf946f90466e45b6160e8880e4d7e1 100644 --- a/en/application-dev/media/audio-decoding.md +++ b/en/application-dev/media/audio-decoding.md @@ -73,33 +73,33 @@ The figure below shows the call relationship of audio decoding. ``` 2. Call **OH_AudioDecoder_SetCallback()** to set callback functions. - + Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: - - - **OnError**, a callback used to report a codec operation error - - **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, audio channel change - - **OnInputBufferAvailable**, a callback used to report input data required, which means that the decoder is ready for receiving data - - **OnOutputBufferAvailable**, a callback used to report output data generated, which means that decoding is complete + + - **OH_AVCodecOnError**, a callback used to report a codec operation error + - **OH_AVCodecOnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OH_AVCodecOnNeedInputData**, a callback used to report input data required, which means that the decoder is ready for receiving data + - **OH_AVCodecOnNewOutputData**, a callback used to report output data generated, which means that decoding is complete You need to process the callback functions to ensure that the decoder runs properly. - - ```cpp - // Set the OnError callback function. + + ```cpp + // Implement the OH_AVCodecOnError callback function. static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) { (void)codec; (void)errorCode; (void)userData; } - // Set the OnOutputFormatChanged callback function. - static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void*userData) + // Implement the OH_AVCodecOnStreamChanged callback function. + static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void*userData) { (void)codec; (void)format; (void)userData; } - // Set the OnInputBufferAvailable callback function, which is used to send the input stream to the InputBuffer queue. - static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory*data, void *userData) + // Implement the OH_AVCodecOnNeedInputData callback function. + static void onNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory*data, void *userData) { (void)codec; ADecSignal *signal = static_cast(userData); @@ -109,8 +109,8 @@ The figure below shows the call relationship of audio decoding. signal->inCond_.notify_all(); // The input stream is sent to the InputBuffer queue. } - // Set the OnOutputBufferAvailable callback function, which is used to send the PCM stream obtained after decoding to the OutputBuffer queue. - static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory*data, OH_AVCodecBufferAttr *attr, + // Implement the OH_AVCodecOnNewOutputData callback function. + static void onNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory*data, OH_AVCodecBufferAttr *attr, void *userData) { (void)codec; @@ -126,14 +126,13 @@ The figure below shows the call relationship of audio decoding. // The decoded data is sent to the OutputBuffer queue. } signal_ = new ADecSignal(); - OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, OnInputBufferAvailable, &OnOutputBufferAvailable}; + OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &onNeedInputData, &onNeedOutputData}; // Set the asynchronous callbacks. int32_t ret = OH_AudioDecoder_SetCallback(audioDec, cb, signal_); if (ret != AV_ERR_OK) { // Exception handling. } - ``` - + ``` 3. Call **OH_AudioDecoder_Configure()** to configure the decoder. The following options are mandatory: sampling rate, bit rate, and number of audio channels. The maximum input length is optional. @@ -141,7 +140,7 @@ The figure below shows the call relationship of audio decoding. - For AAC decoding, the parameter that specifies whether the data type is Audio Data Transport Stream (ADTS) must be specified. If this parameter is not specified, the data type is considered as Low Overhead Audio Transport Multiplex (LATM). - For Vorbis decoding, the ID header and setup header must also be specified. - ```cpp + ```cpp enum AudioFormatType : int32_t { TYPE_AAC = 0, TYPE_FLAC = 1, @@ -176,8 +175,7 @@ The figure below shows the call relationship of audio decoding. if (ret != AV_ERR_OK) { // Exception handling. } - ``` - + ``` 4. Call **OH_AudioDecoder_Prepare()** to prepare internal resources for the decoder. ```cpp @@ -186,7 +184,6 @@ The figure below shows the call relationship of audio decoding. // Exception handling. } ``` - 5. Call **OH_AudioDecoder_Start()** to start the decoder. ```c++ @@ -202,12 +199,10 @@ The figure below shows the call relationship of audio decoding. // Exception handling. } ``` - 6. Call **OH_AudioDecoder_PushInputData()** to write the data to decode. To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag. - - ```c++ + ```c++ // Configure the buffer information. OH_AVCodecBufferAttr info; // Set the package size, offset, and timestamp. @@ -228,8 +223,7 @@ The figure below shows the call relationship of audio decoding. if (ret != AV_ERR_OK) { // Exception handling. } - ``` - + ``` 7. Call **OH_AudioDecoder_FreeOutputData()** to output decoded PCM streams. ```c++ @@ -244,7 +238,6 @@ The figure below shows the call relationship of audio decoding. // Exception handling. } ``` - 8. (Optional) Call **OH_AudioDecoder_Flush()** to refresh the decoder. After **OH_AudioDecoder_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed. To continue decoding, you must call **OH_AudioDecoder_Start()** again. @@ -265,24 +258,22 @@ The figure below shows the call relationship of audio decoding. // Exception handling. } ``` - 9. (Optional) Call **OH_AudioDecoder_Reset()** to reset the decoder. After **OH_AudioDecoder_Reset()** is called, the decoder returns to the initialized state. To continue decoding, you must call **OH_AudioDecoder_Configure()** and then **OH_AudioDecoder_Start()**. - - ```c++ - // Reset the decoder. - ret = OH_AudioDecoder_Reset(audioDec); - if (ret != AV_ERR_OK) { - // Exception handling. - } - // Reconfigure the decoder. - ret = OH_AudioDecoder_Configure(audioDec, format); - if (ret != AV_ERR_OK) { - // Exception handling. - } - ``` - + + ```c++ + // Reset the decoder. + ret = OH_AudioDecoder_Reset(audioDec); + if (ret != AV_ERR_OK) { + // Exception handling. + } + // Reconfigure the decoder. + ret = OH_AudioDecoder_Configure(audioDec, format); + if (ret != AV_ERR_OK) { + // Exception handling. + } + ``` 10. Call **OH_AudioDecoder_Stop()** to stop the decoder. ```c++ @@ -293,18 +284,17 @@ The figure below shows the call relationship of audio decoding. } return ret; ``` - 11. Call **OH_AudioDecoder_Destroy()** to destroy the decoder instance and release resources. - **NOTE**: You only need to call this API once. - - ```c++ - // Call OH_AudioDecoder_Destroy to destroy the decoder. - ret = OH_AudioDecoder_Destroy(audioDec); - if (ret != AV_ERR_OK) { - // Exception handling. - } else { - audioEnc = NULL; // The decoder cannot be destroyed repeatedly. - } - return ret; - ``` \ No newline at end of file + **NOTE**: You only need to call this API once. + + ```c++ + // Call OH_AudioDecoder_Destroy to destroy the decoder. + ret = OH_AudioDecoder_Destroy(audioDec); + if (ret != AV_ERR_OK) { + // Exception handling. + } else { + audioEnc = NULL; // The decoder cannot be destroyed repeatedly. + } + return ret; + ``` diff --git a/en/application-dev/media/audio-encoding.md b/en/application-dev/media/audio-encoding.md index df2a0ace83f52fdbf1a9ae002dc6dae639088e4d..607c89560a052ce98b4170d098840f84df3286f7 100644 --- a/en/application-dev/media/audio-encoding.md +++ b/en/application-dev/media/audio-encoding.md @@ -50,7 +50,7 @@ The figure below shows the call relationship of audio encoding. ```cpp // Create an encoder by MIME type. - OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_AAC); + OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_AAC); ``` ```cpp @@ -76,47 +76,46 @@ The figure below shows the call relationship of audio encoding. Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: - - **OnError**, a callback used to report a codec operation error - - **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, audio channel change - - **OnInputBufferAvailable**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data - - **OnOutputBufferAvailable**, a callback used to report output data generated, which means that encoding is complete + - **OH_AVCodecOnError**, a callback used to report a codec operation error + - **OH_AVCodecOnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OH_AVCodecOnNeedInputData**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data + - **OH_AVCodecOnNewOutputData**, a callback used to report output data generated, which means that encoding is complete You need to process the callback functions to ensure that the encoder runs properly. ```cpp - // Set the OnError callback function. + // Implement the OH_AVCodecOnError callback function. static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) { (void)codec; (void)errorCode; (void)userData; } - // Set the OnOutputFormatChanged callback function. - static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) + // Implement the OH_AVCodecOnStreamChanged callback function. + static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) { (void)codec; (void)format; (void)userData; } - // Set the OnInputBufferAvailable callback function, which is used to send the input PCM data to the InputBuffer queue. - static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData) + // Implement the OH_AVCodecOnNeedInputData callback function. + static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData) { (void)codec; // The input stream is sent to the InputBuffer queue. AEncSignal *signal = static_cast(userData); - cout << "OnInputBufferAvailable received, index:" << index << endl; unique_lock lock(signal->inMutex_); signal->inQueue_.push(index); signal->inBufferQueue_.push(data); signal->inCond_.notify_all(); } - // Set the OnOutputBufferAvailable callback function, which is used to send the encoded stream to the OutputBuffer queue. - static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr, + // Implement the OH_AVCodecOnNewOutputData callback function. + static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr, void *userData) { (void)codec; - // The index of the output buffer is sent to the OutputQueue. - // The encoded data is sent to the OutputBuffer queue. + // The index of the output buffer is sent to OutputQueue_. + // The encoded data is sent to the outBuffer queue. AEncSignal *signal = static_cast(userData); unique_lock lock(signal->outMutex_); signal->outQueue_.push(index); @@ -125,7 +124,7 @@ The figure below shows the call relationship of audio encoding. signal->attrQueue_.push(*attr); } } - OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable}; + OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputData, &OnNeedOutputData}; // Set the asynchronous callbacks. int32_t ret = OH_AudioEncoder_SetCallback(audioEnc, cb, userData); ``` @@ -143,7 +142,7 @@ The figure below shows the call relationship of audio encoding. }; int32_t ret; // (Mandatory) Configure the audio sampling rate. - constexpr uint32_t DEFAULT_SMAPLERATE = 44100; + constexpr uint32_t DEFAULT_SMAPLERATE = 44100; // (Mandatory) Configure the audio bit rate. constexpr uint32_t DEFAULT_BITRATE = 32000; // (Mandatory) Configure the number of audio channels. @@ -193,7 +192,7 @@ The figure below shows the call relationship of audio encoding. ```c++ inputFile_ = std::make_unique(); // Open the path of the binary file to be encoded. - inputFile_->open(inputFilePath.data(), std::ios::in |std::ios::binary); + inputFile_->open(inputFilePath.data(), std::ios::in |std::ios::binary); // Configure the path of the output file. outFile_ = std::make_unique(); outFile_->open(outputFilePath.data(), std::ios::out |std::ios::binary); diff --git a/en/application-dev/media/figures/audio-decode.png b/en/application-dev/media/figures/audio-decode.png index f76febe618c2529b3530436ddab6cb954a42d3b2..388cc259a9500e7b0db7c4d6f9a91f15449de69c 100644 Binary files a/en/application-dev/media/figures/audio-decode.png and b/en/application-dev/media/figures/audio-decode.png differ diff --git a/en/application-dev/media/figures/audio-encode.png b/en/application-dev/media/figures/audio-encode.png index 06be355cc372f7d8fc5614268f4358bbcea1e1a3..f36aca830c3d8831f53cfec1deb77ddf56d0ccac 100644 Binary files a/en/application-dev/media/figures/audio-encode.png and b/en/application-dev/media/figures/audio-encode.png differ diff --git a/en/application-dev/media/figures/video-decode.png b/en/application-dev/media/figures/video-decode.png new file mode 100644 index 0000000000000000000000000000000000000000..cb3fd0f7351359d83572f89605c5c99a306740ba Binary files /dev/null and b/en/application-dev/media/figures/video-decode.png differ diff --git a/en/application-dev/media/figures/video-encode.png b/en/application-dev/media/figures/video-encode.png new file mode 100644 index 0000000000000000000000000000000000000000..4f29b68813155f2b79b3f5cd6d8756f9c28bcfd5 Binary files /dev/null and b/en/application-dev/media/figures/video-encode.png differ diff --git a/en/application-dev/media/video-decoding.md b/en/application-dev/media/video-decoding.md index 7e1dd04c05bb519b1c16cb480050f4625967a474..a267a9195cade7bcb44eecbbeba30450d686eb4f 100644 --- a/en/application-dev/media/video-decoding.md +++ b/en/application-dev/media/video-decoding.md @@ -15,21 +15,24 @@ Video software decoding and hardware decoding are different. When a decoder is c Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API reference. +The figure below shows the call relationship of video decoding. + +![Call relationship of video decoding](figures/video-decode.png) + 1. Create a decoder instance. You can create a decoder by name or MIME type. ``` c++ - // Create a decoder by name. + // To create a decoder by name, call OH_AVCapability_GetName to obtain the codec names available and then call OH_VideoDecoder_CreateByName. If your application has special requirements, for example, expecting a decoder that supports a certain resolution, you can call OH_AVCodec_GetCapability to query the capability first. OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false); const char *name = OH_AVCapability_GetName(capability); - OH_AVCodec *videoDec = OH_VideoDecoder_CreateByName(name); // name:"OH.Media.Codec.Decoder.Video.AVC" + OH_AVCodec *videoDec = OH_VideoDecoder_CreateByName(name); ``` ```c++ // Create a decoder by MIME type. - // Create an H.264 decoder for software/hardware decoding. + // Create an H.264 decoder for software/hardware decoding. The system creates the most appropriate decoder if multiple decoders are available. OH_AVCodec *videoDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC); - // Create a decoder by MIME type. // Create an H.265 decoder for hardware decoding. OH_AVCodec *videoDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_HEVC); ``` @@ -54,30 +57,32 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: - - **OnError**, a callback used to report a codec operation error - - **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, stream width or height change. - - **OnInputBufferAvailable**, a callback used to report input data required, which means that the decoder is ready for receiving data - - **OnOutputBufferAvailable**, a callback used to report output data generated, which means that decoding is complete (Note: The **data** parameter in the callback function is empty in surface output mode.) + - **OH_AVCodecOnError**, a callback used to report a codec operation error + - **OH_AVCodecOnStreamChanged**, a callback used to report a codec stream change, for example, stream width or height change. + - **OH_AVCodecOnNeedInputData**, a callback used to report input data required, which means that the decoder is ready for receiving data + - **OH_AVCodecOnNewOutputData**, a callback used to report output data generated, which means that decoding is complete (Note: The **data** parameter in the callback function is empty in surface output mode.) You need to process the callback functions to ensure that the decoder runs properly. ``` c++ - // Set the OnError callback function. + // Implement the OH_AVCodecOnError callback function. static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) { (void)codec; (void)errorCode; (void)userData; } - // Set the OnOutputFormatChanged callback function. - static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) + + // Implement the OH_AVCodecOnStreamChanged callback function. + static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) { (void)codec; (void)format; (void)userData; } - // Set the OnInputBufferAvailable callback function, which is used to obtain the input frame information. - static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData) + + // Implement the OH_AVCodecOnNeedInputData callback function. + static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData) { (void)codec; VDecSignal *signal_ = static_cast(userData); @@ -88,8 +93,9 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe signal_->inBufferQueue_.push(data); signal_->inCond_.notify_all(); } - // Set the OnOutputBufferAvailable callback function, which is used to obtain the output frame information. - static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr, + + // Implement the OH_AVCodecOnNewOutputData callback function. + static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr, void *userData) { (void)codec; @@ -102,7 +108,7 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe signal_->attrQueue_.push(*attr); signal_->outCond_.notify_all(); } - OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable}; + OH_AVCodecAsyncCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputData, &OnNeedOutputData}; // Set the asynchronous callbacks. int32_t ret = OH_VideoDecoder_SetCallback(videoDec, cb, signal_); ``` @@ -146,7 +152,7 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe ``` 5. (Optional) Configure the surface parameters of the decoder. This step is required only when the surface is used. - + ``` c++ OH_AVFormat *format = OH_AVFormat_Create(); // Configure the display rotation angle. @@ -179,7 +185,7 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe ``` c++ // Configure the buffer information. OH_AVCodecBufferAttr info; - // Call av_packet_alloc to initialize and return a container packet. + // Call av_packet_alloc of FFmpeg to initialize and return a container packet. AVPacket pkt = av_packet_alloc(); // Configure the input size, offset, and timestamp of the buffer. info.size = pkt->size; @@ -208,9 +214,9 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe ``` 9. (Optional) Call **OH_VideoDecoder_Flush()** to refresh the decoder. - + After **OH_VideoDecoder_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed. - + To continue decoding, you must call **OH_VideoDecoder_Start()** again. ``` c++ @@ -225,7 +231,7 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe ``` 10. (Optional) Call **OH_VideoDecoder_Reset()** to reset the decoder. - + After **OH_VideoDecoder_Reset()** is called, the decoder returns to the initialized state. To continue decoding, you must call **OH_VideoDecoder_Configure()** and then **OH_VideoDecoder_Start()**. ``` c++ @@ -240,7 +246,7 @@ Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API refe ``` 11. Call **OH_VideoDecoder_Stop()** to stop the decoder. - + ``` c++ int32_t ret; // Stop the decoder. diff --git a/en/application-dev/media/video-encoding.md b/en/application-dev/media/video-encoding.md index 410922d95b5e66cb2ceab1aee20640a13283d54b..fee759c06f0baaf2c57ee0a4068a68af2048e5ed 100644 --- a/en/application-dev/media/video-encoding.md +++ b/en/application-dev/media/video-encoding.md @@ -29,14 +29,19 @@ For details about the development procedure, see [Buffer Input](#buffer-input) a Read [VideoEncoder](../reference/native-apis/_video_encoder.md) for the API reference. +The figure below shows the call relationship of video encoding. + +![Call relationship of video encoding](figures/video-encode.png) + ### Buffer Input The following walks you through how to implement the entire video encoding process in buffer input mode. It uses the YUV file input and H.264 encoding format as an example. + Currently, the **VideoEncoder** module supports only data transferring in asynchronous mode. 1. Create an encoder instance. - You can create an encoder by name or Multipurpose Internet Mail Extensions (MIME) type. + You can create an encoder by name or MIME type. ``` c++ // To create an encoder by MIME type, call OH_VideoEncoder_CreateByMime. The system creates the most appropriate encoder based on the MIME type. @@ -58,15 +63,15 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers: - - **OnError**, a callback used to report a codec operation error - - **OnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change - - **OnNeedInputData**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data - - **OnNeedOutputData**, a callback used to report output data generated, which means that encoding is complete + - **OH_AVCodecOnError**, a callback used to report a codec operation error + - **OH_AVCodecOnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OH_AVCodecOnNeedInputData**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data + - **OH_AVCodecOnNewOutputData**, a callback used to report output data generated, which means that encoding is complete You need to process the callback functions to ensure that the encoder runs properly. ``` c++ - // Set the OnError callback function. + // Implement the OH_AVCodecOnError callback function. static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) { (void)codec; @@ -74,7 +79,7 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch (void)userData; } - // Set the OnStreamChanged callback function. + // Implement the OH_AVCodecOnStreamChanged callback function. static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) { (void)codec; @@ -82,7 +87,7 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch (void)userData; } - // Set the OnNeedInputData callback function, which is used to send an input frame to the data queue. + // Implement the OH_AVCodecOnNeedInputData callback function. static void OnNeedInputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *mem, void *userData) { (void)userData; @@ -92,8 +97,8 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch // 7. Write the stream to encode. // 8. Notify the encoder of EOS. } - - // Set the OnNeedOutputData callback function, which is used to send an encoded frame to the output queue. + + // Implement the OH_AVCodecOnNewOutputData callback function. static void OnNeedOutputData(OH_AVCodec *codec, uint32_t index, OH_AVMemory *mem, OH_AVCodecBufferAttr *attr, void *userData) { @@ -259,7 +264,7 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch 9. Call **OH_VideoEncoder_FreeOutputData()** to output the encoded frames. - In the code snippet below, the following parameters are used: + In the code snippet below, the following parameters are used: - **index**: index of the data queue, which is passed in by the callback function **OnNeedOutputData**. - **attr**: buffer storing the output data, which is passed in by the callback function **OnNeedOutputData**. - **mem**: parameter passed in by the callback function **OnNeedOutputData**. You can call **OH_AVMemory_GetAddr** to obtain the pointer to the shared memory address. @@ -424,9 +429,9 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch Currently, the following options must be configured for all supported formats: video frame width, video frame height, and video pixel format. In the code snippet below, the following data is used: - - **DEFAULT_WIDTH**: 320 pixels - - **DEFAULT_HEIGHT**: 240 pixels - - **DEFAULT_PIXELFORMAT**: **VideoPixelFormat::YUV420P** (the pixel format of the YUV file is YUV420P) + - **DEFAULT_WIDTH**: 320 pixels + - **DEFAULT_HEIGHT**: 240 pixels + - **DEFAULT_PIXELFORMAT**: **VideoPixelFormat::YUV420P** (the pixel format of the YUV file is YUV420P) ``` c++ // (Mandatory) Configure the video frame width. @@ -547,7 +552,7 @@ Currently, the **VideoEncoder** module supports only data transferring in asynch 10. Call **OH_VideoEncoder_FreeOutputData()** to output the encoded frames. - In the code snippet below, the following parameters are used: + In the code snippet below, the following parameters are used: - **index**: index of the data queue, which is passed in by the callback function **OnNeedOutputData**. - **attr**: buffer storing the output data, which is passed in by the callback function **OnNeedOutputData**. - **mem**: parameter passed in by the callback function **OnNeedOutputData**. You can call **OH_AVMemory_GetAddr** to obtain the pointer to the shared memory address. diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 162a07f752491d75d2bf17a3c90520155fd3672f..ad566d55f740fd7ada74fe22b95e0f1824271c2d 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -8,3 +8,4 @@ - [Using MindSpore Lite for Offline Model Conversion and Inference](mindspore-lite-offline-model-guidelines.md) - [Connecting the Neural Network Runtime to an AI Inference Framework](neural-network-runtime-guidelines.md) - [Purgeable Memory Development](purgeable-memory-guidelines.md) +- [USB DDK Development](usb-ddk-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md index c341703ff86d6d0e3c6a34e8270e934b33a15d3a..1609d8a3410247b328def9aa96e095d2f0d3bbea 100644 --- a/en/application-dev/napi/drawing-guidelines.md +++ b/en/application-dev/napi/drawing-guidelines.md @@ -2,13 +2,13 @@ ## When to Use -The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development: +The **NativeDrawing** module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development: * Drawing 2D graphics * Drawing text drawing ## Available APIs -| API| Description| +| API| Description| | -------- | -------- | | OH_Drawing_BitmapCreate (void) | Creates a bitmap object.| | OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.| @@ -31,7 +31,7 @@ The Native Drawing module provides APIs for drawing 2D graphics and text. The fo | OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.| | OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.| - +For details about the APIs, see [Drawing](../reference/native-apis/_drawing.md). ## Development Procedure for 2D Graphics Drawing diff --git a/en/application-dev/napi/native-buffer-guidelines.md b/en/application-dev/napi/native-buffer-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..b45c43f77e6d63aac676327bc971d9eeb0609259 --- /dev/null +++ b/en/application-dev/napi/native-buffer-guidelines.md @@ -0,0 +1,78 @@ +# NativeBuffer Development + +## When to Use + +The **NativeBuffer** module provides APIs for you to apply for, use, and release the shared memory, and query memory properties. + +The following scenario is common for **NativeBuffer** development: + +Use the native APIs provided by **NativeBuffer** to create an **OH_NativeBuffer** instance, obtain memory properties, and map the corresponding ION memory to the process address space. + +## Available APIs + +| API| Description| +| -------- | -------- | +| OH_NativeBuffer_Alloc (const OH_NativeBuffer_Config \*config) | Creates an **OH_NativeBuffer** instance based on an **OH_NativeBuffer_Config** struct. A new **OH_NativeBuffer** instance is created each time this function is called.| +| OH_NativeBuffer_Reference (OH_NativeBuffer \*buffer) | Increases the reference count of an **OH_NativeBuffer** instance by 1.| +| OH_NativeBuffer_Unreference (OH_NativeBuffer \*buffer) | Decreases the reference count of an **OH_NativeBuffer** instance by 1 and, when the reference count reaches 0, destroys the instance.| +| OH_NativeBuffer_GetConfig (OH_NativeBuffer \*buffer, OH_NativeBuffer_Config \*config) | Obtains the properties of an **OH_NativeBuffer** instance.| +| OH_NativeBuffer_Map (OH_NativeBuffer \*buffer, void \*\*virAddr) | Maps the ION memory corresponding to an **OH_NativeBuffer** instance to the process address space.| +| OH_NativeBuffer_Unmap (OH_NativeBuffer \*buffer) | Unmaps the ION memory corresponding to an **OH_NativeBuffer** instance from the process address space.| +| OH_NativeBuffer_GetSeqNum (OH_NativeBuffer \*buffer) | Obtains the sequence number of an **OH_NativeBuffer** instance.| + +For details about the APIs, see [native_buffer](../reference/native-apis/_o_h___native_buffer.md). + +## How to Develop + +The following describes how to use the native APIs provided by **NativeBuffer** to create an **OH_NativeBuffer** instance, obtain memory properties, and map the corresponding ION memory to the process address space. + +**Header File** +```c++ +#include +``` + +1. Create an **OH_NativeBuffer** instance. + ```c++ + OH_NativeBuffer_Config config { + .width = 0x100, + .height = 0x100, + }; + OH_NativeBuffer* buffer = OH_NativeBuffer_Alloc(&config); + if (buffer == nullptr) { + std::cout << "OH_NativeBuffer_Alloc Failed" << std::endl; + } + ``` + +2. Map the ION memory corresponding to the **OH_NativeBuffer** instance to the process address space by calling **OH_NativeBuffer_Map**, if the application needs to access the memory space of the buffer. + ```c++ + // Map the ION memory to the process address space. + void* virAddr = nullptr; + int32_t ret = OH_NativeBuffer_Map(buffer, &virAddr); // After mapping, the start address of the memory is returned through the parameter virAddr. + if (ret != 0) { + std::cout << "OH_NativeBuffer_Map Failed" << std::endl; + } + + // Unmap the ION memory from the process address space when it is no longer needed. + ret = OH_NativeBuffer_Unmap(buffer); + if (ret != 0) { + std::cout << "OH_NativeBuffer_Unmap Failed" << std::endl; + } + ``` + +3. Obtain the memory properties. + ```c++ + // Obtain the properties of the OH_NativeBuffer instance. + OH_NativeBuffer_Config config = {}; + OH_NativeBuffer_GetConfig(buffer, &config); + // Obtain the sequence number of the OH_NativeBuffer instance. + uint32_t hwBufferID = OH_NativeBuffer_GetSeqNum(buffer); + ``` + +4. Destroy the **OH_NativeBuffer** instance. + ```c++ + // Call OH_NativeBuffer_Unreference to decrease the reference count by 1. When the reference count reaches 0, the instance is destroyed. + ret = OH_NativeBuffer_Unreference(buffer); + if (ret != 0) { + std::cout << "OH_NativeBuffer_Unreference Failed" << std::endl; + } + ``` diff --git a/en/application-dev/napi/native-image-guidelines.md b/en/application-dev/napi/native-image-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..10142f438059908cef4320b5d01e2029cf6cfe16 --- /dev/null +++ b/en/application-dev/napi/native-image-guidelines.md @@ -0,0 +1,230 @@ +# NativeImage Development + +## When to Use + +**NativeImage** is a module provided by OpenHarmony for associating a surface with a OpenGL external texture. It functions as the consumer of a graphics queue. It provides APIs for you to obtain and use a buffer, and output the buffer content to a OpenGL external texture. + +The following scenario is common for **NativeImage** development: + +Use the native APIs provided by **NativeImage** to create a **NativeImage** instance as the consumer and obtain the corresponding **NativeWindow** instance (functioning as the producer). Use the APIs provided by **NativeWindow** to fill in and flush the buffer, and then use the APIs provided by **NativeImage** to update the buffer content to a OpenGL ES texture. The **NativeImage** module must be used together with the **NativeWindow**, **NativeBuffer**, **EGL**, and **GLES3** modules. + +## Available APIs + +| API| Description| +| -------- | -------- | +| OH_NativeImage_Create (uint32_t textureId, uint32_t textureTarget) | Creates an **OH_NativeImage** instance to be associated with the OpenGL ES texture ID and target.| +| OH_NativeImage_AcquireNativeWindow (OH_NativeImage \*image) | Obtains a **NativeWindow** instance associated with an **OH_NativeImage** instance. You need to call **OH_NativeWindow_DestroyNativeWindow** to release the **NativeWindow** instance when it is no longer needed.| +| OH_NativeImage_AttachContext (OH_NativeImage \*image, uint32_t textureId) | Attaches an **OH_NativeImage** instance to the current OpenGL ES context. The OpenGL ES texture will be bound to an **GL_TEXTURE_EXTERNAL_OES** instance and updated through the **OH_NativeImage** instance.| +| OH_NativeImage_DetachContext (OH_NativeImage \*image) | Detaches an **OH_NativeImage** instance from the current OpenGL ES context.| +| OH_NativeImage_UpdateSurfaceImage (OH_NativeImage \*image) | Updates the OpenGL ES texture associated with the latest frame through an **OH_NativeImage** instance.| +| OH_NativeImage_GetTimestamp (OH_NativeImage \*image) | Obtains the timestamp of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.| +| OH_NativeImage_GetTransformMatrix (OH_NativeImage \*image, float matrix[16]) | Obtains the transform matrix of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.| +| OH_NativeImage_Destroy (OH_NativeImage \*\*image) | Destroys an **OH_NativeImage** instance created by calling **OH_NativeImage_Create**. After the instance is destroyed, the pointer to the **OH_NativeImage** instance is assigned **NULL**.| + +For details about the APIs, see [native_image](../reference/native-apis/_o_h___native_image.md). + +## How to Develop + +The following steps describe how to use the native APIs provided by **NativeImage** to create an **OH_NativeImage** instance as the consumer and update the data to a OpenGL external texture. + +**Header File** +```c++ +#include +#include +#include +#include +#include +#include +``` + +1. Initialize the EGL environment. + + Refer to the code snippet below. + ```c++ + #include + #include + using GetPlatformDisplayExt = PFNEGLGETPLATFORMDISPLAYEXTPROC; + constexpr const char* EGL_EXT_PLATFORM_WAYLAND = "EGL_EXT_platform_wayland"; + constexpr const char* EGL_KHR_PLATFORM_WAYLAND = "EGL_KHR_platform_wayland"; + constexpr int32_t EGL_CONTEXT_CLIENT_VERSION_NUM = 2; + constexpr char CHARACTER_WHITESPACE = ' '; + constexpr const char* CHARACTER_STRING_WHITESPACE = " "; + constexpr const char* EGL_GET_PLATFORM_DISPLAY_EXT = "eglGetPlatformDisplayEXT"; + EGLContext eglContext_ = EGL_NO_CONTEXT; + EGLDisplay eglDisplay_ = EGL_NO_DISPLAY; + static inline EGLConfig config_; + + // Check the EGL extension. + static bool CheckEglExtension(const char* extensions, const char* extension) + { + size_t extlen = strlen(extension); + const char* end = extensions + strlen(extensions); + + while (extensions < end) { + size_t n = 0; + if (*extensions == CHARACTER_WHITESPACE) { + extensions++; + continue; + } + n = strcspn(extensions, CHARACTER_STRING_WHITESPACE); + if (n == extlen && strncmp(extension, extensions, n) == 0) { + return true; + } + extensions += n; + } + return false; + } + + // Obtain the display. + static EGLDisplay GetPlatformEglDisplay(EGLenum platform, void* native_display, const EGLint* attrib_list) + { + static GetPlatformDisplayExt eglGetPlatformDisplayExt = NULL; + + if (!eglGetPlatformDisplayExt) { + const char* extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); + if (extensions && + (CheckEglExtension(extensions, EGL_EXT_PLATFORM_WAYLAND) || + CheckEglExtension(extensions, EGL_KHR_PLATFORM_WAYLAND))) { + eglGetPlatformDisplayExt = (GetPlatformDisplayExt)eglGetProcAddress(EGL_GET_PLATFORM_DISPLAY_EXT); + } + } + + if (eglGetPlatformDisplayExt) { + return eglGetPlatformDisplayExt(platform, native_display, attrib_list); + } + + return eglGetDisplay((EGLNativeDisplayType)native_display); + } + + static void InitEGLEnv() + { + // Obtain the display. + eglDisplay_ = GetPlatformEglDisplay(EGL_PLATFORM_OHOS_KHR, EGL_DEFAULT_DISPLAY, NULL); + if (eglDisplay_ == EGL_NO_DISPLAY) { + std::cout << "Failed to create EGLDisplay gl errno : " << eglGetError() << std::endl; + } + + EGLint major, minor; + // Initialize the EGL display. + if (eglInitialize(eglDisplay_, &major, &minor) == EGL_FALSE) { + std::cout << "Failed to initialize EGLDisplay" << std::endl; + } + + // Bind the OpenGL ES API. + if (eglBindAPI(EGL_OPENGL_ES_API) == EGL_FALSE) { + std::cout << "Failed to bind OpenGL ES API" << std::endl; + } + + unsigned int ret; + EGLint count; + EGLint config_attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_NONE }; + + // Obtain a valid system configuration. + ret = eglChooseConfig(eglDisplay_, config_attribs, &config_, 1, &count); + if (!(ret && static_cast(count) >= 1)) { + std::cout << "Failed to eglChooseConfig" << std::endl; + } + + static const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, EGL_CONTEXT_CLIENT_VERSION_NUM, EGL_NONE }; + + // Create a context. + eglContext_ = eglCreateContext(eglDisplay_, config_, EGL_NO_CONTEXT, context_attribs); + if (eglContext_ == EGL_NO_CONTEXT) { + std::cout << "Failed to create egl context %{public}x, error:" << eglGetError() << std::endl; + } + + // Associate the context. + eglMakeCurrent(eglDisplay_, EGL_NO_SURFACE, EGL_NO_SURFACE, eglContext_); + + // The EGL environment initialization is complete. + std::cout << "Create EGL context successfully, version" << major << "." << minor << std::endl; + } + ``` + +2. Create an **OH_NativeImage** instance. + ```c++ + // Create an OpenGL ES texture. + GLuint textureId; + glGenTextures(1, &textureId); + // Create an OH_NativeImage instance, which will be associated with an OpenGL ES texture. + OH_NativeImage* image = OH_NativeImage_Create(textureId, GL_TEXTURE_2D); + ``` + +3. Obtain a **NativeWindow** instance that functions as the producer. + ```c++ + // Obtain a NativeWindow instance. + OHNativeWindow* nativeWindow = OH_NativeImage_AcquireNativeWindow(image); + ``` + +4. Write the produced content to a **NativeWindowBuffer** instance. + 1. Obtain a NativeWindowBuffer instance from the NativeWindow instance. + ```c++ + OHNativeWindowBuffer* buffer = nullptr; + int fenceFd; + // Obtain a NativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer. + OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow, &buffer, &fenceFd); + + BufferHandle *handle = OH_NativeWindow_GetBufferHandleFromNative(buffer); + int code = SET_BUFFER_GEOMETRY; + int32_t width = 0x100; + int32_t height = 0x100; + ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); + ``` + 3. Write the produced content to the **NativeWindowBuffer** instance. + ```c++ + static uint32_t value = 0x00; + value++; + uint32_t *pixel = static_cast(handle->virAddr); + for (uint32_t x = 0; x < width; x++) { + for (uint32_t y = 0; y < height; y++) { + *pixel++ = value; + } + } + ``` + 4. Flush the **NativeWindowBuffer** to the **NativeWindow**. + ```c++ + // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the NativeWindowBuffer 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); + ``` + 5. Destroy the **NativeWindow** instance when it is no longer needed. + ```c++ + OH_NativeWindow_DestroyNativeWindow(nativeWindow); + ``` + +5. Update the content to the OpenGL texture. + ```c++ + // Update the content to the OpenGL texture. + int32_t ret = OH_NativeImage_UpdateSurfaceImage(image); + if (ret != 0) { + std::cout << "OH_NativeImage_UpdateSurfaceImage failed" << std::endl; + } + // Obtain the timestamp and transform matrix of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function. + int64_t timeStamp = OH_NativeImage_GetTimestamp(image); + float matrix[16]; + ret = OH_NativeImage_GetTransformMatrix(image, matrix); + if (ret != 0) { + std::cout << "OH_NativeImage_GetTransformMatrix failed" << std::endl; + } + ``` + +6. Unbind the OpenGL texture and bind it to a new external texture. + ```c++ + // Detach an OH_NativeImage instance from the current OpenGL ES context. + ret = OH_NativeImage_DetachContext(image); + if (ret != 0) { + std::cout << "OH_NativeImage_DetachContext failed" << std::endl; + } + // Attach the OH_NativeImage instance to the current OpenGL ES context. The OpenGL ES texture will be bound to an GL_TEXTURE_EXTERNAL_OES instance and updated through the OH_NativeImage instance. + GLuint textureId2; + glGenTextures(1, &textureId2); + ret = OH_NativeImage_AttachContext(image, textureId2); + ``` + +7. Destroy the **OH_NativeImage** instance when it is no longer needed. + ```c++ + // Destroy the OH_NativeImage instance. + OH_NativeImage_Destroy(&image); + ``` diff --git a/en/application-dev/napi/native-vsync-guidelines.md b/en/application-dev/napi/native-vsync-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..548a791e97ee75a1ee4ad83123893c5495181b59 --- /dev/null +++ b/en/application-dev/napi/native-vsync-guidelines.md @@ -0,0 +1,56 @@ +# NativeVSync Development + +## When to Use + +The **NativeVSync** module is used to obtain virtual synchronization (VSync) signals from the system. It provides APIs for creating and destroying an **OH_NativeVSync** instance and setting the VSync callback function, which is triggered when a VSync signal arrives. + +## Available APIs + +| API| Description:| +| -------- | -------- | +| OH_NativeVSync_Create (const char \*name, unsigned int length) | Creates an **OH_NativeVSync** instance. A new **OH_NativeVSync** instance is created each time this function is called.| +| OH_NativeVSync_Destroy (OH_NativeVSync \*nativeVsync) | Destroys an **OH_NativeVSync** instance.| +| OH_NativeVSync_FrameCallback (long long timestamp, void \*data) | Sets a callback function. **timestamp** indicates the timestamp, and **data** indicates the input parameter of the callback function. | +| OH_NativeVSync_RequestFrame (OH_NativeVSync \*nativeVsync, OH_NativeVSync_FrameCallback callback, void \*data) | Requests the next VSync signal. When the signal arrives, a callback function is invoked.| + +For details about the APIs, see [native_vsync](../reference/native-apis/_native_vsync.md). + +## How to Develop + +The following steps describe how to use the native APIs provided by **NativeVSync** to create and destroy an **OH_NativeVSync** instance and set the VSync callback function. + +**Header File** +```c++ +#include +``` + +1. Prepare a VSync callback function. + ```c++ + static bool flag = false; + static void OnVSync(long long timestamp, void* data) + { + flag = true; + std::cout << "OnVSync: " << timestamp << std::endl; + } + OH_NativeVSync_FrameCallback callback = OnVSync; // The callback function must be of the OH_NativeVSync_FrameCallback type. + ``` +2. Create an **OH_NativeVSync** instance. + ```c++ + char name[] = "hello_vsync"; + OH_NativeVSync* nativeVSync = OH_NativeVSync_Create(name, strlen(name)); + ``` + +3. Set the VSync callback function through the **OH_NativeVSync** instance. + ```c++ + OH_NativeVSync_RequestFrame(nativeVSync, callback, nullptr); + while (!flag) { // Check the flag value. The while loop exits only after the VSync callback function is executed, indicating that a VSync signal is received. + std::cout << "wait for vsync!\n"; + sleep(1); + } + std::cout << "vsync come, end this thread\n"; + ``` + +4. Destroy the **OH_NativeVSync** instance. + ```c++ + OH_NativeVSync_Destroy(nativeVSync); // Destroy the OH_NativeVSync instance when the application does not need to receive VSync signals. + ``` diff --git a/en/application-dev/napi/native-window-guidelines.md b/en/application-dev/napi/native-window-guidelines.md index f5a5ead9c083217c77692b34384f969c4b44dc00..4f39be0a9b311d28b1a6551eac728484893a948f 100644 --- a/en/application-dev/napi/native-window-guidelines.md +++ b/en/application-dev/napi/native-window-guidelines.md @@ -1,39 +1,34 @@ -# Native Window Development +# NativeWindow Development ## When to Use -**NativeWindow** is a local platform-based window of OpenHarmony that represents the producer of a graphics queue. It provides APIs for you to create a native window from **Surface**, create a native window buffer from **SurfaceBuffer**, and request and flush a buffer. -The following scenarios are common for native window development: +**NativeWindow** is a local platform-based window of OpenHarmony that represents the producer of a graphics queue. It provides APIs for you to request and flush a buffer and configure buffer attributes. -* Request a graphics buffer by using the NAPI provided by **NativeWindow**, write the produced graphics content to the buffer, and flush the buffer to the graphics queue. +The following scenarios are common for NativeWindow development: + +* Request a graphics buffer by using the native API provided by **NativeWindow**, write the produced graphics content to the buffer, and flush the buffer to the graphics queue. * Request and flush a buffer when adapting to the **eglswapbuffer** interface at the EGL. ## Available APIs | API| Description| | -------- | -------- | -| OH_NativeWindow_CreateNativeWindowFromSurface (void \*pSurface) | Creates a **NativeWindow** instance. A new **NativeWindow** instance is created each time this function is called.| -| OH_NativeWindow_DestroyNativeWindow (OHNativeWindow \*window) | Decreases the reference count of a **NativeWindow** instance by 1 and, when the reference count reaches 0, destroys the instance.| -| OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void \*pSurfaceBuffer) | Creates a **NativeWindowBuffer** instance. A new **NativeWindowBuffer** instance is created each time this function is called.| -| OH_NativeWindow_DestroyNativeWindowBuffer (OHNativeWindowBuffer \*buffer) | Decreases the reference count of a **NativeWindowBuffer** instance by 1 and, when the reference count reaches 0, destroys the instance.| -| OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests a **NativeWindowBuffer** through a **NativeWindow** instance for content production.| -| OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the **NativeWindowBuffer** filled with the content to the buffer queue through a **NativeWindow** instance for content consumption.| -| OH_NativeWindow_NativeWindowAbortBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer) | Returns the **NativeWindowBuffer** to the buffer queue through a **NativeWindow** instance, without filling in any content. The **NativeWindowBuffer** can be used for another request.| -| OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | Sets or obtains the attributes of a native window, including the width, height, and content format.| -| OH_NativeWindow_GetBufferHandleFromNative (OHNativeWindowBuffer \*buffer) | Obtains the pointer to a **BufferHandle** of a **NativeWindowBuffer** instance.| -| OH_NativeWindow_NativeObjectReference (void \*obj) | Adds the reference count of a native object.| -| OH_NativeWindow_NativeObjectUnreference (void \*obj) | Decreases the reference count of a native object and, when the reference count reaches 0, destroys this object.| -| OH_NativeWindow_GetNativeObjectMagic (void \*obj) | Obtains the magic ID of a native object.| -| OH_NativeWindow_NativeWindowSetScalingMode (OHNativeWindow \*window, uint32_t sequence, OHScalingMode scalingMode) | Sets the scaling mode of the native window.| -| OH_NativeWindow_NativeWindowSetMetaData(OHNativeWindow \*window, uint32_t sequence, int32_t size, const OHHDRMetaData \*metaData) | Sets the HDR static metadata of the native window.| -| OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow \*window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t \*metaData) | Sets the HDR static metadata set of the native window.| -| OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow \*window, const OHExtDataHandle \*handle) | Sets the tunnel handle to the native window.| +| OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests an **OHNativeWindowBuffer** through an **OHNativeWindow** instance for content production.| +| OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the **OHNativeWindowBuffer** filled with the content to the buffer queue through an **OHNativeWindow** instance for content consumption.| +| OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | Sets or obtains the attributes of an **OHNativeWindow**, including the width, height, and content format.| + +For details about the APIs, see [native_window](../reference/native-apis/_native_window.md). ## How to Develop -The following describes how to use the NAPI provided by **NativeWindow** to request a graphics buffer, write the produced graphics content to the buffer, and flush the buffer to the graphics queue. +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. + +**Header File** +```c++ +#include +``` -1. Obtain a **NativeWindow** instance, which can be obtained by running the APIs provided by **OH_NativeXComponent_Callback**. +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. ```ts XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'nativerender'}) @@ -60,25 +55,25 @@ The following describes how to use the NAPI provided by **NativeWindow** to requ // Define the callback. void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) { - // Obtain a NativeWindow instance. + // Obtain an OHNativeWindow instance. OHNativeWindow* nativeWindow = window; // ... } void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window) { - // Obtain a NativeWindow instance. + // Obtain an OHNativeWindow instance. OHNativeWindow* nativeWindow = window; // ... } void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) { - // Obtain a NativeWindow instance. + // Obtain an OHNativeWindow instance. OHNativeWindow* nativeWindow = window; // ... } void DispatchTouchEventCB(OH_NativeXComponent* component, void* window) { - // Obtain a NativeWindow instance. + // Obtain an OHNativeWindow instance. OHNativeWindow* nativeWindow = window; // ... } @@ -96,38 +91,30 @@ The following describes how to use the NAPI provided by **NativeWindow** to requ OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback_); ``` -2. Set the attributes of a native window buffer by using **OH_NativeWindow_NativeWindowHandleOpt**. +2. Set the attributes of an **OHNativeWindowBuffer** by using **OH_NativeWindow_NativeWindowHandleOpt**. ```c++ - // Set the read and write scenarios of the native window buffer. - int code = SET_USAGE; - int32_t usage = BUFFER_USAGE_CPU_READ | BUFFER_USAGE_CPU_WRITE | BUFFER_USAGE_MEM_DMA; - int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, usage); - // Set the width and height of the native window buffer. + // Set the width and height of the OHNativeWindowBuffer. code = SET_BUFFER_GEOMETRY; int32_t width = 0x100; int32_t height = 0x100; ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height); - // Set the step of the native window buffer. + // Set the step of the OHNativeWindowBuffer. code = SET_STRIDE; int32_t stride = 0x8; ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, stride); - // Set the format of the native window buffer. - code = SET_FORMAT; - int32_t format = PIXEL_FMT_RGBA_8888; - ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, format); ``` -3. Request a native window buffer from the graphics queue. +3. Request an **OHNativeWindowBuffer** from the graphics queue. ```c++ - struct NativeWindowBuffer* buffer = nullptr; + OHNativeWindowBuffer* buffer = nullptr; int fenceFd; - // Obtain the NativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer. + // 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); ``` -4. Write the produced content to the native window buffer. +4. Write the produced content to the **OHNativeWindowBuffer**. ```c++ auto image = static_cast(buffer->sfbuffer->GetVirAddr()); static uint32_t value = 0x00; @@ -141,9 +128,9 @@ The following describes how to use the NAPI provided by **NativeWindow** to requ } ``` -5. Flush the native window buffer to the graphics queue. +5. Flush the **OHNativeWindowBuffer** to the graphics queue. ```c++ - // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the native window buffer are changed. + // 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); diff --git a/en/application-dev/napi/usb-ddk-guidelines.md b/en/application-dev/napi/usb-ddk-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..708a82dc905ce78b9f3823269c2bef392d595046 --- /dev/null +++ b/en/application-dev/napi/usb-ddk-guidelines.md @@ -0,0 +1,79 @@ +# USB DDK Development + +## When to Use + +USB Driver Development Kit (USB DDK) is a tool kit provided by OpenHarmony to help you develop USB device drivers for your applications based on the user mode. It provides a series of device access APIs, which implement functions such as opening and closing USB interfaces, performing non-isochronous and isochronous data transfer, and implementing control transfer and interrupt transfer over USB pipes, etc. + +## Available APIs + +| Name| Description| +| -------- | -------- | +| OH_Usb_Init(void) | Initializes the DDK.| +| OH_Usb_Release(void) | Releases the DDK.| +| OH_Usb_GetDeviceDescriptor(uint64_t deviceId, struct UsbDeviceDescriptor *desc) | Obtains the device descriptor.| +| OH_Usb_GetConfigDescriptor(uint64_t deviceId, uint8_t configIndex, struct UsbDdkConfigDescriptor **const config) | Obtains the configuration descriptor. To avoid memory leakage, use **OH_Usb_FreeConfigDescriptor()** to release a descriptor after use.| +| OH_Usb_FreeConfigDescriptor(const struct UsbDdkConfigDescriptor *const config) | Releases a configuration descriptor. To avoid memory leakage, release a descriptor after use.| +| OH_Usb_ClaimInterface(uint64_t deviceId, uint8_t interfaceIndex, uint64_t *interfaceHandle) | Declares a USB interface.| +| OH_Usb_ReleaseInterface(uint64_t interfaceHandle) | Releases a USB interface.| +| OH_Usb_SendPipeRequest(const struct UsbRequestPipe *pipe, UsbDeviceMemMap *devMmap) | Sends a pipe request. This API works in a synchronous manner. It applies to interrupt transfer and bulk transfer.| +| OH_Usb_CreateDeviceMemMap(uint64_t deviceId, size_t size, UsbDeviceMemMap **devMmap) | Creates a buffer. To avoid memory leakage, use **OH_Usb_DestroyDeviceMemMap()** to destroy a buffer after use.| +| OH_Usb_DestroyDeviceMemMap(UsbDeviceMemMap *devMmap) | Destroys a buffer. To avoid resource leakage, destroy a buffer in time after use.| + +For details about the APIs, see [USB DDK](../reference/native-apis/_usb_ddk.md). + +## How to Develop + +To develop a USB driver using the USB DDK in OpenHarmony, perform the following steps: + +1. Obtain the device descriptor. Initialize the DDK by calling **OH_Usb_Init** of **usb_ddk_api.h**, and obtain the device descriptor by calling **OH_Usb_GetDeviceDescriptor**. + + ```c++ + // Initialize the USB DDK. + OH_Usb_Init(); + struct UsbDeviceDescriptor devDesc; + uint64_t deviceId = 0; + // Obtain the device descriptor. + OH_Usb_GetDeviceDescriptor(deviceId, &devDesc); + ``` + +2. Obtain the configuration descriptor, and declare the USB interface. Obtain the configuration descriptor **config** by calling **OH_Usb_GetConfigDescriptor** of **usb_ddk_api.h**, and declare the USB interface by calling **OH_Usb_ClaimInterface**. + + ```c++ + struct UsbDdkConfigDescriptor *config = nullptr; + // Obtain the configuration descriptor. + OH_Usb_GetConfigDescriptor(deviceId, 1, &config); + // Obtain the index of the target USB interface based on the configuration descriptor. + uint8_t interfaceIndex = 0; + // Declare the USB interface. + uint64_t interfaceHandle = 0; + OH_Usb_ClaimInterface(deviceId, interfaceIndex, &interfaceHandle); + // Release the configuration descriptor. + OH_Usb_FreeConfigDescriptor(config); + ``` + +3. Create a device memory map, and send a request. Create the device memory map **devMmap** by calling **OH_Usb_CreateDeviceMemMap** of **usb_ddk_api.h**, and send a request by calling **OH_Usb_SendPipeRequest**. + + ```c++ + struct UsbDeviceMemMap *devMmap = nullptr; + // Create a buffer for storing data. + size_t bufferLen = 10; + OH_Usb_CreateDeviceMemMap(deviceId, bufferLen, &devMmap); + struct UsbRequestPipe pipe; + pipe.interfaceHandle = interfaceHandle; + // Obtain the target endpoint based on the configuration descriptor. + pipe.endpoint = 128; + pipe.timeout = UINT32_MAX; + // Send a request. + OH_Usb_SendPipeRequest(&pipe, devMmap); + ``` + +4. Release resources. After all requests are processed and before the application exits, destroy the buffer by calling **OH_Usb_DestroyDeviceMemMap** of **usb_ddk_api.h** to release resources. Release the USB interface by calling **OH_Usb_ReleaseInterface**. Release the USB DDK by calling **OH_Usb_Release**. + + ```c++ + // Destroy the buffer. + OH_Usb_DestroyDeviceMemMap(devMmap); + // Release the USB interface. + OH_Usb_ReleaseInterface(interfaceHandle); + // Release the USB DDK. + OH_Usb_Release(); + ``` diff --git a/en/application-dev/napi/vulkan-guidelines.md b/en/application-dev/napi/vulkan-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..e55b53cd38d44fb5d5a893cdbc21d175b9b0c8df --- /dev/null +++ b/en/application-dev/napi/vulkan-guidelines.md @@ -0,0 +1,113 @@ +# Vulkan Development + +## When to Use + +Vulkan is a set of graphics APIs for 2D and 3D rendering. Creating a **VkSurfaceKHR** instance is a key step, since **VkSurfaceKHR** work with the **OHNativeWindow** module to implement buffer recycling. + +A **VkSurfaceKHR** instance is obtained through an **OHNativeWindow**, which is obtained from the **\**. Therefore, the **OHNativeWindow** module must be used together with the **XComponent** and **NativeWindow** modules. + +## Available APIs + +| API| Description| +| -------- | -------- | +| vkCreateSurfaceOHOS (VkInstance instance, const VkSurfaceCreateInfoOHOS\* pCreateInfo, const VkAllocationCallbacks\* pAllocator, VkSurfaceKHR\* pSurface) | Creates a **VkSurfaceKHR** instance.| + +For details about the APIs, see [Vulkan](../reference/native-lib/third_party_vulkan/vulkan-symbol.md). + +## How to Develop + +The following steps illustrate how to create a **VkSurfaceKHR** instance. + +**Header File** +```c++ +#include +#include +#include +``` + +1. Create a Vulkan instance. + ```c++ + VkInstance instance = VK_NULL_HANDLE; + + VkApplicationInfo appInfo = {}; + appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + appInfo.pApplicationName = "vulkanExample"; + appInfo.pEngineName = "vulkanExample"; + appInfo.apiVersion = VK_API_VERSION_1_3; + + VkInstanceCreateInfo instanceCreateInfo = {}; + instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + instanceCreateInfo.pNext = NULL; + instanceCreateInfo.pApplicationInfo = &appInfo; + + std::vector instanceExtensions = { + VK_KHR_SURFACE_EXTENSION_NAME, + VK_OHOS_SURFACE_EXTENSION_NAME // Surface extension. + }; + instanceCreateInfo.enabledExtensionCount = static_cast(instanceExtensions.size()); + instanceCreateInfo.ppEnabledExtensionNames = instanceExtensions.data(); + + vkCreateInstance(&instanceCreateInfo, nullptr, &instance); + ``` + +2. Obtain an **OHNativeWindow** instance. + + The **OHNativeWindow** instance is obtained from the **\**. For details about how to use the **\**, see [XComponent](../ui/arkts-common-components-xcomponent.md) and [XComponent Development](xcomponent-guidelines.md). + 1. Add an **\** to **ets/pages/Index.ets**. + ```ts + XComponent({ + id: 'xcomponentId', + type: 'surface', + libraryname: 'entry' + }) + .margin({ bottom: 20 }) + .width(360) + .height(360) + ``` + 2. Obtain an **OHNativeWindow** instance from the **\**. + ```c++ + // Callback function of the \ triggered when a surface is created. + void OnSurfaceCreatedCB(OH_NativeXComponent *component, void *window) { + // You can obtain an OHNativeWindow instance from the callback function. + OHNativeWindow* nativeWindow = static_cast(window); + } + + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + // Declare an XComponent callback. + OH_NativeXComponent_Callback callback; + // Register the OnSurfaceCreated callback function. + callback.OnSurfaceCreated = OnSurfaceCreatedCB; + + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {}; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + napi_value exportInstance = nullptr; + OH_NativeXComponent *nativeXComponent = nullptr; + // Obtain a native XComponent. + napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); + napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + // Register the callback function for the native XComponent. + OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback); + + return exports; + } + ``` + +3. Create a **VkSurfaceKHR** instance. + ```c++ + VkSurfaceKHR surface = VK_NULL_HANDLE; + VkSurfaceCreateInfoOHOS surfaceCreateInfo = {}; + surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_SURFACE_CREATE_INFO_OHOS; + surfaceCreateInfo.window = nativeWindow; // nativeWindow is obtained from the OnSurfaceCreatedCB callback function in the previous step. + int err = vkCreateSurfaceOHOS(instance, &surfaceCreateInfo, NULL, &surface); + if (err != VK_SUCCESS) { + std::cout << "Could not create surface!" << std::endl; + } + ``` +For details about how to use Vulkan, visit the [Vulkan official website](https://www.vulkan.org/). diff --git a/en/application-dev/performance/Readme.md b/en/application-dev/performance/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..8172a210af94348fdb22831295c90a19b74965e6 --- /dev/null +++ b/en/application-dev/performance/Readme.md @@ -0,0 +1,33 @@ +# Best Practices for Application Performance + +This topic outlines some best practices for improving your application performance to live up to user expectations for quick startup, timely response, and no frame freezing. + +Following these practices, you can reduce your application's startup time, response time, and frame loss. + +- Improving application startup and response time + + - [Speeding Up Application Cold Start](../performance/improve-application-startup-and-response/improve-application-cold-start-speed.md) + + Application startup latency is a key factor that affects user experience. To speed up the application cold start, you are advised to perform optimization in the following four phases: + + ​ 1. Application process creation and initialization + + ​ 2. Application and ability initialization + + ​ 3. Ability lifecycle + + ​ 4. Home page loading and drawing + + - [Speeding Up Application Response](../performance/improve-application-startup-and-response/improve-application-response.md) + + A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of component to be refreshed. + +- Reducing frame loss + + - [Reducing Nesting](../performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md) + + The smoothness of rendering the layout to the screen affects the user perceived quality. It is recommended that you minimize nesting in your code to shorten the render time. + + - [Reducing Frame Loss](../performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md) + + Whether animations in your application run smoothly is a key factor that affects user experience. You are advised to use the system-provided animation APIs to reduce frame loss. diff --git a/en/application-dev/performance/figure/application-cold-start.png b/en/application-dev/performance/figure/application-cold-start.png new file mode 100644 index 0000000000000000000000000000000000000000..210664879280518713b3ccb309875a059523319c Binary files /dev/null and b/en/application-dev/performance/figure/application-cold-start.png differ diff --git a/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md b/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md new file mode 100644 index 0000000000000000000000000000000000000000..b99c5dfc0ac84d75954b53b3a5c291bf60f4314e --- /dev/null +++ b/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md @@ -0,0 +1,110 @@ +# Speeding Up Application Cold Start + +Application startup latency is a key factor that affects user experience. When an application is started, the background does not have a process of the application, and therefore the system creates a new process and allocates it to the application. This startup mode is called cold start. + +## Analyzing the Time Required for Application Cold Start + +The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown in the following figure. + +![application-cold-start](../figure/application-cold-start.png) + +## 1. Shortening Time Required for Application Process Creation And Initialization + +In the phase of application process creation and initialization, the system creates and initializes an application process, including decoding the icon of the startup page (specified by **startWindowIcon**). + +### Using startWindowIcon of Appropriate Resolution + +With regard to the icon of the startup page, the recommended maximum resolution is 256 x 256 pixels. Larger resolutions may result in slow startup. + +```json + "abilities": [ + { + "name": "EntryAbility", + "srcEntrance": "./ets/entryability/EntryAbility.ts", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 pixels x 256 pixels. + "startWindowBackground": "$color:start_window_background", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ] +``` + +## 2. Shortening Time Required for Application and Ability Initialization + +In this phase of application and ability initialization, resources are loaded, VMs are created, application and ability related objects are created and initialized, and dependent modules are loaded. + +### Minimizing the Number of Imported Modules + +Before the application code is executed, the application must find and load all imported modules. Each additional third-party framework or module to be loaded by the application increases the startup time. The time required depends on the number and size of loaded third-party frameworks or modules. To speed up startup, use system-provided modules when possible and load the modules as required. + +## 3. Shortening Time Required for Ability Lifecycle + +In this phase of ability lifecycle, the ability lifecycle callbacks are executed. + +### Avoiding Time-Consuming Operations in Ability Lifecycle Callbacks + +In the application startup process, the system executes the ability lifecycle callbacks. Whenever possible, avoid performing time-consuming operations in these callbacks. You are advised to perform time-consuming operations through asynchronous tasks or execute them in other threads. + +In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](https://gitee.com/openharmony/docs/blob/master/en/application-dev/application-models/uiability-lifecycle.md). + +## 4. Shortening Time Required for Home Page Loading and Drawing + +In this phase of home page loading and drawing, the home page content is loaded, the layout is measured, and components are refreshed and drawn. + +### Avoid time-consuming operations in the custom component lifecycle callbacks. + +When the lifecycle of a custom component changes, the corresponding callback is called. + +The **aboutToAppear** function is executed after the custom component instance is created and before the page is drawn. The following code asynchronously processes the time-consuming computing task in **aboutToAppear** to avoid executing the operation in this function and blocking the page drawing. + +```javascript +@Entry +@Component +struct Index { + @State private text: string = undefined; + private count: number = undefined; + + aboutToAppear() { + this.computeTaskAsync(); // Asynchronous task + this.text = "hello world"; + } + + build() { + Column({space: 10}) { + Text(this.text).fontSize(50) + } + .width('100%') + .height('100%') + .padding(10) + } + + computeTask() { + this.count = 0; + while (this.count < 10000000) { + this.count++; + } + this.text = 'task complete'; + } + + // Asynchronous processing of the computing task + private computeTaskAsync() { + new Promise((resolved, rejected) => { + setTimeout(() => {// setTimeout is used to implement asynchronous processing. + this.computeTask(); + }, 1000) + }) + } +} +``` diff --git a/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md b/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md new file mode 100644 index 0000000000000000000000000000000000000000..b740edb6f1f4e2df007631f6feef966762e0d2ba --- /dev/null +++ b/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md @@ -0,0 +1,325 @@ +# Speeding Up Application Response + +This topic provides the following tips for improving your application's response to user input. + +- Prevent the main thread from being blocked by non-UI tasks. +- Reduce the number of components to be refreshed. + +## Preventing Main Thread from Being Blocked by Non-UI Tasks + +When the application responds to user input, its main thread should execute only UI tasks (such as preparation of data to be displayed and update of visible components). It is recommended that non-UI, time-consuming tasks (such as long-time content loading) be executed through asynchronous tasks or allocated to other threads. + +### Using Asynchronous Component Loading + +The **\** component has the asynchronous loading feature enabled by default. When an application loads a batch of local images to be displayed on the page, blank placeholder icons are displayed first, and then replaced by the images when these images have finished loading in other threads. In this way, image loading does not block page display. The following code is recommended only when the image loading takes a short time. + +```javascript +@Entry +@Component +struct ImageExample1 { + build() { + Column() { + Row() { + Image('resources/base/media/sss001.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%') + Image('resources/base/media/sss002.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%') + Image('resources/base/media/sss003.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%') + Image('resources/base/media/sss004.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%') + } + // Several containers are omitted here. Each container contains the preceding components. + } + } +} +``` + +Recommendation: If it takes a short time to load an image, the benefits of asynchronous loading will be greatly undermined. In this case, change the value of the syncLoad attribute. + +```javascript +@Entry +@Component +struct ImageExample1 { + build() { + Column() { + Row() { + Image('resources/base/media/sss001.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true) + Image('resources/base/media/sss002.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true) + Image('resources/base/media/sss003.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true) + Image('resources/base/media/sss004.jpg') + .border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true) + } + // Several containers are omitted here. Each container contains the preceding components. + } + } +} +``` + +### Using TaskPool for Asynchronous Processing + +Compared with the worker thread, [TaskPool](https://gitee.com/sqsyqqy/docs/blob/master/en/application-dev/reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example: + +```javascript +import taskpool from '@ohos.taskpool'; + +@Concurrent +function computeTask(arr: string[]): string[] { + // Simulate a compute-intensive task. + let count = 0; + while (count < 100000000) { + count++; + } + return arr.reverse(); +} + +@Entry +@Component +struct AspectRatioExample { + @State children: string[] = ['1', '2', '3', '4', '5', '6']; + + aboutToAppear() { + this.computeTaskInTaskPool(); + } + + async computeTaskInTaskPool() { + const param = this.children.slice(); + let task = new taskpool.Task(computeTask, param); + // @ts-ignore + this.children = await taskpool.execute(task); + } + + build() { + // Component layout + } +} +``` + +### Creating Asynchronous Tasks + +The following code shows how to declare a long-running non-UI task as an asynchronous task through **Promise**. This allows the main thread to first focus on providing user feedback and completing the initial render, and then execute the asynchronous task when it is idle. After the asynchronous task is complete, related components are redrawn to refresh the page. + +```javascript +@Entry +@Component +struct AspectRatioExample { + @State private children: string[] = ['1', '2', '3', '4', '5', '6']; + private count: number = undefined; + + aboutToAppear() { + this.computeTaskAsync(); // Invoke the asynchronous compute function. + } + + // Simulate a compute-intensive task. + computeTask() { + this.count = 0; + while (this.count < 100000000) { + this.count++; + } + this.children = this.children.reverse(); + } + + computeTaskAsync() { + new Promise((resolved, rejected) => { + setTimeout(() => {// setTimeout is used to implement asynchronous processing. + this.computeTask(); + }, 1000) + }) + } + + build() { + // Component layout + } +} +``` + +## Reducing the Number of Components to Be Refreshed + +When an application refreshes a page, the number of components to be refreshed must be reduced as much as possible. If this number is too large, the main thread will take a long time to perform measurement and layout. In addition, the **aboutToAppear()** and **aboutToDisappear()** APIs will be called multiple times during the creation and destruction of custom components, increasing the load of the main thread. + +### Limiting the Refresh Scope with Containers + +Negative example: If a component in a container is included in the **if** condition, changes in the **if** condition result will trigger the creation and destruction of the component. If the container layout is affected in this case, all components in the container are refreshed. As a result, the UI refresh of the main thread takes a long time. + +In the following example, the **Text('New Page')** component is controlled by the state variable **isVisible**. When **isVisible** is set to **true**, the component is created. When **isVisible** is set to **false**, the component is destroyed. This means that, when the value of **isVisible** changes, all components in the **\** container are refreshed. + +```javascript +@Entry +@Component +struct StackExample { + @State isVisible : boolean = false; + + build() { + Column() { + Stack({alignContent: Alignment.Top}) { + Text().width('100%').height('70%').backgroundColor(0xd2cab3) + .align(Alignment.Center).textAlign(TextAlign.Center); + + // 100 identical components are omitted here. + + if (this.isVisible) { + Text('New Page').height("100%").height("70%").backgroundColor(0xd2cab3) + .align(Alignment.Center).textAlign(TextAlign.Center); + } + } + Button("press").onClick(() => { + this.isVisible = !(this.isVisible); + }) + } + } +} +``` + +Recommendation: For the component controlled by the state variable, add a container to the **if** statement to reduce the refresh scope. + +```javascript +@Entry +@Component +struct StackExample { + @State isVisible : boolean = false; + + build() { + Column() { + Stack({alignContent: Alignment.Top}) { + Text().width('100%').height('70%').backgroundColor(0xd2cab3) + .align(Alignment.Center).textAlign(TextAlign.Center); + + // 100 identical components are omitted here. + + Stack() { + if (this.isVisible) { + Text('New Page').height("100%").height("70%").backgroundColor(0xd2cab3) + .align(Alignment.Center).textAlign(TextAlign.Center); + } + }.width('100%').height('70%') + } + Button("press").onClick(() => { + this.isVisible = !(this.isVisible); + }) + } + } +} +``` + +### Implementing On-Demand Loading of List Items + +Negative example: Each of the 10000 elements in **this.arr** is initialized and loaded. As a result, the execution of the main thread takes a long time. + +```javascript +@Entry +@Component +struct MyComponent { + @State arr: number[] = Array.from(Array(10000), (v,k) =>k); + build() { + List() { + ForEach(this.arr, (item: number) => { + ListItem() { + Text(`item value: ${item}`) + } + }, (item: number) => item.toString()) + } + } +} +``` + +Recommendation: In similar cases, replace **ForEach** with **LazyForEach** so that only visible elements are loaded. + +```javascript +class BasicDataSource implements IDataSource { + private listeners: DataChangeListener[] = [] + + public totalCount(): number { + return 0 + } + + public getData(index: number): any { + return undefined + } + + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + console.info('add listener') + this.listeners.push(listener) + } + } + + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { + console.info('remove listener') + this.listeners.splice(pos, 1) + } + } + + notifyDataReload(): void { + this.listeners.forEach(listener => { + listener.onDataReloaded() + }) + } + + notifyDataAdd(index: number): void { + this.listeners.forEach(listener => { + listener.onDataAdd(index) + }) + } + + notifyDataChange(index: number): void { + this.listeners.forEach(listener => { + listener.onDataChange(index) + }) + } + + notifyDataDelete(index: number): void { + this.listeners.forEach(listener => { + listener.onDataDelete(index) + }) + } + + notifyDataMove(from: number, to: number): void { + this.listeners.forEach(listener => { + listener.onDataMove(from, to) + }) + } +} + +class MyDataSource extends BasicDataSource { + private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString()); + + public totalCount(): number { + return this.dataArray.length + } + + public getData(index: number): any { + return this.dataArray[index] + } + + public addData(index: number, data: string): void { + this.dataArray.splice(index, 0, data) + this.notifyDataAdd(index) + } + + public pushData(data: string): void { + this.dataArray.push(data) + this.notifyDataAdd(this.dataArray.length - 1) + } +} + +@Entry +@Component +struct MyComponent { + private data: MyDataSource = new MyDataSource() + + build() { + List() { + LazyForEach(this.data, (item: string) => { + ListItem() { + Text(item).fontSize(20).margin({ left: 10 }) + } + }, item => item) + } + } +} +``` diff --git a/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md b/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md new file mode 100644 index 0000000000000000000000000000000000000000..a61c8649e392b7fd0055e63ab48e0fa335faab7f --- /dev/null +++ b/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md @@ -0,0 +1,142 @@ +# Reducing Frame Loss + +Frame loss in the animation arena is a phenomenon where the frame rate of an animation drops when it is running or being created. + +When playing an animation, the system needs to calculate the animation curve and draw the component layout within a refresh period. You are advised to use the system-provided animation APIs. With these APIs, setting the curve type, end point position, and duration is enough for meeting common animation needs, thereby reducing the load of the UI main thread. + +Negative example: The application uses a custom animation, which involves animation curve calculation. This calculation process may cause high load of the UI thread and frame loss. + +```javascript +@Entry +@Component +struct AttrAnimationExample { + @State widthSize: number = 200 + @State heightSize: number = 100 + @State flag: boolean = true + + computeSize() { + let duration = 2000 + let period = 16 + let widthSizeEnd = undefined + let heightSizeEnd = undefined + if (this.flag) { + widthSizeEnd = 100 + heightSizeEnd = 50 + } else { + widthSizeEnd = 200 + heightSizeEnd = 100 + } + let doTimes = duration / period + let deltaHeight = (heightSizeEnd - this.heightSize) / doTimes + let deltaWeight = (widthSizeEnd - this.widthSize) / doTimes + for (let i = 1; i <= doTimes; i++) { + let t = period * (i); + setTimeout(() => { + this.heightSize = this.heightSize + deltaHeight + this.widthSize = this.widthSize + deltaWeight + }, t) + } + this.flag = !this.flag + } + + build() { + Column() { + Button('click me') + .onClick(() => { + let delay = 500 + setTimeout(() => { this.computeSize() }, delay) + }) + .width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff) + }.width('100%').margin({ top: 5 }) + } +} +``` + +## Using System-Provided Attribute Animation APIs + +The following uses the system-provided attribute animation APIs to implement the preceding animation features: + +```javascript +@Entry +@Component +struct AttrAnimationExample { + @State widthSize: number = 200 + @State heightSize: number = 100 + @State flag: boolean = true + + build() { + Column() { + Button('click me') + .onClick((event: ClickEvent) => { + if (this.flag) { + this.widthSize = 100 + this.heightSize = 50 + } else { + this.widthSize = 200 + this.heightSize = 100 + } + this.flag = !this.flag + }) + .width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff) + .animation({ + duration: 2000, // Animation duration. + curve: Curve.Linear, // Animation curve. + delay: 500, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation playback mode. + }) // Animation configuration for the width and height attributes of the +

@@ -4322,6 +4324,10 @@ export default class EntryAbility extends UIAbility { 通过WebCookie可以控制Web组件中的cookie的各种行为,其中每个应用中的所有web组件共享一个WebCookieManager实例。 +> **说明:** +> +> 目前调用WebCookieManager下的方法,都需要先加载Web组件。 + ### getCookie static getCookie(url: string): string @@ -4783,6 +4789,10 @@ struct WebComponent { 通过WebStorage可管理Web SQL数据库接口和HTML5 Web存储接口,每个应用中的所有Web组件共享一个WebStorage。 +> **说明:** +> +> 目前调用WebStorage下的方法,都需要先加载Web组件。 + ### deleteOrigin static deleteOrigin(origin : string): void @@ -5243,6 +5253,10 @@ struct WebComponent { web组件数据库管理对象。 +> **说明:** +> +> 目前调用WebDataBase下的方法,都需要先加载Web组件。 + ### getHttpAuthCredentials static getHttpAuthCredentials(host: string, realm: string): Array\ @@ -5421,6 +5435,10 @@ struct WebComponent { web组件地理位置权限管理对象。 +> **说明:** +> +> 目前调用GeolocationPermissions下的方法,都需要先加载Web组件。 + ### 需要权限 访问地理位置时需添加权限:ohos.permission.LOCATION、ohos.permission.APPROXIMATELY_LOCATION、ohos.permission.LOCATION_IN_BACKGROUND,具体权限说明请参考[位置服务](./js-apis-geolocation.md)。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifi.md b/zh-cn/application-dev/reference/apis/js-apis-wifi.md index 3ea825222560fb011540cd04369883ff60430768..d1c1cd4080bbeb6168055b5be52b95c1ea21dbed 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifi.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifi.md @@ -96,8 +96,8 @@ isWifiActive(): boolean import wifi from '@ohos.wifi'; try { - let isActivate = wifi.isActivate(); - console.info("isActivate:" + isActivate); + let isWifiActive = wifi.isWifiActive(); + console.info("isWifiActive:" + isWifiActive); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -569,7 +569,7 @@ connectToDevice(config: WifiDeviceConfig): boolean **系统接口:** 此接口为系统接口。 **需要权限:** ohos.permission.SET_WIFI_INFO 和 ohos.permission.SET_WIFI_CONFIG 和 ohos.permission.MANAGE_WIFI_CONNECTION,仅系统应用可用。 - + **系统能力:** SystemCapability.Communication.WiFi.STA @@ -2254,7 +2254,58 @@ wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); // Unregister event wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); + +``` +## wifi.on('streamChange')7+ + +on(type: "streamChange", callback: Callback<number>): void + +注册WIFI流更改事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"streamChange"字符串。 | + | callback | Callback<number> | 是 | 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | + +## wifi.off('streamChange')7+ + +off(type: "streamChange", callback: Callback<number>): void + +取消注册WIFI流更改事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"streamChange"字符串。 | + | callback | Callback<number> | 是 | 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | + +**示例:** +```js +import wifi from '@ohos.wifi'; + +var recvStreamChangeFunc = result => { + console.info("Receive stream change event: " + result); +} + +// Register event +wifi.on("streamChange", recvStreamChangeFunc); + +// Unregister event +wifi.off("streamChange", recvStreamChangeFunc); + ``` + ## wifi.on('hotspotStateChange')7+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -2313,6 +2364,105 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void | type | string | 是 | 固定填"hotspotStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | +## wifi.on('hotspotStaJoin')7+ + +on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void + +注册wifi热点sta加入事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"hotspotStaJoin"字符串。 | + | callback | Callback<StationInfo> | 是 | 状态改变回调函数。 | + +## wifi.off('hotspotStaJoin')7+ + +off(type: "hotspotStaJoin", callback: Callback<StationInfo>): void + +取消注册wifi热点sta加入事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"hotspotStaJoin"字符串。 | + | callback | Callback<StationInfo> | 是 | 状态改变回调函数。 | + + **示例:** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStaJoinFunc = result => { + console.info("Receive hotspot sta join event: " + result); +} + +// Register event +wifi.on("hotspotStaJoin", recvHotspotStaJoinFunc); + +// Unregister event +wifi.off("hotspotStaJoin", recvHotspotStaJoinFunc); + +``` + +## wifi.on('hotspotStaLeave')7+ + +on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void + +注册wifi热点sta离开事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"hotspotStaLeave"字符串。 | + | callback | Callback<StationInf]> | 是 | 状态改变回调函数。 | + +## wifi.off('hotspotStaLeave')7+ + +off(type: "hotspotStaLeave", callback: Callback<StationInfo>): void + +取消注册wifi热点sta离开事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"hotspotStaLeave"字符串。 | + | callback | Callback<StationInf]> | 是 | 状态改变回调函数。 | + + **示例:** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStaLeaveFunc = result => { + console.info("Receive hotspot sta leave event: " + result); +} + +// Register event +wifi.on("hotspotStaLeave", recvHotspotStaLeaveFunc); + +// Unregister event +wifi.off("hotspotStaLeave", recvHotspotStaLeaveFunc); + +``` ## wifi.on('p2pStateChange')8+ @@ -2373,7 +2523,7 @@ wifi.on("p2pStateChange", recvP2pStateChangeFunc); wifi.off("p2pStateChange", recvP2pStateChangeFunc); ``` - ## wifi.on('p2pConnectionChange')8+ +## wifi.on('p2pConnectionChange')8+ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void @@ -2463,7 +2613,7 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void import wifi from '@ohos.wifi'; var recvP2pDeviceChangeFunc = result => { - console.info("Receive recv p2p device change event: " + result); + console.info("Receive p2p device change event: " + result); } // Register event @@ -2513,7 +2663,7 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo import wifi from '@ohos.wifi'; var recvP2pPeerDeviceChangeFunc = result => { - console.info("Receive recv p2p peer device change event: " + result); + console.info("Receive p2p peer device change event: " + result); } // Register event @@ -2563,7 +2713,7 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void import wifi from '@ohos.wifi'; var recvP2pPersistentGroupChangeFunc = result => { - console.info("Receive recv p2p persistent group change event: " + result); + console.info("Receive p2p persistent group change event: " + result); } // Register event @@ -2621,7 +2771,7 @@ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void import wifi from '@ohos.wifi'; var recvP2pDiscoveryChangeFunc = result => { - console.info("Receive recv p2p discovery change event: " + result); + console.info("Receive p2p discovery change event: " + result); } // Register event diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md index c1bccfd5d6bf606b154d87dfc514911cf027a548..0bdb1e7994c7dbd5db90fd354910721136e779de 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md @@ -11,7 +11,7 @@ import wifiManager from '@ohos.wifiManager'; ``` -## wifi.enableWifi9+ +## wifiManager.enableWifi9+ enableWifi(): void @@ -23,12 +23,6 @@ enableWifi(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** - - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。| - **错误码:** 以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 @@ -49,7 +43,7 @@ enableWifi(): void } ``` -## wifi.disableWifi9+ +## wifiManager.disableWifi9+ disableWifi(): void @@ -61,12 +55,6 @@ disableWifi(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** - - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。| - **错误码:** 以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 @@ -87,7 +75,7 @@ disableWifi(): void } ``` -## wifi.isWifiActive9+ +## wifiManager.isWifiActive9+ isWifiActive(): boolean @@ -117,14 +105,14 @@ isWifiActive(): boolean import wifiManager from '@ohos.wifiManager'; try { - let isActivate = wifiManager.isActivate(); - console.info("isActivate:" + isActivate); + let isWifiActive = wifiManager.isWifiActive(); + console.info("isWifiActive:" + isWifiActive); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.scan9+ +## wifiManager.scan9+ scan(): void @@ -134,11 +122,37 @@ scan(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** +**错误码:** - | **类型** | **说明** | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | | -------- | -------- | - | boolean | true:扫描操作执行成功, false:扫描操作执行失败。 | +| 2501000 | Operation failed.| + +**示例:** + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + wifiManager.scan(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifiManager.startScan10+ + +startScan(): void + +**系统接口:** 此接口为系统接口。 + +启动WLAN扫描。 + +**需要权限:** ohos.permission.SET_WIFI_INFO 和ohos.permission.MANAGE_WIFI_CONNECTION + +**系统能力:** SystemCapability.Communication.WiFi.STA **错误码:** @@ -154,19 +168,161 @@ scan(): void import wifiManager from '@ohos.wifiManager'; try { - wifiManager.scan(); + wifiManager.startScan(); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` +## wifiManager.getScanResults10+ + +getScanResults(): Promise<Array<WifiScanInfo>> + +获取扫描结果,使用Promise异步回调。 + +**需要权限:** ohos.permission.GET_WIFI_INFO 和 (ohos.permission.GET_WIFI_PEERS_MAC 或(ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION)) + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**返回值:** + +| **类型** | **说明** | +| -------- | -------- | +| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise对象。返回扫描到的热点列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | +| -------- | -------- | +| 2501000 | Operation failed.| + +## wifiManager.getScanResults10+ + +getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void + +获取扫描结果,使用callback异步回调。 + +**需要权限:** ohos.permission.GET_WIFI_INFO 和 (ohos.permission.GET_WIFI_PEERS_MAC 或 (ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION)) + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | 是 | 回调函数。当成功时,err为0,data为扫描到的热点;否则err为非0值,data为空。 | + | Array<[WifiScanInfo](#wifiscaninfo)> | 返回扫描到的热点列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | +| -------- | -------- | +| 2501000 | Operation failed.| + +**示例:** +```js + import wifiManager from '@ohos.wifiManager'; + + wifiManager.getScanResults((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifiManager.getScanResults().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); +``` + +## wifiManager.getScanResultsSync10+ + +getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> + +获取扫描结果,使用同步方式返回结果。 + +**需要权限:** ohos.permission.GET_WIFI_INFO 和 (ohos.permission.GET_WIFI_PEERS_MAC 或 (ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION)) + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**返回值:** + +| **类型** | **说明** | +| -------- | -------- | +|  Array<[WifiScanInfo](#wifiscaninfo)> | 扫描结果数组。 | + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | + | -------- | -------- | +| 2501000 | Operation failed.| + +**示例:** + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let scanInfoList = wifiManager.getScanResultsSync(); + console.info("scanInfoList:" + JSON.stringify(scanInfoList)); + let len = Object.keys(scanInfoList).length; + console.log("wifi received scan info: " + len); + if(len > 0){ + for (var i = 0; i < len; ++i) { + console.info("ssid: " + scanInfoList[i].ssid); + console.info("bssid: " + scanInfoList[i].bssid); + console.info("capabilities: " + scanInfoList[i].capabilities); + console.info("securityType: " + scanInfoList[i].securityType); + console.info("rssi: " + scanInfoList[i].rssi); + console.info("band: " + scanInfoList[i].band); + console.info("frequency: " + scanInfoList[i].frequency); + console.info("channelWidth: " + scanInfoList[i].channelWidth); + console.info("timestamp: " + scanInfoList[i].timestamp); + } + } }catch(error){ console.error("failed:" + JSON.stringify(error)); } + ``` -## wifi.getScanInfoList9+ +## wifiManager.getScanInfoList10+ getScanInfoList(): Array<WifiScanInfo>; 获取扫描结果。 -**需要权限:** ohos.permission.GET_WIFI_INFO 和 (ohos.permission.GET_WIFI_PEERS_MAC 或 (ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION)) +**需要权限:** ohos.permission.GET_WIFI_INFO **系统能力:** SystemCapability.Communication.WiFi.STA @@ -224,6 +380,7 @@ WLAN热点信息。 | -------- | -------- | -------- | -------- | -------- | | ssid | string | 是 | 否 | 热点的SSID,编码格式为UTF-8。 | | bssid | string | 是 | 否 | 热点的BSSID。 | +| bssidType10+| DeviceAddressType | 是 | 否 | 热点的BSSID类型。 | | capabilities | string | 是 | 否 | 热点能力。 | | securityType | [WifiSecurityType](#wifisecuritytype) | 是 | 否 | WLAN加密类型。 | | rssi | number | 是 | 否 | 热点的信号强度(dBm)。 | @@ -235,6 +392,16 @@ WLAN热点信息。 | infoElems | Array<[WifiInfoElem](#wifiinfoelem9)> | 是 | 否 | 信息元素。 | | timestamp | number | 是 | 否 | 时间戳。 | +## DeviceAddressType 10+ + +wifi 设备地址(mac/bissid)类型。 + +**系统能力:** SystemCapability.Communication.WiFi.Core + +| **名称** | **值** | **说明** | +| -------- | -------- | -------- | +| RANDOM_DEVICE_ADDRESS | 0 | 随机设备地址。 | +| REAL_DEVICE_ADDRESS | 1 | 真实设备地址。 | ## WifiSecurityType9+ @@ -317,7 +484,84 @@ WLAN热点信息。 | WIDTH_80MHZ_PLUS | 4 | 80MHZ+。 | | WIDTH_INVALID | 5 | 无效值 | -## wifi.addDeviceConfig9+ +## wifiManager.setScanAlwaysAllowed10+ + +setScanAlwaysAllowed(isScanAlwaysAllowed: boolean): void + +设置是否始终允许扫描。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.SET_WIFI_INFO 和 ohos.permission.SET_WIFI_CONFIG + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| isScanAlwaysAllowed | boolean | 是 | 是否始终允许扫描。 | + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | + | -------- | -------- | +| 2501000 | Operation failed.| + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let isScanAlwaysAllowed = true; + wifiManager.setScanAlwaysAllowed(isScanAlwaysAllowed); + }); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifiManager.getScanAlwaysAllowed10+ + +getScanAlwaysAllowed(): boolean + +获取是否始终允许扫描。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.SET_WIFI_INFO 和 ohos.permission.SET_WIFI_CONFIG + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**返回值:** + +| **类型** | **说明** | +| -------- | -------- | +| boolean| 是否始终允许扫描。 true 表示允许触发扫描,false表示在禁用wifi时不允许触发扫描| + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | + | -------- | -------- | +| 2501000 | Operation failed.| + +**示例:** + +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let isScanAlwaysAllowed = wifiManager.getScanAlwaysAllowed(); + console.info("isScanAlwaysAllowed:" + ret); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` + +## wifiManager.addDeviceConfig9+ addDeviceConfig(config: WifiDeviceConfig): Promise<number> @@ -379,6 +623,7 @@ WLAN配置信息。 | -------- | -------- | -------- | -------- | -------- | | ssid | string | 是 | 否 | 热点的SSID,编码格式为UTF-8。 | | bssid | string | 是 | 否 | 热点的BSSID。 | +| bssidType10+ | DeviceAddressType | 是 | 否 | 热点的BSSID类型。 | | preSharedKey | string | 是 | 否 | 热点的密钥。 | | isHiddenSsid | boolean | 是 | 否 | 是否是隐藏网络。 | | securityType | [WifiSecurityType](#wifisecuritytype) | 是 | 否 | 加密类型。 | @@ -389,8 +634,8 @@ WLAN配置信息。 | randomMacAddr | string | 是 | 否 | 随机MAC地址。
**系统接口:** 此接口为系统接口。 | | ipType | [IpType](#iptype9) | 是 | 否 | IP地址类型。
**系统接口:** 此接口为系统接口。 | | staticIp | [IpConfig](#ipconfig9) | 是 | 否 | 静态IP配置信息。
**系统接口:** 此接口为系统接口。 | -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | 是 | 否 | 可扩展身份验证协议配置。
**系统接口:** 此接口为系统接口。 | - +| eapConfig10+ | [WifiEapConfig](#wifieapconfig10) | 是 | 否 | 可扩展身份验证协议配置。 | +| proxyConfig10+ | WifiProxyConfig | 是 | 否 | 代理配置。
**系统接口:** 此接口为系统接口。| ## IpType9+ @@ -425,18 +670,16 @@ IP配置信息。 | domains | Array<string> | 是 | 否 | 域信息。 | -## WifiEapConfig9+ +## WifiEapConfig10+ 可扩展身份验证协议配置信息。 -**系统接口:** 此接口为系统接口。 - **系统能力:** SystemCapability.Communication.WiFi.STA | **名称** | **类型** | **可读** | **可写** | **说明** | | -------- | -------- | -------- | -------- | -------- | -| eapMethod | [EapMethod](#eapmethod9) | 是 | 否 | EAP认证方式。 | -| phase2Method | [Phase2Method](#phase2method9) | 是 | 否 | 第二阶段认证方式。 | +| eapMethod | [EapMethod](#eapmethod10) | 是 | 否 | EAP认证方式。 | +| phase2Method | [Phase2Method](#phase2method10) | 是 | 否 | 第二阶段认证方式。 | | identity | string | 是 | 否 | 身份信息。 | | anonymousIdentity | string | 是 | 否 | 匿名身份。 | | password | string | 是 | 否 | 密码。 | @@ -452,12 +695,10 @@ IP配置信息。 | eapSubId | number | 是 | 否 | SIM卡的子ID。 | -## EapMethod9+ +## EapMethod10+ 表示EAP认证方式的枚举。 -**系统接口:** 此接口为系统接口。 - **系统能力:** SystemCapability.Communication.WiFi.STA | 名称 | 值 | 说明 | @@ -473,12 +714,10 @@ IP配置信息。 | EAP_UNAUTH_TLS | 8 | UNAUTH TLS类型。 | -## Phase2Method9+ +## Phase2Method10+ 表示第二阶段认证方式的枚举。 -**系统接口:** 此接口为系统接口。 - **系统能力:** SystemCapability.Communication.WiFi.STA | 名称 | 值 | 说明 | @@ -493,7 +732,37 @@ IP配置信息。 | PHASE2_AKA_PRIME | 7 | AKA Prime类型。 | -## wifi.addDeviceConfig9+ +## WifiProxyConfig 10+ + +Wifi 代理配置。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Communication.WiFi.STA + +| **名称** | **类型** | **可读** | **可写** | **说明** | +| -------- | -------- | -------- | -------- | -------- | +| proxyMethod | ProxyMethod | 是 | 否 | 代理方法 | +| pacWebAddress | string | 是 | 否 | 自动配置代理的PAC web 地址。 | +| serverHostName | string | 是 | 否 | 手动配置代理的服务器主机名。 | +| serverPort | string | 是 | 否 | 手动配置代理的服务器端口。 | +| exclusionObjects | string | 是 | 否 | 手动配置代理的排除对象,对象用“,”分隔。| + +## ProxyMethod10+ + +表示WiFi代理方法的枚举。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.Communication.WiFi.STA + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| METHOD_NONE | 0 | 不使用代理。 | +| METHOD_AUTO | 1 | 使用自动配置的代理。 | +| METHOD_MANUAL | 2 | 使用手动配置的代理。 | + +## wifiManager.addDeviceConfig9+ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void @@ -539,7 +808,7 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>) } ``` -## wifi.addCandidateConfig9+ +## wifiManager.addCandidateConfig9+ addCandidateConfig(config: WifiDeviceConfig): Promise<number> @@ -587,7 +856,7 @@ addCandidateConfig(config: WifiDeviceConfig): Promise<number> } ````` -## wifi.addCandidateConfig9+ +## wifiManager.addCandidateConfig9+ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void @@ -630,7 +899,7 @@ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number&g } ````` -## wifi.removeCandidateConfig9+ +## wifiManager.removeCandidateConfig9+ removeCandidateConfig(networkId: number): Promise<void> @@ -675,7 +944,7 @@ removeCandidateConfig(networkId: number): Promise<void> } ``` -## wifi.removeCandidateConfig9+ +## wifiManager.removeCandidateConfig9+ removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void @@ -714,7 +983,7 @@ removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): v } ``` -## wifi.getCandidateConfigs9+ +## wifiManager.getCandidateConfigs9+ getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> @@ -760,7 +1029,7 @@ getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> ````` -## wifi.connectToCandidateConfig9+ +## wifiManager.connectToCandidateConfig9+ connectToCandidateConfig(networkId: number): void @@ -799,7 +1068,7 @@ connectToCandidateConfig(networkId: number): void ``` -## wifi.connectToNetwork9+ +## wifiManager.connectToNetwork9+ connectToNetwork(networkId: number): void @@ -839,7 +1108,7 @@ connectToNetwork(networkId: number): void } ``` -## wifi.connectToDevice9+ +## wifiManager.connectToDevice9+ connectToDevice(config: WifiDeviceConfig): void @@ -884,7 +1153,7 @@ connectToDevice(config: WifiDeviceConfig): void } ``` -## wifi.disconnect9+ +## wifiManager.disconnect9+ disconnect(): void @@ -916,7 +1185,7 @@ disconnect(): void } ``` -## wifi.getSignalLevel9+ +## wifiManager.getSignalLevel9+ getSignalLevel(rssi: number, band: number): number @@ -962,7 +1231,7 @@ getSignalLevel(rssi: number, band: number): number ``` -## wifi.getLinkedInfo9+ +## wifiManager.getLinkedInfo9+ getLinkedInfo(): Promise<WifiLinkedInfo> @@ -987,7 +1256,7 @@ getLinkedInfo(): Promise<WifiLinkedInfo> | 2501000 | Operation failed.| | 2501001 | Wifi is closed.| -## wifi.getLinkedInfo9+ +## wifiManager.getLinkedInfo9+ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void @@ -1103,7 +1372,7 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void | UNINITIALIZED | 10 | 连接建立失败。 | | INVALID | 11 | 无效值。 | -## wifi.isConnected9+ +## wifiManager.isConnected9+ isConnected(): boolean @@ -1140,7 +1409,7 @@ isConnected(): boolean ``` -## wifi.getSupportedFeatures9+ +## wifiManager.getSupportedFeatures9+ getSupportedFeatures(): number @@ -1194,7 +1463,7 @@ getSupportedFeatures(): number ``` -## wifi.isFeatureSupported9+ +## wifiManager.isFeatureSupported9+ isFeatureSupported(featureId: number): boolean @@ -1239,7 +1508,7 @@ isFeatureSupported(featureId: number): boolean ``` -## wifi.getDeviceMacAddress9+ +## wifiManager.getDeviceMacAddress9+ getDeviceMacAddress(): string[] @@ -1278,7 +1547,7 @@ getDeviceMacAddress(): string[] ``` -## wifi.getIpInfo9+ +## wifiManager.getIpInfo9+ getIpInfo(): IpInfo @@ -1331,7 +1600,59 @@ IP信息。 | leaseDuration | number | 是 | 否 | IP地址租用时长。 | -## wifi.getCountryCode9+ +## wifiManager.getIpv6Info10+ + +getIpv6Info(): Ipv6Info + +获取IP信息。 + +**需要权限:** ohos.permission.GET_WIFI_INFO + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**返回值:** + +| **类型** | **说明** | +| -------- | -------- | +| Ipv6Info | Ipv6信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | + | -------- | -------- | +| 2501000 | Operation failed.| + +**示例:** +```js + import wifiManager from '@ohos.wifiManager'; + + try { + let info = wifiManager.getIpv6Info(); + console.info("info:" + JSON.stringify(info)); + }catch(error){ + console.error("failed:" + JSON.stringify(error)); + } +``` +## Ipv6Info 10+ + +Ipv6信息。 + +**系统能力:** SystemCapability.Communication.WiFi.STA + +| **名称** | **类型** | **可读** | **可写** | **说明** | +| -------- | -------- | -------- | -------- | -------- | +| linkIpv6Address | string | 是 | 否 | 链路Ipv6地址。 | +| globalIpv6Address | string | 是 | 否 | 全局Ipv6地址。 | +| randomGlobalIpv6Address | number | 是 | 否 | 随机全局Ipv6地址。 | +| gateway | string | 是 | 否 | 网关。 | +| netmask | string | 是 | 否 | 网络掩码。 | +| primaryDNS | string | 是 | 否 | 主DNS服务器Ipv6地址。 | +| secondDNS | string | 是 | 否 | 备DNS服务器Ipv6地址。 | + + +## wifiManager.getCountryCode9+ getCountryCode(): string @@ -1367,7 +1688,7 @@ getCountryCode(): string } ``` -## wifi.reassociate9+ +## wifiManager.reassociate9+ reassociate(): void @@ -1399,7 +1720,7 @@ reassociate(): void } ``` -## wifi.reconnect9+ +## wifiManager.reconnect9+ reconnect(): void @@ -1431,7 +1752,7 @@ reconnect(): void } ``` -## wifi.getDeviceConfigs9+ +## wifiManager.getDeviceConfigs9+ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> @@ -1469,9 +1790,9 @@ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> } ``` -## wifi.updateDeviceConfig9+ +## wifiManager.updateNetwork9+ -updateDeviceConfig(config: WifiDeviceConfig): number +updateNetwork(config: WifiDeviceConfig): number 更新网络配置。 @@ -1511,16 +1832,16 @@ updateDeviceConfig(config: WifiDeviceConfig): number preSharedKey : "****", securityType : 3 } - let ret = wifiManager.updateDeviceConfig(config); + let ret = wifiManager.updateNetwork(config); console.error("ret:" + ret); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.disableDeviceConfig9+ +## wifiManager.disableNetwork9+ -disableDeviceConfig(networkId: number): void +disableNetwork(networkId: number): void 去使能网络配置。 @@ -1550,15 +1871,15 @@ disableDeviceConfig(networkId: number): void try { let netId = 0; - wifiManager.disableDeviceConfig(netId); + wifiManager.disableNetwork(netId); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.removeAllDeviceConfigs9+ +## wifiManager.removeAllNetwork9+ -removeAllDeviceConfigs(): void +removeAllNetwork(): void 移除所有网络配置。 @@ -1581,15 +1902,15 @@ removeAllDeviceConfigs(): void import wifiManager from '@ohos.wifiManager'; try { - wifiManager.removeAllDeviceConfigs(); + wifiManager.removeAllNetwork(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.removeDeviceConfig9+ +## wifiManager.removeDevice9+ -removeDeviceConfig(networkId: number): void +removeDevice(networkId: number): void 移除指定的网络配置。 @@ -1619,13 +1940,13 @@ removeDeviceConfig(networkId: number): void try { let id = 0; - wifiManager.removeDeviceConfig(id); + wifiManager.removeDevice(id); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.isBandTypeSupported10+ +## wifiManager.isBandTypeSupported10+ isBandTypeSupported(bandType: WifiBandType): boolean @@ -1641,6 +1962,12 @@ isBandTypeSupported(bandType: WifiBandType): boolean | -------- | -------- | -------- | -------- | | bandType | WifiBandType | 是 | Wifi 频段类型。 | +**返回值:** + + | **类型** | **说明** | + | -------- | -------- | + | boolean | true:支持, false:不支持。 | + **错误码:** 以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 @@ -1662,7 +1989,7 @@ isBandTypeSupported(bandType: WifiBandType): boolean } ``` -## wifi.get5GChannelList10+ +## wifiManager.get5GChannelList10+ get5GChannelList(): Array<number> @@ -1674,6 +2001,12 @@ get5GChannelList(): Array<number> **系统能力:** SystemCapability.Communication.WiFi.STA +**返回值:** + + | **类型** | **说明** | + | -------- | -------- | + |  Array<number> | 设备支持的5G信道列表。 | + **错误码:** 以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 @@ -1693,7 +2026,7 @@ get5GChannelList(): Array<number> console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.getDisconnectedReason10+ +## wifiManager.getDisconnectedReason10+ getDisconnectedReason(): DisconnectedReason @@ -1745,7 +2078,7 @@ getDisconnectedReason(): DisconnectedReason | DISC_REASON_WRONG_PWD | 1 | 密码错误。 | | DISC_REASON_CONNECTION_FULL | 2 | 路由器的连接数已达到最大数量限制。 | -## wifi.enableHotspot9+ +## wifiManager.enableHotspot9+ enableHotspot(): void @@ -1776,7 +2109,7 @@ enableHotspot(): void } ``` -## wifi.disableHotspot9+ +## wifiManager.disableHotspot9+ disableHotspot(): void @@ -1807,7 +2140,7 @@ disableHotspot(): void } ``` -## wifi.isHotspotDualBandSupported9+ +## wifiManager.isHotspotDualBandSupported9+ isHotspotDualBandSupported(): boolean @@ -1845,7 +2178,7 @@ isHotspotDualBandSupported(): boolean } ``` -## wifi.isHotspotActive9+ +## wifiManager.isHotspotActive9+ isHotspotActive(): boolean @@ -1883,7 +2216,7 @@ isHotspotActive(): boolean } ``` -## wifi.setHotspotConfig9+ +## wifiManager.setHotspotConfig9+ setHotspotConfig(config: HotspotConfig): void @@ -1946,7 +2279,7 @@ setHotspotConfig(config: HotspotConfig): void | preSharedKey | string | 是 | 是 | 热点的密钥。 | | maxConn | number | 是 | 是 | 最大设备连接数。 | -## wifi.getHotspotConfig9+ +## wifiManager.getHotspotConfig9+ getHotspotConfig(): HotspotConfig @@ -1984,9 +2317,9 @@ getHotspotConfig(): HotspotConfig } ``` -## wifi.getHotspotStations9+ +## wifiManager.getStations9+ -getHotspotStations():  Array<[StationInfo](#stationinfo9)> +getStations():  Array<[StationInfo](#stationinfo9)> 获取连接的设备。 @@ -2015,7 +2348,7 @@ getHotspotStations():  Array<[StationInfo](#stationinfo9)> import wifiManager from '@ohos.wifiManager'; try { - let stations = wifiManager.getHotspotStations(); + let stations = wifiManager.getStations(); console.info("result:" + JSON.stringify(stations)); }catch(error){ console.error("failed:" + JSON.stringify(error)); @@ -2034,10 +2367,11 @@ getHotspotStations():  Array<[StationInfo](#stationinfo9)> | -------- | -------- | -------- | -------- | -------- | | name | string | 是 | 否 | 设备名称。 | | macAddress | string | 是 | 否 | MAC地址。 | +| macAddressType10+ | DeviceAddressType | 是 | 否 | MAC地址类型。 | | ipAddress | string | 是 | 否 | IP地址。 | -## wifi.getP2pLinkedInfo9+ +## wifiManager.getP2pLinkedInfo9+ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> @@ -2104,7 +2438,7 @@ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> | CONNECTED | 1 | 连接状态。 | -## wifi.getP2pLinkedInfo9+ +## wifiManager.getP2pLinkedInfo9+ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void @@ -2121,7 +2455,7 @@ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 | -## wifi.getCurrentP2pGroup9+ +## wifiManager.getCurrentP2pGroup9+ getCurrentP2pGroup(): Promise<WifiP2pGroupInfo> @@ -2145,7 +2479,7 @@ getCurrentP2pGroup(): Promise<WifiP2pGroupInfo> | -------- | -------- | | 2801000 | Operation failed.| -## wifi.getCurrentP2pGroup9+ +## wifiManager.getCurrentP2pGroup9+ getCurrentP2pGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void @@ -2186,7 +2520,7 @@ getCurrentP2pGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void }); ``` -## wifi.getP2pPeerDevices9+ +## wifiManager.getP2pPeerDevices9+ getP2pPeerDevices(): Promise<WifiP2pDevice[]> @@ -2210,7 +2544,7 @@ getP2pPeerDevices(): Promise<WifiP2pDevice[]> | -------- | -------- | | 2801000 | Operation failed.| -## wifi.getP2pPeerDevices9+ +## wifiManager.getP2pPeerDevices9+ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void @@ -2261,6 +2595,7 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void | -------- | -------- | -------- | -------- | -------- | | deviceName | string | 是 | 否 | 设备名称。 | | deviceAddress | string | 是 | 否 | 设备MAC地址。 | +| deviceAddressType10+ | DeviceAddressType | 是 | 否 | 设备MAC地址类型。 | | primaryDeviceType | string | 是 | 否 | 主设备类型。 | | deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | 是 | 否 | 设备状态。 | | groupCapabilities | number | 是 | 否 | 群组能力。 | @@ -2281,7 +2616,7 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void | UNAVAILABLE | 4 | 不可用状态。 | -## wifi.getP2pLocalDevice9+ +## wifiManager.getP2pLocalDevice9+ getP2pLocalDevice(): Promise<WifiP2pDevice> @@ -2305,7 +2640,7 @@ getP2pLocalDevice(): Promise<WifiP2pDevice> | -------- | -------- | | 2801000 | Operation failed.| -## wifi.getP2pLocalDevice9+ +## wifiManager.getP2pLocalDevice9+ getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void @@ -2344,9 +2679,9 @@ getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void }); ``` -## wifi.createP2pGroup9+ +## wifiManager.createGroup9+ -createP2pGroup(config: WifiP2PConfig): void +createGroup(config: WifiP2PConfig): void 创建群组。 @@ -2380,7 +2715,7 @@ createP2pGroup(config: WifiP2PConfig): void groupName: "****", goBand: 0 } - wifiManager.createP2pGroup(config); + wifiManager.createGroup(config); }catch(error){ console.error("failed:" + JSON.stringify(error)); @@ -2396,6 +2731,7 @@ createP2pGroup(config: WifiP2PConfig): void | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | deviceAddress | string | 是 | 否 | 设备地址。 | +| deviceAddressType10+| DeviceAddressType | 是 | 否 | 设备地址类型。 | | netId | number | 是 | 否 | 网络ID。创建群组时-1表示创建临时组,-2表示创建永久组。 | | passphrase | string | 是 | 否 | 群组密钥。 | | groupName | string | 是 | 否 | 群组名称。 | @@ -2415,9 +2751,9 @@ createP2pGroup(config: WifiP2PConfig): void | GO_BAND_5GHZ | 2 | 5GHZ。 | -## wifi.removeP2pGroup9+ +## wifiManager.removeGroup9+ -removeP2pGroup(): void +removeGroup(): void 移除群组。 @@ -2438,13 +2774,13 @@ removeP2pGroup(): void import wifiManager from '@ohos.wifiManager'; try { - wifiManager.removeP2pGroup(); + wifiManager.removeGroup(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.p2pConnect9+ +## wifiManager.p2pConnect9+ p2pConnect(config: WifiP2PConfig): void @@ -2535,7 +2871,7 @@ p2pConnect(config: WifiP2PConfig): void console.info("start discover devices -> " + wifiManager.startDiscoverP2pDevices()); ``` -## wifi.p2pCancelConnect9+ +## wifiManager.p2pCancelConnect9+ p2pCancelConnect(): void @@ -2564,9 +2900,9 @@ p2pCancelConnect(): void } ``` -## wifi.startDiscoverP2pDevices9+ +## wifiManager.startDiscoverDevices10+ -startDiscoverP2pDevices(): void +startDiscoverDevices(): void 开始发现设备。 @@ -2587,15 +2923,15 @@ startDiscoverP2pDevices(): void import wifiManager from '@ohos.wifiManager'; try { - wifiManager.startDiscoverP2pDevices(); + wifiManager.startDiscoverDevices(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.stopDiscoverP2pDevices9+ +## wifiManager.stopDiscoverDevices10+ -stopDiscoverP2pDevices(): void +stopDiscoverDevices(): void 停止发现设备。 @@ -2616,15 +2952,15 @@ stopDiscoverP2pDevices(): void import wifiManager from '@ohos.wifiManager'; try { - wifiManager.stopDiscoverP2pDevices(); + wifiManager.stopDiscoverDevices(); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.deletePersistentP2pGroup9+ +## wifiManager.deletePersistentGroup9+ -deletePersistentP2pGroup(netId: number): void +deletePersistentGroup(netId: number): void 删除永久组。 @@ -2655,13 +2991,13 @@ deletePersistentP2pGroup(netId: number): void try { let netId = 0; - wifiManager.deletePersistentP2pGroup(netId); + wifiManager.deletePersistentGroup(netId); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.getP2pGroups9+ +## wifiManager.getP2pGroups9+ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> @@ -2724,7 +3060,7 @@ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> | goIpAddress | string | 是 | 否 | 群组IP地址。 | -## wifi.getP2pGroups9+ +## wifiManager.getP2pGroups9+ getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void @@ -2750,9 +3086,9 @@ getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void | -------- | -------- | | 2801000 | Operation failed.| -## wifi.setP2pDeviceName9+ +## wifiManager.setDeviceName9+ -setP2pDeviceName(devName: string): void +setDeviceName(devName: string): void 设置设备名称。 @@ -2782,13 +3118,13 @@ setP2pDeviceName(devName: string): void try { let name = "****"; - wifiManager.setP2pDeviceName(name); + wifiManager.setDeviceName(name); }catch(error){ console.error("failed:" + JSON.stringify(error)); } ``` -## wifi.on('wifiStateChange')9+ +## wifiManager.on('wifiStateChange')9+ on(type: "wifiStateChange", callback: Callback<number>): void @@ -2823,7 +3159,7 @@ on(type: "wifiStateChange", callback: Callback<number>): void | 3 | 去激活中。 | -## wifi.off('wifiStateChange')9+ +## wifiManager.off('wifiStateChange')9+ off(type: "wifiStateChange", callback?: Callback<number>): void @@ -2864,7 +3200,7 @@ off(type: "wifiStateChange", callback?: Callback<number>): void ``` -## wifi.on('wifiConnectionChange')9+ +## wifiManager.on('wifiConnectionChange')9+ on(type: "wifiConnectionChange", callback: Callback<number>): void @@ -2896,7 +3232,7 @@ on(type: "wifiConnectionChange", callback: Callback<number>): void | -------- | -------- | | 2501000 | Operation failed.| -## wifi.off('wifiConnectionChange')9+ +## wifiManager.off('wifiConnectionChange')9+ off(type: "wifiConnectionChange", callback?: Callback<number>): void @@ -2936,7 +3272,7 @@ off(type: "wifiConnectionChange", callback?: Callback<number>): void wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc); ``` -## wifi.on('wifiScanStateChange')9+ +## wifiManager.on('wifiScanStateChange')9+ on(type: "wifiScanStateChange", callback: Callback<number>): void @@ -2968,7 +3304,7 @@ on(type: "wifiScanStateChange", callback: Callback<number>): void | -------- | -------- | | 2501000 | Operation failed.| -## wifi.off('wifiScanStateChange')9+ +## wifiManager.off('wifiScanStateChange')9+ off(type: "wifiScanStateChange", callback?: Callback<number>): void @@ -3008,7 +3344,7 @@ off(type: "wifiScanStateChange", callback?: Callback<number>): void wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc); ``` -## wifi.on('wifiRssiChange')9+ +## wifiManager.on('wifiRssiChange')9+ on(type: "wifiRssiChange", callback: Callback<number>): void @@ -3033,7 +3369,7 @@ on(type: "wifiRssiChange", callback: Callback<number>): void | -------- | -------- | | 2501000 | Operation failed.| -## wifi.off('wifiRssiChange')9+ +## wifiManager.off('wifiRssiChange')9+ off(type: "wifiRssiChange", callback?: Callback<number>): void @@ -3073,7 +3409,7 @@ off(type: "wifiRssiChange", callback?: Callback<number>): void wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc); ``` -## wifi.on('hotspotStateChange')9+ +## wifiManager.on('hotspotStateChange')9+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -3107,7 +3443,7 @@ on(type: "hotspotStateChange", callback: Callback<number>): void | -------- | -------- | | 2601000 | Operation failed.| -## wifi.off('hotspotStateChange')9+ +## wifiManager.off('hotspotStateChange')9+ off(type: "hotspotStateChange", callback?: Callback<number>): void @@ -3147,7 +3483,7 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc); ``` -## wifi.on('p2pStateChange')9+ +## wifiManager.on('p2pStateChange')9+ on(type: "p2pStateChange", callback: Callback<number>): void @@ -3182,7 +3518,7 @@ on(type: "p2pStateChange", callback: Callback<number>): void | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pStateChange')9+ +## wifiManager.off('p2pStateChange')9+ off(type: "p2pStateChange", callback?: Callback<number>): void @@ -3222,7 +3558,7 @@ off(type: "p2pStateChange", callback?: Callback<number>): void wifiManager.off("p2pStateChange", recvP2pStateChangeFunc); ``` -## wifi.on('p2pConnectionChange')9+ +## wifiManager.on('p2pConnectionChange')9+ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void @@ -3247,7 +3583,7 @@ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): vo | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pConnectionChange')9+ +## wifiManager.off('p2pConnectionChange')9+ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void @@ -3287,7 +3623,7 @@ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc); ``` -## wifi.on('p2pDeviceChange')9+ +## wifiManager.on('p2pDeviceChange')9+ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void @@ -3312,7 +3648,7 @@ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pDeviceChange')9+ +## wifiManager.off('p2pDeviceChange')9+ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void @@ -3342,7 +3678,7 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void import wifiManager from '@ohos.wifiManager'; var recvP2pDeviceChangeFunc = result => { - console.info("Receive recv p2p device change event: " + result); + console.info("Receive p2p device change event: " + result); } // Register event @@ -3352,7 +3688,7 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc); ``` -## wifi.on('p2pPeerDeviceChange')9+ +## wifiManager.on('p2pPeerDeviceChange')9+ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void @@ -3377,7 +3713,7 @@ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pPeerDeviceChange')9+ +## wifiManager.off('p2pPeerDeviceChange')9+ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void @@ -3407,7 +3743,7 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo import wifiManager from '@ohos.wifiManager'; var recvP2pPeerDeviceChangeFunc = result => { - console.info("Receive recv p2p peer device change event: " + result); + console.info("Receive p2p peer device change event: " + result); } // Register event @@ -3417,7 +3753,7 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); ``` -## wifi.on('p2pPersistentGroupChange')9+ +## wifiManager.on('p2pPersistentGroupChange')9 on(type: "p2pPersistentGroupChange", callback: Callback<void>): void @@ -3442,7 +3778,7 @@ on(type: "p2pPersistentGroupChange", callback: Callback<void>): void | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pPersistentGroupChange')9+ +## wifiManager.off('p2pPersistentGroupChange')9 off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void @@ -3472,7 +3808,7 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void import wifiManager from '@ohos.wifiManager'; var recvP2pPersistentGroupChangeFunc = result => { - console.info("Receive recv p2p persistent group change event: " + result); + console.info("Receive p2p persistent group change event: " + result); } // Register event @@ -3482,7 +3818,7 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); ``` -## wifi.on('p2pDiscoveryChange')9+ +## wifiManager.on('p2pDiscoveryChange')9+ on(type: "p2pDiscoveryChange", callback: Callback<number>): void @@ -3514,7 +3850,7 @@ on(type: "p2pDiscoveryChange", callback: Callback<number>): void | -------- | -------- | | 2801000 | Operation failed.| -## wifi.off('p2pDiscoveryChange')9+ +## wifiManager.off('p2pDiscoveryChange')9+ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void @@ -3544,7 +3880,7 @@ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void import wifiManager from '@ohos.wifiManager'; var recvP2pDiscoveryChangeFunc = result => { - console.info("Receive recv p2p discovery change event: " + result); + console.info("Receive p2p discovery change event: " + result); } // Register event diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index b5ac04f9fb002c8fb460131b52015b71bf35c75f..1051cf2f086c4b9201ab11a3d76100cbfb355314 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -859,6 +859,15 @@ on(type: 'gestureNavigationEnabledChange', callback: Callback<boolean>): v | type | string | 是 | 监听事件,固定为'gestureNavigationEnabledChange',即手势导航启用状态变化事件。 | | callback | Callback<boolean> | 是 | 回调函数。返回当前手势导航的启用状态。true表示手势导航状态变化为启用;false表示手势导航状态变化为禁用。 | +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **示例:** ```js @@ -888,6 +897,15 @@ off(type: 'gestureNavigationEnabledChange', callback?: Callback<boolean>): | type | string | 是 | 监听事件,固定为'gestureNavigationEnabledChange',即手势导航启用状态变化事件。 | | callback | Callback<boolean> | 否 | 已注册的回调函数。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有手势导航启用状态变化的监听。 | +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **示例:** ```js @@ -2740,7 +2758,7 @@ try { ### on('avoidAreaChange')9+ -on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void +on(type: 'avoidAreaChange', callback: Callback<{ type: AvoidAreaType, area: AvoidArea}>): void 开启系统规避区变化的监听。 @@ -2751,7 +2769,7 @@ on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}> | 参数名 | 类型 | 必填 | 说明 | | -------- |------------------------------------------------------------------| ---- |--------------------------------------| | type | string | 是 | 监听事件,固定为'avoidAreaChange',即系统规避区变化事件。 | -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | 是 | 回调函数。返回当前规避区以及规避区类型。| +| callback | Callback<{ type: [AvoidAreaType](#avoidareatype7), area: [AvoidArea](#avoidarea7) }> | 是 | 回调函数。返回当前规避区以及规避区类型。| **示例:** @@ -2768,7 +2786,7 @@ try { ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}>): void +off(type: 'avoidAreaChange', callback?: Callback<{ type: AvoidAreaType, area: AvoidArea }>): void 关闭系统规避区变化的监听。 @@ -2779,7 +2797,7 @@ off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}&g | 参数名 | 类型 | 必填 | 说明 | | -------- |-----------------------------------------------------------------------------|-----|------------------------------------| | type | string | 是 | 监听事件,固定为'avoidAreaChange',即系统规避区变化事件。 | -| callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | 否 | 回调函数。返回当前规避区以及规避区类型。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有系统规避区变化的监听。| +| callback | Callback<{ type: [AvoidAreaType](#avoidareatype7), area: [AvoidArea](#avoidarea7) }> | 否 | 回调函数。返回当前规避区以及规避区类型。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有系统规避区变化的监听。| **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 64c8b9a39fb1274a8fa01223e93cb592ba7674bb..2ae6e87673eda293fe296ae27164873154a38e26 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -2025,18 +2025,8 @@ parentPort.onerror = function(e){ ## 其他说明 ### 序列化支持类型 -| Type | 备注 | 是否支持 | -| ------------------ | -------------------------------------- | -------- | -| All Primitive Type | 不包括symbol | 是 | -| Date | | 是 | -| String | | 是 | -| RegExp | | 是 | -| Array | | 是 | -| Map | | 是 | -| Set | | 是 | -| Object | 只支持Plain Object,不支持带function的 | 是 | -| ArrayBuffer | 提供transfer能力 | 是 | -| TypedArray | | 是 | + +序列化支持类型包括:除Symbol之外的基础类型、Date、String、RegExp、Array、Map、Set、Object(仅限简单对象,比如通过"{}"或者"new Object"创建,普通对象仅支持传递属性,不支持传递其原型及方法)、ArrayBuffer、TypedArray。 特例:传递通过自定义class创建出来的object时,不会发生序列化错误,但是自定义class的属性(如Function)无法通过序列化传递。 > **说明:**
diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/image-animator.gif b/zh-cn/application-dev/reference/arkui-js-lite/figures/image-animator-lite.gif similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/image-animator.gif rename to zh-cn/application-dev/reference/arkui-js-lite/figures/image-animator-lite.gif diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/image.png b/zh-cn/application-dev/reference/arkui-js-lite/figures/image-lite.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/image.png rename to zh-cn/application-dev/reference/arkui-js-lite/figures/image-lite.png diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/list.png b/zh-cn/application-dev/reference/arkui-js-lite/figures/list-lite.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/list.png rename to zh-cn/application-dev/reference/arkui-js-lite/figures/list-lite.png diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/lite_line.PNG b/zh-cn/application-dev/reference/arkui-js-lite/figures/lite_line.PNG index 664ade98b38a3b6ac2b3e96dc4af8b75b6749a72..6fc94377d0df58e97d531dd11695c105bf161cd8 100644 Binary files a/zh-cn/application-dev/reference/arkui-js-lite/figures/lite_line.PNG and b/zh-cn/application-dev/reference/arkui-js-lite/figures/lite_line.PNG differ diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/marquee.gif b/zh-cn/application-dev/reference/arkui-js-lite/figures/marquee-lite.gif similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/marquee.gif rename to zh-cn/application-dev/reference/arkui-js-lite/figures/marquee-lite.gif diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/picker-view.png b/zh-cn/application-dev/reference/arkui-js-lite/figures/picker-view-lite.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/picker-view.png rename to zh-cn/application-dev/reference/arkui-js-lite/figures/picker-view-lite.png diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/progress.png b/zh-cn/application-dev/reference/arkui-js-lite/figures/progress-lite.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/progress.png rename to zh-cn/application-dev/reference/arkui-js-lite/figures/progress-lite.png diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/qrcode.gif b/zh-cn/application-dev/reference/arkui-js-lite/figures/qrcode-lite.gif similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/qrcode.gif rename to zh-cn/application-dev/reference/arkui-js-lite/figures/qrcode-lite.gif diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/slider.png b/zh-cn/application-dev/reference/arkui-js-lite/figures/slider-lite.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/slider.png rename to zh-cn/application-dev/reference/arkui-js-lite/figures/slider-lite.png diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/swiper.gif b/zh-cn/application-dev/reference/arkui-js-lite/figures/swiper-lite.gif similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/swiper.gif rename to zh-cn/application-dev/reference/arkui-js-lite/figures/swiper-lite.gif diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/switch.gif b/zh-cn/application-dev/reference/arkui-js-lite/figures/switch-lite.gif similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/switch.gif rename to zh-cn/application-dev/reference/arkui-js-lite/figures/switch-lite.gif diff --git a/zh-cn/application-dev/reference/arkui-js-lite/figures/text.png b/zh-cn/application-dev/reference/arkui-js-lite/figures/text-lite.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js-lite/figures/text.png rename to zh-cn/application-dev/reference/arkui-js-lite/figures/text-lite.png diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-chart.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-chart.md index fd8ea82d1b255962a099342721f72cd4c718e9e8..0bdab9207f17390a768f0ffe86e046a8a7a5f4a5 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-chart.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-chart.md @@ -165,7 +165,7 @@ strokeColor: '#0081ff', fillColor: '#cce5ff', data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], - gradient: true, + gradient: false, } ], lineOps: { diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md index d0db3c1abf138cca8c062bee7bfa73426908ab78..e654181563a1190c3411106a189ef13848ef0f46 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image-animator.md @@ -204,4 +204,4 @@ export default { }; ``` -![image-animator](figures/image-animator.gif) +![image-animator](figures/image-animator-lite.gif) diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image.md index 838db18b496f1fd144bc2cebddb70dfc2e84e516..490657fda5476ce6eee0d775eb056009554b6111 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-image.md @@ -71,4 +71,4 @@ } ``` -![image](figures/image.png) \ No newline at end of file +![image](figures/image-lite.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md index e146eb244ac7c796efca5773842feaf1607502ee..ab78dac2347cee08cb90b537d52ddb4503035581 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-marquee.md @@ -115,4 +115,4 @@ export default { } ``` -![marquee](figures/marquee.gif) \ No newline at end of file +![marquee](figures/marquee-lite.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md index 3722716aae1e0d42bf1638e0efc50d475430ee13..afe4258925e7b117f171e7e7154fb49663bd47da 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-picker-view.md @@ -142,4 +142,4 @@ export default { } ``` -![picker-view](figures/picker-view.png) \ No newline at end of file +![picker-view](figures/picker-view-lite.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-progress.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-progress.md index afbbb9010be0c457ac3419da1c5f30aae9fa8388..44b5e0a7d8f9fc502a16290eabf7d9e064dc6ec6 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-progress.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-progress.md @@ -122,4 +122,4 @@ export default { } ``` -![progress](figures/progress.png) \ No newline at end of file +![progress](figures/progress-lite.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md index c454322301d03fe4ae53bb7d3c83aa3b733cf239..3859d4ae1069b3b6a13678e0c0584f9d52ae6814 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-qrcode.md @@ -63,10 +63,10 @@ ```html
- - Color - BackgroundColor - Value + + Color + BackgroundColor + Value
``` @@ -93,33 +93,33 @@ ```javascript // xxx.js export default { - data: { - qr_col: '#87ceeb', - qr_bcol: '#f0ffff', - qr_value: 'value' - }, - changeColor() { - if (this.qr_col == '#87ceeb') { - this.qr_col = '#fa8072'; - } else { - this.qr_col = '#87ceeb'; + data: { + qr_col: '#87ceeb', + qr_bcol: '#f0ffff', + qr_value: 'value' + }, + changeColor() { + if (this.qr_col == '#87ceeb') { + this.qr_col = '#fa8072'; + } else { + this.qr_col = '#87ceeb'; + } + }, + changeBackgroundColor() { + if (this.qr_bcol == '#f0ffff') { + this.qr_bcol = '#ffffe0'; + } else { + this.qr_bcol = '#f0ffff'; + } + }, + changeValue() { + if (this.qr_value == 'value') { + this.qr_value = 'change'; + } else { + this.qr_value = 'value'; + } } - }, - changeBackgroundColor() { - if (this.qr_bcol == '#f0ffff') { - this.qr_bcol = '#ffffe0'; - } else { - this.qr_bcol = '#f0ffff'; - } - }, - changeValue() { - if (this.qr_value == 'value') { - this.qr_value = 'change'; - } else { - this.qr_value = 'value'; - } - } } ``` -![qrcode](figures/qrcode.gif) \ No newline at end of file +![qrcode](figures/qrcode-lite.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-slider.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-slider.md index 8851c22fecbb2077f9a9d4e34740e5ee24e237a5..97b630078fa98bdc06479c279798048e561a056a 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-slider.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-slider.md @@ -99,4 +99,4 @@ export default { } ``` -![slider](figures/slider.png) \ No newline at end of file +![slider](figures/slider-lite.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-switch.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-switch.md index 4891bf42f55debc468e561b2736911725336b609..0fa33788192d4afcabc642bdd0bc51dbe3d94111 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-switch.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-switch.md @@ -96,4 +96,4 @@ export default { } ``` -![switch](figures/switch.gif) \ No newline at end of file +![switch](figures/switch-lite.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-text.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-text.md index 8eae2cbea67e59d15aba3e9d848e037a5d54ade1..c736b2e3d30489b7cea942f934349fcd7a6cdf80 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-text.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-basic-text.md @@ -96,4 +96,4 @@ export default { } ``` -![text](figures/text.png) \ No newline at end of file +![text](figures/text-lite.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-list.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-list.md index 905cf802427c20a6b474de2f32adcb241b01db28..34b07ee49fc4788054be5c2f57520ce3fb7eb051 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-list.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-list.md @@ -120,4 +120,4 @@ export default { } ``` -![list](figures/list.png) +![list](figures/list-lite.png) diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-swiper.md b/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-swiper.md index 37865ab41d81a1d873ab0df01b06253f397b779b..add61b8e167cde18a22097d0d30850c6704727e4 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-components-container-swiper.md @@ -109,4 +109,4 @@ export default { } ``` -![swiper](figures/swiper.gif) +![swiper](figures/swiper-lite.gif) diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md b/zh-cn/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md index 19823d44ee74a86b286e439aedafade9001a089e..ecb2eb31bb4140cd22f1253c5f12320dde2f53c5 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-framework-syntax-js.md @@ -33,7 +33,7 @@ JS文件用来定义HML页面的业务逻辑,支持ECMA规范的JavaScript语 ``` - import router from '@system.router'; + import router from '@ohos.router'; ``` - 代码引用 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 4748ee9252113f2b4fd7a527cef44c5f1dfcad5e..e96ca170e6bad8a24e02897605ff9a2014ccf705 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -123,6 +123,7 @@ - [GridRow](ts-container-gridrow.md) - [Grid](ts-container-grid.md) - [GridItem](ts-container-griditem.md) + - [Hyperlink](ts-container-hyperlink.md) - [List](ts-container-list.md) - [ListItem](ts-container-listitem.md) - [ListItemGroup](ts-container-listitemgroup.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag.png b/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag.png new file mode 100644 index 0000000000000000000000000000000000000000..ab2755200c7ec3877b929c9182256f22b0cc5138 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag1.png b/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag1.png new file mode 100644 index 0000000000000000000000000000000000000000..721ec8950cc43af81afefdcd22afb14f50dfdb0e Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag1.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag2.png b/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag2.png new file mode 100644 index 0000000000000000000000000000000000000000..5fbb5f43fbb38a3b10d6455abec94bef4c5f98aa Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/gridDrag2.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/hyperlink.PNG b/zh-cn/application-dev/reference/arkui-ts/figures/hyperlink.PNG new file mode 100644 index 0000000000000000000000000000000000000000..840110d2c649008658a812bb58d61d22727f99ea Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/hyperlink.PNG differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/image-matrix-1.jpg b/zh-cn/application-dev/reference/arkui-ts/figures/image-matrix-1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9a2140166f2056e424976046655e5480903f2c0f Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/image-matrix-1.jpg differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/image-matrix-2.jpg b/zh-cn/application-dev/reference/arkui-ts/figures/image-matrix-2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..01285cbbaff67c9b1e99c8eb7ae384889ad99bb1 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/image-matrix-2.jpg differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/listItem3.jpeg b/zh-cn/application-dev/reference/arkui-ts/figures/listItem3.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5188c9221033fb57e3e483ade647353097f9e4e4 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/listItem3.jpeg differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/listItemGroup2.jpeg b/zh-cn/application-dev/reference/arkui-ts/figures/listItemGroup2.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..4b85118fd80799129e19f376e601eaa6b9aa799f Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/listItemGroup2.jpeg differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/tabContent3.gif b/zh-cn/application-dev/reference/arkui-ts/figures/tabContent3.gif new file mode 100644 index 0000000000000000000000000000000000000000..97caa2fdc55bfee964edaacac110ee46e3fcf0c8 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/tabContent3.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/tabContent4.png b/zh-cn/application-dev/reference/arkui-ts/figures/tabContent4.png new file mode 100644 index 0000000000000000000000000000000000000000..a202932241fc8352e501528ce91e3d91e83b2a26 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/tabContent4.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/tabs3.gif b/zh-cn/application-dev/reference/arkui-ts/figures/tabs3.gif new file mode 100644 index 0000000000000000000000000000000000000000..6f65f71007d5943f849d2b8e300fc82b1205409c Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/tabs3.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/tabs4.gif b/zh-cn/application-dev/reference/arkui-ts/figures/tabs4.gif new file mode 100644 index 0000000000000000000000000000000000000000..f05d302966838afbb9b1f10873846fc942a274fe Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/tabs4.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/tabs5.gif b/zh-cn/application-dev/reference/arkui-ts/figures/tabs5.gif new file mode 100644 index 0000000000000000000000000000000000000000..94a3ce1abe2eaa51bf45c812c09f9c150ba56198 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/tabs5.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422896.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422896.gif index 1cd6ff13714a55e253e9649c007080b47f02f791..65dce0858d00df7ce62b578ce8de8b3f153d006e 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422896.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422896.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001205812616.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001205812616.png deleted file mode 100644 index 9dd3c2c156b40ce5feb16eb8b8d4541361f877d2..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001205812616.png and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif index 738e50b17cf1c20514f17034ec08bba1cadf2893..2d852ce15286468dace1661d2ef9796274aff07d 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982708.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982729.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982729.gif index 0ea18f82170eb3309aefb8af24ef89f886718bdd..c5f6fec069ee84ed9a59ca6e457338a59f570f39 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982729.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219982729.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001592882500.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001592882500.gif new file mode 100644 index 0000000000000000000000000000000000000000..ccdd2b1aa8255ce173bc923f6686bdfb99e61ce3 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001592882500.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001607845173.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001607845173.gif new file mode 100644 index 0000000000000000000000000000000000000000..f312df91ae0f7fd8cd8520904a11ddaccd7c58e4 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001607845173.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 8d38be12a656b2394ca1ca5c95922ed937527f87..0a7776d01bd030d9fcebd530b0636c80736b3150 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -6,7 +6,7 @@ > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -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}) 从API version 9开始,该接口支持在ArkTS卡片中使用。 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 6ce743a0f15883c6f04e11dd085cbb825ad5587f..9eb6ea3b66e032f8a441b65e509759dda062a37f 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 @@ -26,6 +26,26 @@ DatePicker(options?: {start?: Date, end?: Date, selected?: Date}) | end | Date | 否 | 指定选择器的结束日期。
默认值:Date('2100-12-31') | | selected | Date | 否 | 设置选中项的日期。
默认值:当前系统日期
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 | +**异常情形说明:** + +| 异常情形 | 对应结果 | +| -------- | ------------------------------------------------------------ | +| 起始日期晚于结束日期,选中日期未设置 | 起始日期、结束日期和选中日期都为默认值 | +| 起始日期晚于结束日期,选中日期早于起始日期默认值 | 起始日期、结束日期都为默认值,选中日期为起始日期默认值 | +| 起始日期晚于结束日期,选中日期晚于结束日期默认值 | 起始日期、结束日期都为默认值,选中日期为结束日期默认值 | +| 起始日期晚于结束日期,选中日期在起始日期与结束日期默认值范围内 | 起始日期、结束日期都为默认值,选中日期为设置的值 | +| 选中日期早于起始日期 | 选中日期为起始日期 | +| 选中日期晚于结束日期 | 选中日期为结束日期 | +| 起始日期晚于当前系统日期,选中日期未设置 | 选中日期为起始日期 | +| 结束日期早于当前系统日期,选中日期未设置 | 选中日期为结束日期 | +| 日期格式不符合规范,如‘1999-13-32’ | 取默认值 | +| 起始日期或结束日期早于系统有效范围 | 起始日期或结束日期取系统有效范围最早日期 | +| 起始日期或结束日期晚于系统有效范围 | 起始日期或结束日期取系统有效范围最晚日期 | + +系统日期范围:1900-1-31 ~ 2100-12-31 + +选中日期会在起始日期与结束日期异常处理完成后再进行异常情形判断处理 + ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md index 186fc08864a5b5a8da793bd3f3b1fed536f940a0..ce1cffabe846b63c78516bff04e9f615c59de951 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -68,7 +68,7 @@ struct GaugeExample { // 参数设置当前值为75,属性设置值为25,属性设置优先级高 Gauge({ value: 75 }) - .value(25) // 属性和参数都设置时以参数为准 + .value(25) // 属性和参数都设置时以属性为准 .width(200).height(200) .colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]]) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index 6163a9cc3a097bc2b1e30a10f5a139301d7a7af5..4e4158658ff7940b443f618a3bb944c8f048a791 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 @@ -1,6 +1,6 @@ # Image -图片组件,支持本地图片和网络图片的渲染展示。 +Image为图片组件,常用于在应用中显示图片。Image支持加载[PixelMap](../apis/js-apis-image.md#pixelmap7)、[ResourceStr](ts-types.md#resourcestr)和[DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor)类型的数据源,支持png、jpg、bmp、svg和gif类型的图片格式。 > **说明:** > @@ -21,77 +21,122 @@ Image(src: PixelMap | ResourceStr | DrawableDescriptor) -通过图片数据源获取图片,用于后续渲染展示。Image组件加载图片失败或图片尺寸为0时,图片组件大小自动为0,不跟随父组件的布局约束。 +通过图片数据源获取图片,用于后续渲染展示。 + +Image组件加载图片失败或图片尺寸为0时,图片组件大小自动为0,不跟随父组件的布局约束。 从API version 9开始,该接口支持在ArkTS卡片中使用。 **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src |  [PixelMap](../apis/js-apis-image.md#pixelmap7) \|ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | 是 | 图片的数据源,支持本地图片和网络图片。
当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。
\- 支持的图片格式包括png、jpg、bmp、svg和gif。
\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
\- 支持`datashare://`路径前缀的字符串,用于访问通过data ability提供的图片路径。
\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。
\- 支持[DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor)对象
- 详细使用方法可参考[显示图片](../../ui/arkts-graphics-display.md)
**说明:**
- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。
- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串
- ArkTS卡片上不支持 [PixelMap](../apis/js-apis-image.md#pixelmap7)类型 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | 是 | 图片的数据源,支持本地图片和网络图片,引用方式请参考[加载图片资源](../../ui/arkts-graphics-display.md#加载图片资源)。
1. PixelMap格式为像素图,常用于图片编辑的场景。
2. ResourceStr包含Resource和string格式。
string格式可用于加载网络图片和本地图片,常用于加载网络图片。当使用相对路径引用本地图片时,例如Image("common/test.jpg"),不支持跨包/跨模块调用该Image组件,建议使用Resource格式来管理需全局使用的图片资源。
- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
- 支持file://路径前缀的字符串。用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。
Resource格式可以跨包/跨模块访问资源文件,是访问本地图片的推荐方式。
3. 当传入资源id或name为普通图片时,生成DrawableDescriptor对象。
**说明:**
- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。
- ArkTS卡片上不支持http://等网络相关路径前缀和file://路径前缀的字符串。
- ArkTS卡片上不支持 [PixelMap](../apis/js-apis-image.md#pixelmap7)类型。 | ## 属性 -除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: - -| 名称 | 参数类型 | 描述 | -| ------------------------ | ---------------------------------------- | ---------------------------------------- | -| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。
默认值:ImageRepeat.NoRepeat
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。 | -| interpolation | [ImageInterpolation](#imageinterpolation) | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。
默认值:ImageInterpolation.None
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。
PixelMap资源不支持该属性。 | -| renderMode | [ImageRenderMode](#imagerendermode) | 设置图片渲染的模式。
默认值:ImageRenderMode.Original
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。 | -| sourceSize | {
width: number,
height: number
} | 设置图片裁剪尺寸,将原始图片解码成pixelMap,指定尺寸的图片,单位为px。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
PixelMap资源和SVG图片不支持该属性。 | -| matchTextDirection | boolean | 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| fitOriginalSize | boolean | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| fillColor | [ResourceColor](ts-types.md#resourcecolor) | 填充颜色。设置的填充颜色会覆盖在图片上。仅对svg图源生效,设置后会替换svg图片的fill颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| autoResize | boolean | 是否需要在图片解码过程中对图源做resize操作,该操作会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| syncLoad8+ | boolean | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置图片是否可复制(SVG图片不支持复制)。
当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键'CTRL+C'等方式进行复制。
默认值:CopyOptions.None
该接口支持在ArkTS卡片中使用。 | -| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | 给图像设置颜色滤镜效果。
该接口支持在ArkTS卡片中使用。 | -| draggable(deprecated) | boolean | 设置默认拖拽效果。(不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用。)
默认值:false
该接口支持在ArkTS卡片中使用。
**说明:**
从 API version 9 开始支持,从 API version 10 开始废弃,建议使用通用属性[draggable](ts-universal-events-drag-drop.md)替代。 | +属性的详细使用指导请参考[添加属性](../../ui/arkts-graphics-display.md#添加属性)。除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: + +| 名称 | 参数类型 | 描述 | +| -------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | +| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片(png、jpg、bmp、svg和gif类型),不支持网络图片。
默认值:null
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。从中心点向两边重复,剩余空间不足放下一张图片时会截断。
默认值:ImageRepeat.NoRepeat
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。 | +| interpolation | [ImageInterpolation](#imageinterpolation) | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。
默认值:ImageInterpolation.None
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。
PixelMap资源不支持该属性。 | +| renderMode | [ImageRenderMode](#imagerendermode) | 设置图片的渲染模式为原色或黑白。
默认值:ImageRenderMode.Original
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
svg类型图源不支持该属性。 | +| sourceSize | {
width: number,
height: number
} | 设置图片解码尺寸,降低图片的分辨率,常用于需要让图片显示尺寸比组件尺寸更小的场景。和ImageFit.None配合使用时可在组件内显示小图。
单位:px
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在目标尺寸小于图源尺寸时生效。
svg类型图源不支持该属性。
PixelMap资源不支持该属性。 | +| matchTextDirection | boolean | 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fitOriginalSize | boolean | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fillColor | [ResourceColor](ts-types.md#resourcecolor) | 设置填充颜色,设置后填充颜色会覆盖在图片上。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅对svg图源生效,设置后会替换svg图片的填充颜色。 | +| autoResize | boolean | 设置图片解码过程中是否对图源自动缩放。设置为true时,组件会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。如原图大小为1920x1080,而显示区域大小为200x200,则图片会自动解码到200x200的尺寸,大幅度节省图片占用的内存。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| 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)替代。 | > **说明:** > -> 使用快捷组合键对Image组件复制的前提是,该组件必须处于获焦状态。将Image组件的属性focusable设置为true,即可使用TAB键将焦点切换到Image组件上,再将Image组件的focusOnTouch属性设置为true,即可实现点击获焦。 -> 图片设置svg图源时,支持的标签范围有限,目前支持的svg标签包括svg、rect、circle、ellipse、path、line、polyline、polygon。 +> - 使用快捷组合键对Image组件复制时,Image组件必须处于[获焦状态](../../ui/arkts-common-events-focus-event.md#设置组件是否获焦)。Image组件默认不获焦,需将[focusable](ts-universal-attributes-focus.md)属性设置为true,即可使用TAB键将焦点切换到组件上,再将[focusOnTouch](ts-universal-attributes-focus.md)属性设置为true,即可实现点击获焦。 +> - 图片设置为svg图源时,当前支持的标签是svg、rect、circle、ellipse、path、line、polyline和polygon。 -### ImageInterpolation +## ImageInterpolation 从API version 9开始,该接口支持在ArkTS卡片中使用。 -| 名称 | 描述 | -| ------ | ------------------------- | -| None | 不使用插值图片数据。 | -| High | 插值图片数据的使用率高,可能会影响图片渲染的速度。 | -| Medium | 插值图片数据的使用率中。 | -| Low | 插值图片数据的使用率低。 | +| 名称 | 描述 | +| ------ | ---------------------------------------------------- | +| None | 不使用图片插值。 | +| High | 高图片插值,插值质量最高,可能会影响图片渲染的速度。 | +| Medium | 中图片插值。 | +| Low | 低图片插值。 | -### ImageRenderMode +## ImageRenderMode 从API version 9开始,该接口支持在ArkTS卡片中使用。 -| 名称 | 描述 | -| -------- | --------------------- | -| Original | 按照原图进行渲染,包括颜色。 | -| Template | 将图片渲染为模板图片,忽略图片的颜色信息。 | +| 名称 | 描述 | +| -------- | -------------- | +| Original | 原色渲染模式。 | +| Template | 黑白渲染模式。 | ## 事件 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: -| 名称 | 功能描述 | -| ---------------------------------------- | ---------------------------------------- | -| onComplete(callback: (event?: { width: number, height: number, 
componentWidth: number, componentHeight: number, 
loadingStatus: number ,contentWidth10+: number, 
contentHeight10+: number, contentOffsetX10+: number, 
contentOffsetY10+: number}) => void) | 图片成功加载时触发该回调,返回成功加载的图片尺寸。
- width:图片的宽,单位为像素。
- height:图片的高,单位为像素。
- componentWidth:组件的宽,单位为像素。
- componentHeight:组件的高,单位为像素。
- loadingStatus:图片加载成功的状态。
- contentWidth:图片实际绘制的宽度,单位为像素。
- contentHeight:图片实际绘制的高度,单位为像素。
- contentOffsetX:实际绘制内容相对于组件自身的x轴偏移,单位为像素。
- contentOffsetY:实际绘制内容相对于组件自身的y轴偏移,单位为像素。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
loadingStatus返回的状态值为0时,代表图片加载失败;返回的状态值为1时,代表图片加载成功, API version 10新增属性仅在loadingStatus返回1时有效。 | -| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | 图片加载出现异常时触发该回调。
- componentWidth:组件的宽,单位为像素。
- componentHeight:组件的高,单位为像素。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| onFinish(event: () => void) | 当加载的源文件为带动效的svg图片时,当svg动效播放完成时会触发这个回调,如果动效为无限循环动效,则不会触发这个回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +### onComplete + +onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number}) => void) }) => void) + +图片数据加载成功和解码成功时均触发该回调,返回成功加载的图片尺寸。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------------------------- | ------ | ------------------------------------------------------------ | +| width | number | 图片的宽。
单位:像素 | +| height | number | 图片的高。
单位:像素 | +| componentWidth | number | 组件的宽。
单位:像素 | +| componentHeight | number | 组件的高。
单位:像素 | +| loadingStatus | number | 图片加载成功的状态值。
**说明:**
返回的状态值为0时,表示图片数据加载成功。返回的状态值为1时,表示图片解码成功。 | +| contentWidth10+ | number | 图片实际绘制的宽度。
单位:像素
**说明:**
仅在loadingStatus返回1时有效。 | +| contentHeight10+ | number | 图片实际绘制的高度。
单位:像素
**说明:**
仅在loadingStatus返回1时有效。 | +| contentOffsetX10+ | number | 实际绘制内容相对于组件自身的x轴偏移。
单位:像素
**说明:**
仅在loadingStatus返回1时有效。 | +| contentOffsetY10+ | number | 实际绘制内容相对于组件自身的y轴偏移。
单位:像素
**说明:**
仅在loadingStatus返回1时有效。 | + + +### onError + +onError(callback: (event?: { componentWidth: number, componentHeight: number , message: string }) => void) + +图片加载异常时触发该回调。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| -------------------- | ------ | ------------------------- | +| componentWidth | number | 组件的宽。
单位:像素 | +| componentHeight | number | 组件的高。
单位:像素 | +| message9+ | string | 报错信息。 | + + +### onFinish + +onFinish(event: () => void) + +当加载的源文件为带动效的svg格式图片时,svg动效播放完成时会触发这个回调。如果动效为无限循环动效,则不会触发这个回调。 + +仅支持svg格式的图片。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 ## 示例 -### 图片加载 +### 加载基本类型图片 -加载显示不同类型的图片,并设置图片的缩放类型。
overlay属性用于设置图片的遮罩文本,具体使用可参考[浮层](ts-universal-attributes-overlay.md)。 ```ts @Entry @@ -100,178 +145,70 @@ struct ImageExample1 { build() { Column() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) { - Row({ space: 5 }) { - Image($r('app.media.example_png')) - .width(110).height(110).border({ width: 1 }) + Row() { + // 加载png格式图片 + Image($r('app.media.ic_camera_master_ai_leaf')) + .width(110).height(110).margin(15) .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - Image($r('app.media.example_gif')) - .width(110).height(110).border({ width: 1 }) + // 加载gif格式图片 + Image($r('app.media.loading')) + .width(110).height(110).margin(15) .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) } - - Row({ space: 5 }) { - Image($r('app.media.example_svg')) - .width(110).height(110).border({ width: 1 }) + Row() { + // 加载svg格式图片 + Image($r('app.media.ic_camera_master_ai_clouded')) + .width(110).height(110).margin(15) .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - Image($r('app.media.example_jpg')) - .width(110).height(110).border({ width: 1 }) + // 加载jpg格式图片 + Image($r('app.media.ic_public_favor_filled')) + .width(110).height(110).margin(15) .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - }.margin({ top: 25, bottom: 10 }) + } } }.height(320).width(360).padding({ right: 10, top: 10 }) } } ``` -![zh-cn_image_0000001250492613](figures/zh-cn_image_0000001250492613.gif) +![zh-cn_image_0000001592882500](figures/zh-cn_image_0000001592882500.gif) +### 加载网络图片 +加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。如果需要更灵活的网络配置,可以使用[HTTP](../../connectivity/http-request.md)工具包发送网络请求,接着将返回的数据解码为Image组件中的`PixelMap`,图片开发可参考[图片处理](../../media/image-overview.md)。 -### 网络图片 - -加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。如果需要更灵活的网络配置,可以使用SDK中提供的[HTTP](../../connectivity/http-request.md)工具包发送网络请求,接着将返回的数据解码为Image组件中的`PixelMap`,图片开发可参考[图片处理](../../media/image-overview.md)。代码如下。 - -```tsx -// @ts-nocheck -import http from '@ohos.net.http'; -import ResponseCode from '@ohos.net.http' -import image from '@ohos.multimedia.image' - - -@Entry -@Component -struct Index { - - // 先创建一个PixelMap状态变量用于接收网络图片 - @State image: PixelMap = undefined - - build() { - Column({space: 10}) { - Button("获取网络图片") - .onClick(() => { - this.httpRequest() - }) - Image(this.image).height(100).width(100) - } - .width('100%') - .height('100%') - .padding(10) - } - - // 网络图片请求方法 - private httpRequest() { - let httpRequest = http.createHttp() - - httpRequest.request( - "https://www.example.com/xxx.png", // 请填写一个具体的网络图片地址 - (error, data) => { - if(error) { - console.log("error code: " + error.code + ", msg: " + error.message) - } else { - let code = data.responseCode - if(ResponseCode.ResponseCode.OK == code) { - let imageSource = image.createImageSource(data.result) - let options = {alphaType: 0, // 透明度 - editable: false, // 是否可编辑 - pixelFormat: 3, // 像素格式 - scaleMode: 1, // 缩略值 - size: {height: 100, width: 100}} // 创建图片大小 - imageSource.createPixelMap(options).then((pixelMap) => { - this.image = pixelMap - }) - } else { - console.log("response code: " + code) - } - } - } - ) - } -} -``` - -**说明**:网络图片加载的请求方式、超时、额外请求参数等配置可以参考HTTP工具包中关于[`request()`](../../reference/apis/js-apis-http.md)请求方法的细节。 - -### 设置属性 +使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[权限申请声明](../../security/accesstoken-guidelines.md)。 ```ts @Entry @Component struct ImageExample2 { - build() { Column({ space: 10 }) { - Text('renderMode').fontSize(12).fontColor(0xcccccc).width('96%').height(30) - Row({ space: 50 }) { - Image($r('app.media.img_example')) - .renderMode(ImageRenderMode.Original).width(100).height(100) - .border({ width: 1 }) - .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - Image($r('app.media.img_example')) - .renderMode(ImageRenderMode.Template).width(100).height(100) - .border({ width: 1 }) - .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - } - - Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30) - Image('') - .alt($r('app.media.Image_none')) - .width(100).height(100).border({ width: 1 }) - - Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%') - Row({ space: 50 }) { - Image($r('app.media.img_example')) - .sourceSize({ - width: 150, - height: 150 - }) - .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1) - .border({ width: 1 }) - .overlay('w:150 h:150', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - Image($r('app.media.img_example')) - .sourceSize({ - width: 200, - height: 200 - }) - .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1) - .border({ width: 1 }) - .overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - } - - Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30) - Row({ space: 5 }) { - Image($r('app.media.ic_health_heart')) - .width(120).height(125).border({ width: 1 }) - .objectRepeat(ImageRepeat.XY).objectFit(ImageFit.ScaleDown) - .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - Image($r('app.media.ic_health_heart')) - .width(110).height(125).border({ width: 1 }) - .objectRepeat(ImageRepeat.Y).objectFit(ImageFit.ScaleDown) - .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - Image($r('app.media.ic_health_heart')) - .width(110).height(125).border({ width: 1 }) - .objectRepeat(ImageRepeat.X).objectFit(ImageFit.ScaleDown) - .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) - } - }.height(150).width('100%').padding({ right: 10 }) + Image("https://www.example.com/xxx.png")// 直接加载网络地址,请填写一个具体的网络图片地址 + .alt($r('app.media.icon'))// 使用alt,在网络图片加载成功前使用占位图 + .width(100) + .height(100) + } } } ``` -![zh-cn_image_0000001205812616](figures/zh-cn_image_0000001205812616.png) -### 事件调用 +### 为图片添加事件 + ```ts @Entry @Component struct ImageExample3 { - @State widthValue: number = 0 - @State heightValue: number = 0 - private on: Resource = $r('app.media.image_on') - private off: Resource = $r('app.media.image_off') - private on2off: Resource = $r('app.media.image_on2off') - private off2on: Resource = $r('app.media.image_off2on') - @State src: Resource = this.on + @State widthValue: number = 0; + @State heightValue: number = 0; + private on: Resource = $r('app.media.image_on'); + private off: Resource = $r('app.media.image_off'); + private on2off: Resource = $r('app.media.image_on2off'); + private off2on: Resource = $r('app.media.image_off2on'); + @State src: Resource = this.on; build() { Column() { @@ -298,7 +235,7 @@ struct ImageExample3 { offset: { x: 0, y: 20 } }) } - // 为图片添加点击事件,点击完成后加载特定图片。 + // 为图片添加点击事件,点击完成后加载特定图片 Image(this.src) .width(120).height(120) .onClick(() => { @@ -321,144 +258,4 @@ struct ImageExample3 { } ``` -![zh-cn_image_0000001205972610](figures/zh-cn_image_0000001205972610.gif) - -### 渲染沙箱路径图片 - -```ts -import fileio from '@ohos.fileio'; -import fs from '@ohos.file.fs'; -import context from '@ohos.app.ability.common'; - -@Entry -@Component -struct LoadImageExample { - @State resourcesPath: string = '' - @State sandboxPath: string = '' - context: context.UIAbilityContext = getContext(this) as context.UIAbilityContext - - build() { - Column() { - Button('读取沙箱图片') - .margin({ bottom: 10, top: 10 }) - .onClick(() => { - this.sandboxPath = this.context.getApplicationContext().filesDir + '/icon.png' - console.log(`读取沙箱图片=========>${this.sandboxPath}`) - let fd = fs.openSync(this.sandboxPath, 0o100) - console.log(`create file========>${fd}`) - let srcPath = this.context.bundleCodeDir + '/entry/resources/base/media/icon.png' - console.log('mySrcpath' + srcPath) - fileio.copyFileSync(srcPath, this.sandboxPath) // 复制图片到沙箱路径 - this.sandboxPath = 'file://' + this.context.getApplicationContext().filesDir + '/icon.png' - }) - Button('读取资源图片') - .margin({ bottom: 10 }) - .onClick(() => { - this.resourcesPath = 'file://' + this.context.bundleCodeDir + '/entry/resources/base/media/icon.png' - }) - Text(`资源图片路径:${this.resourcesPath}`) - .fontSize(20) - .margin({ bottom: 10 }) - Image(this.resourcesPath) - .width(100) - .height(100) - .colorFilter([ - 0.30, 0.59, 0.11, 0, 0, - 0.30, 0.59, 0.11, 0, 0, - 0.30, 0.59, 0.11, 0, 0, - 0, 0, 0, 1.0, 0 - ]) - Text(`沙箱图片路径:${this.sandboxPath}`) - .fontSize(20) - .margin({ bottom: 10 }) - Image(this.sandboxPath) - .width(100) - .height(100) - } - .width('100%').height('100%') - } -} -``` - -### 为图片增加滤镜 - -```ts -// xxx.ets -@Entry -@Component -struct colorFilterExample { - @State colorFilterR: number = 0 - @State colorFilterG: number = 0 - @State colorFilterB: number = 0 - @State colorFilterA: number = 0 - - build() { - Row() { - Column() { - Image($r('app.media.sky')) - .width(200) - .height(200) - Image($r('app.media.sky')) - .width(200) - .height(200) - .colorFilter([ - this.colorFilterR, 0, this.colorFilterR, 0, 0, - 0, this.colorFilterG, this.colorFilterG, 0, 0, - this.colorFilterB, 0, this.colorFilterB, 0, 0, - 0, 0, this.colorFilterA, 0, 0 - ]) - - Row() { - Text('R') - Slider({ - min: 0, - max: 1, - step: 0.01 - }) - .onChange((valueR) => { - this.colorFilterR = valueR - }) - } - - Row() { - Text('G') - Slider({ - min: 0, - max: 1, - step: 0.01 - }) - .onChange((valueG) => { - this.colorFilterG = valueG - }) - } - - Row() { - Text('B') - Slider({ - min: 0, - max: 1, - step: 0.01 - }) - .onChange((valueB) => { - this.colorFilterB = valueB - }) - } - - Row() { - Text('A') - Slider({ - min: 0, - max: 1, - step: 0.01 - }) - .onChange((valueA) => { - this.colorFilterA = valueA - }) - } - }.width('90%').alignItems(HorizontalAlign.Center) - }.height('100%').width('100%').justifyContent(FlexAlign.Center) - } -} -``` - -![colorFilter](figures/colorFilter.gif) \ No newline at end of file +![zh-cn_image_0000001607845173](figures/zh-cn_image_0000001607845173.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md index 228c3f9293649d7e6e7eb13aeaf8568bb4876150..0c86c7f80fc6dbbf5fcc83b31c03b7c39fbaac7f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md @@ -25,11 +25,11 @@ ImageSpan(value: ResourceStr | PixelMap) ## 属性 -[通用属性](ts-universal-attributes-size.md)方法仅支持宽(width)、高(height)和size。 +[通用属性](ts-universal-attributes-size.md)方法支持尺寸设置、背景设置、边框设置。 | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | 图片基于文本的对齐方式。 | +| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | 图片基于文本的对齐方式。
默认值:ImageSpanAlignment.BOTTOM | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover | ## ImageSpanAlignment diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md index 749862d2f2a64193ca641ab384426e0b223845bb..c0485b25da8e7c866f618286b2c8ac0bec511346 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md @@ -30,7 +30,7 @@ Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boole | src | string | 是 | 需要滚动的文本。 | ## 属性 - +除支持文本通用属性:fontColor、fontSize、fontWeight、fontFamily外,还支持以下属性: | 名称 | 参数类型 | 描述 | | ---------- | -------- | ------------------------------------------------------------ | | allowScale | boolean | 是否允许文本缩放。
暂不支持该接口。
默认值:false
| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index b67a7b34017d30ae99143e6819b579d21c0b4e52..8f41626354e47508dbdf4c13263f741a4f1ae619 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -36,18 +36,19 @@ Navigation组件一般作为Page页面的根容器,通过属性设置来展示 | subTitle(deprecated) | string | 页面副标题。不设置时不显示副标题。从API Version 9开始废弃,建议使用title代替。 | | menus | Array<[NavigationMenuItem](#navigationmenuitem类型说明)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 页面右上角菜单。不设置时不显示菜单项。使用Array<[NavigationMenuItem](#navigationmenuitem类型说明)> 写法时,竖屏最多支持显示3个图标,横屏最多支持显示5个图标,多余的图标会被放入自动生成的更多图标。 | | titleMode | [NavigationTitleMode](#navigationtitlemode枚举说明) | 页面标题栏显示模式。
默认值:NavigationTitleMode.Free | -| toolBar | [object](#object类型说明) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 设置工具栏内容。不设置时不显示工具栏。
items: 工具栏所有项。
**说明:**
items均分底部工具栏,在每个均分内容区布局文本和图标,文本超长时,逐级缩小,缩小之后换行,最后...截断。 | +| toolBar(deprecated) | [object](#object类型说明) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 设置工具栏内容。不设置时不显示工具栏。
items: 工具栏所有项。
**说明:**
items均分底部工具栏,在每个均分内容区布局文本和图标,文本超长时,逐级缩小,缩小之后换行,最后...截断。
从API version 10开始,该接口不再维护,推荐使用toolbarConfiguration代替。 | +| toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10类型说明)10+> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 设置工具栏内容。不设置时不显示工具栏。
**说明:**
使用Array<[ToolbarItem](#ToolbarItem类型说明)>写法设置的工具栏有如下特性:
工具栏所有选项均分底部工具栏,在每个均分内容区布局文本和图标。
文本超长时,若工具栏选项个数小于5个,优先拓展选项的宽度,最大宽度与屏幕等宽,其次逐级缩小,缩小之后换行,最后...截断。
竖屏最多支持显示5个图标,多余的图标会被放入自动生成的更多图标。横屏下必须配合menus属性的Array<[NavigationMenuItem](#navigationmenuitem类型说明)>使用,底部工具栏会自动隐藏,同时底部工具栏所有选项移动至页面右上角菜单。
使用[CustomBuilder](ts-types.md#custombuilder8)写法为用户自定义工具栏选项,除均分底部工具栏外不具备以上功能。 | | hideToolBar | boolean | 隐藏工具栏。
默认值:false
true: 隐藏工具栏。
false: 显示工具栏。 | | hideTitleBar | boolean | 隐藏标题栏。
默认值:false
true: 隐藏标题栏。
false: 显示标题栏。 | | hideBackButton | boolean | 隐藏返回键。
默认值:false
true: 隐藏返回键。
false: 显示返回键。
不支持隐藏NavDestination组件标题栏中的返回图标。
**说明:**
返回键仅针对titleMode为NavigationTitleMode.Mini时才生效。 | -| navBarWidth9+ | [Length](ts-types.md#length) | 导航栏宽度。
默认值:200
单位:vp
**说明:**
仅在Navigation组件分栏时生效。 | +| navBarWidth9+ | [Length](ts-types.md#length) | 导航栏宽度。
默认值:240
单位:vp
**说明:**
仅在Navigation组件分栏时生效。 | | navBarPosition9+ | [NavBarPosition](#navbarposition枚举说明) | 导航栏位置。
默认值:NavBarPosition.Start
**说明:**
仅在Navigation组件分栏时生效。 | -| mode9+ | [NavigationMode](#navigationmode枚举说明) | 导航栏的显示模式。
默认值:NavigationMode.Auto
自适应:基于组件宽度自适应单栏和双栏。 | +| mode9+ | [NavigationMode](#navigationmode枚举说明) | 导航栏的显示模式。
默认值:NavigationMode.Auto
自适应:基于组件宽度自适应单栏和双栏。
**说明:**
支持Stack、Split与Auto模式。 | | backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | 设置导航栏返回图标。不支持隐藏NavDestination组件标题栏中的返回图标。 | | hideNavBar9+ | boolean | 是否显示导航栏(仅在mode为NavigationMode.Split时生效)。 | | navDestination10+ | builder: (name: string, param: unknown) => void | 创建NavDestination组件。
**说明:**
使用builder函数,基于name和param构造NavDestination组件。builder中允许在NavDestination组件外包含一层自定义组件, 但自定义组件不允许设置属性和事件,否则仅显示空白。 | -| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | 导航栏最小和最大宽度。
默认值:[240, 280]
单位:vp | -| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | 导航栏内容区最小宽度。
默认值:360
单位:vp | +| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | 导航栏最小和最大宽度(双栏模式下生效)。
默认值:最小默认值 240,最大默认值为组件宽度的40% ,且不大于 432。
单位:vp
规则:
开发者设置优先级 > 默认值
最小值优先级 > 最大值
navBar 优先级 > content优先级
开发者设置多个值冲突,以全局数值优先,局部最小值跟随容器大小。 | +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | 导航栏内容区最小宽度(双栏模式下生效)。
默认值:360
单位:vp
规则:
开发者设置优先级 > 默认值
最小值优先级 > 最大值
navBar优先级 > content优先级
开发者设置多个值冲突,以全局数值优先,局部最小值跟随容器大小。
Auto模式断点计算:默认600vp,minNavBarWidth(240vp) + minContentWidth (360vp) | ## NavPathStack10+ @@ -267,6 +268,24 @@ constructor(name: string, param: unknown) | icon | string | 否 | 工具栏单个选项的图标资源路径。 | | action | () => void | 否 | 当前选项被选中的事件回调。 | +## ToolbarItem10+类型说明 + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- | +| value | ResourceStr | 是 | 工具栏单个选项的显示文本。 | +| icon | ResourceStr | 否 | 工具栏单个选项的图标资源路径。 | +| action | () => void | 否 | 当前选项被选中的事件回调。 | +| status | [ToolbarItemStatus](#toolbaritemstatus10枚举说明) | 否 | 工具栏单个选项的状态。
默认值:ToolbarItemStatus.NORMAL | +| activeIcon | ResourceStr | 否 | 工具栏单个选项处于ACTIVE态时的图标资源路径。 | + +## ToolbarItemStatus10+枚举说明 + +| 名称 | 描述 | +| -------- | ------------------------------------------------------------ | +| NORMAL | 设置工具栏单个选项为NORMAL态,该选项显示默认样式,可以触发Hover,Press,Focus事件并显示对应的多态样式。 | +| DISABLED | 设置工具栏单个选项为DISABLED态, 该选项显示DISABLED态样式,并且不可交互。 | +| ACTIVE | 设置工具栏单个选项为ACTIVE态, 该选项通过点击事件可以将icon图标更新为activeIcon对应的图片资源。 | + ## NavigationTitleMode枚举说明 | 名称 | 描述 | @@ -298,11 +317,11 @@ constructor(name: string, param: unknown) ## NavigationMode枚举说明 -| 名称 | 描述 | -| ----- | ---------------------------------------- | +| 名称 | 描述 | +| ----- | ------------------------------------------------------------ | | Stack | 导航栏与内容区独立显示,相当于两个页面。 | -| Split | 导航栏与内容区分两栏显示。 | -| Auto | 窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。 | +| Split | 导航栏与内容区分两栏显示。 | +| Auto | API version 9之前:窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。
API version 10及以上:窗口宽度>=600vp时,采用Split模式显示;窗口宽度<600vp时,采用Stack模式显示,600vp等于minNavBarWidth(240vp) + minContentWidth (360vp)。 | ## TitleHeight枚举说明 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 13653c27a6f350091794ea36af4c6847209fe355..99065afdcd9233733cb66d0d4bc08f4b8c74b4b8 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 @@ -22,7 +22,7 @@ PatternLock(controller?: PatternLockController) ## 属性 -不支持除backgroundColor以外的通用属性设置。 +除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: | 名称 | 参数类型 | 描述 | | --------------- | ------------------------------------- | ------------------------------------------------------------ | 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 3815626b1e12dde989f20738df509a3f77f86bf4..16d0c313fe393f4a6c4674dbfa8acb78d6f51100 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 @@ -114,7 +114,7 @@ Span位置信息。 | ------ | -------- | ---- | -------------------------------------- | | size | [number, number] | 是 | 图片的宽度和高度。 | | verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | 是 | 图片垂直对齐方式。 | -| objectFit | [ImageFit]((ts-basic-components-imagespan.md#imagefit)) | 是 | 图片缩放类型。 | +| objectFit | [ImageFit](ts-basic-components-imagespan.md#imagefit) | 是 | 图片缩放类型。 | ## RichEditorOptions @@ -158,7 +158,7 @@ setCaretOffset(offset: number): boolean | 参数名 | 参数类型 | 必填 | 参数描述 | | ------ | -------- | ---- | -------------------------------------- | -| offset | number | 是 | 光标偏移位置。 | +| offset | number | 是 | 光标偏移位置。超出文本范围时,设置失败。 | **返回值:** @@ -265,8 +265,8 @@ deleteSpans(value?: RichEditorRange): void | 名称 | 类型 | 必填 | 描述 | | ------ | -------- | ---- | -------------------------------------- | -| start | number | 否 | 需要更新样式的文本起始位置,省略时表示从0开始。 | -| end | number | 否 | 需要更新样式的文本结束位置,省略时表示到结尾。 | +| start | number | 否 | 需要更新样式的文本起始位置,省略或者设置负值时表示从0开始。 | +| end | number | 否 | 需要更新样式的文本结束位置,省略或者超出文本范围时表示到结尾。 | | textStyle | [RichEditorTextStyle](#richeditortextstyle) | 是 | 文本样式。 | @@ -276,8 +276,8 @@ deleteSpans(value?: RichEditorRange): void | 名称 | 类型 | 必填 | 描述 | | ------ | -------- | ---- | -------------------------------------- | -| start | number | 否 | 需要更新样式的图片起始位置,省略时表示从0开始。 | -| end | number | 否 | 需要更新样式的图片结束位置,省略时表示到结尾。 | +| start | number | 否 | 需要更新样式的图片起始位置,省略或者设置负值时表示从0开始。 | +| end | number | 否 | 需要更新样式的图片结束位置,省略或者超出文本范围时表示到结尾。 | | imageStyle | [RichEditorImageSpanStyle](#richeditorimagespanstyle) | 是 | 图片样式。 | @@ -296,12 +296,12 @@ deleteSpans(value?: RichEditorRange): void | 名称 | 类型 | 必填 | 描述 | | ------ | -------- | ---- | -------------------------------------- | -| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 文本颜色。 | -| fontSize | [Length](ts-types.md#length) \| number | 否 | 字体大小。 | -| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 否 | 字体样式。 | -| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | 否 | 字体粗细。 | -| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | 否 | 设置字体列表。默认字体'HarmonyOS Sans',且当前只支持这种字体。 | -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} \| number \| string | 否 | 设置文本装饰线样式及其颜色。 | +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 文本颜色。
默认值:Color.Black。 | +| fontSize | [Length](ts-types.md#length) \| number | 否 | 字体大小。
默认值:16fp。| +| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 否 | 字体样式。
默认值:FontStyle.Normal。 | +| fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | 否 | 字体粗细。
默认值:FontWeight.Normal。 | +| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | 否 | 设置字体列表。默认字体'HarmonyOS Sans',且当前只支持这种字体。
默认字体:'HarmonyOS Sans'。| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 否 | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
}。 | ## RichEditorImageSpanOptions @@ -320,8 +320,8 @@ deleteSpans(value?: RichEditorRange): void | 名称 | 类型 | 必填 | 描述 | | ------ | -------- | ---- | -------------------------------------- | | size | [Dimension, Dimension] | 否 | 图片宽度和高度。 | -| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | 否 | 图片垂直对齐方式。 | -| objectFit | [ImageFit]((ts-basic-components-imagespan.md#imagefit)) | 否 | 图片缩放类型。 | +| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | 否 | 图片垂直对齐方式。
默认值:ImageSpanAlignment.BASELINE | +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 否 | 图片缩放类型。
默认值:ImageFit.Cover。 | ## RichEditorRange @@ -329,8 +329,8 @@ deleteSpans(value?: RichEditorRange): void | 名称 | 类型 | 必填 | 描述 | | ------ | -------- | ---- | -------------------------------------- | -| start | number | 否 | 起始位置,省略时表示从0开始。 | -| end | number | 否 | 结束位置,省略时表示到结尾。 | +| start | number | 否 | 起始位置,省略或者设置负值时表示从0开始。 | +| end | number | 否 | 结束位置,省略或者超出文本范围时表示到结尾。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index e29d853d6a68151476bb6d81d3eeef83564de0c4..f394f34b2831a18f6b4fe2c4cc1a15bbe75eedc0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -52,6 +52,19 @@ RichText(content:string) | style | 属性规定元素的行内样式,写在标签内部,在使用的时候需用引号来进行区分,并以; 间隔样式,style='width: 500px;height: 500px;border: 1px soild;margin: 0 auto;'。 | \

这是一个标题\

\

这是一个段落。\

| | \ | 用于定义客户端脚本,比如JavaScript。 | \ | + +## 使用场景 + +RichText组件底层复用了Web组件来提供基础能力,包括但不限于HTML页面的解析、渲染等。但由于Web组件比较消耗资源,所以在一些重复使用RichText组件的场景下,比如在List下循环重复使用RichText时,会出现卡顿、滑动响应慢等现象。 + +RichText使用Web提供基础能力,同样遵循Web约束条件。常见典型场景如下: + +移动设备的视口默认值大小为980px,默认值可以确保大部分网页在移动设备下可以正常浏览。如果RichText组件宽度低于这个值,content内部的HTML则可能会生产一个可以滑动的页面被RichText组件包裹。如果想替换默认值,可以在content中添加以下标签: + +```html + +``` + ## 示例 示例效果请以真机运行为准,当前IDE预览器不支持。 @@ -83,7 +96,7 @@ struct RichTextExample { console.info('RichText onComplete'); }) .width(500) - .height(400) + .height(500) .backgroundColor(0XBDDB69) RichText('layoutWeight(1)') .onStart(() => { @@ -112,6 +125,3 @@ struct RichTextExample { ![richText](figures/richText.png) -## 使用场景说明 - -RichText组件底层复用了Web组件来提供基础能力,包括但不限于HTML页面的解析、渲染等。但由于Web组件比较消耗资源,所以在一些重复使用RichText组件的场景下,比如在List下循环重复使用RichText时,会出现卡顿、滑动响应慢等现象。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md index 2bccc9841169e4b759debe1de330ede88afd75c7..70438299ccfda297a9f4f520c4b74864913f8d8d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -12,7 +12,7 @@ ## 接口 -Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; controller?: SearchController }) +Search(options?: { value?: string, placeholder?: ResourceStr, icon?: string, controller?: SearchController }) **参数:** @@ -20,7 +20,7 @@ Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; con | ----------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | value | string | 否 | 设置当前显示的搜索文本内容。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 | | placeholder | [ResourceStr](ts-types.md#resourcestr)10+ | 否 | 设置无输入时的提示文本。 | -| icon | string | 否 | 设置搜索图标路径,默认使用系统搜索图标。
**说明:**
icon的数据源支持本地图片和网络图片。
- 支持的图片格式包括png、jpg、bmp、svg、gif和pixelmap。
- 支持Base64字符串。格式data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], 其中[base64 data]为Base64字符串数据。 | +| icon | string | 否 | 设置搜索图标路径,默认使用系统搜索图标。
**说明:**
icon的数据源支持本地图片和网络图片。
- 支持的图片格式包括png、jpg、bmp、svg、gif和pixelmap。
- 支持Base64字符串。格式data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], 其中[base64 data]为Base64字符串数据。
如果与属性searchIcon同时设置,则searchIcon优先。 | | controller | SearchController | 否 | 设置Search组件控制器。 | ## 属性 @@ -30,15 +30,15 @@ Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; con | 名称 | 参数类型 | 描述 | | ----------------------- | ------------------------------------------------ | ---------------------------------------------- | | searchButton10+ | value: string,
option?: [SearchButtonOptions](#searchbuttonoptions10对象说明) | 搜索框末尾搜索按钮文本内容,默认无搜索按钮。 | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | 设置placeholder文本颜色。 | +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | 设置placeholder文本颜色。
默认值:'#99182431'。 | | placeholderFont | [Font](ts-types.md#font) | 设置placeholder文本样式,包括字体大小,字体粗细,字体族,字体风格。目前仅支持默认字体族。 | | textFont | [Font](ts-types.md#font) | 设置搜索框内输入文本样式,包括字体大小,字体粗细,字体族,字体风格。目前仅支持默认字体族。 | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本在搜索框中的对齐方式。
默认值:TextAlign.Start | -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置输入的文本是否可复制。 | +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置输入的文本是否可复制。
默认值:CopyOptions.LocalDevice,支持设备内复制。
设置CopyOptions.None时,当前Search中的文字无法被复制或剪切,仅支持粘贴。 | | searchIcon10+ | [IconOptions](#iconoptions10对象说明) | 设置左侧搜索图标样式。 | -| cancelButton10+ | {
style? : [CancelButtonStyle](#cancelbuttonstyle10枚举说明)
icon?: [IconOptions](#iconoptions10对象说明)
} | 设置右侧清除按钮样式。 | -| fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置输入文本的字体颜色。 | -| caretStyle10+ | [CaretStyle](#caretstyle10对象说明) | 设置光标样式。 | +| cancelButton10+ | {
style? : [CancelButtonStyle](#cancelbuttonstyle10枚举说明)
icon?: [IconOptions](#iconoptions10对象说明)
} | 设置右侧清除按钮样式。
默认值:
{
style:CancelButtonStyle.INPUT
} | +| fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置输入文本的字体颜色。
默认值:'#FF182431'。
**说明:**
[文本通用属性](ts-universal-attributes-text-style.md)fontSize、fontStyle、fontWeight和fontFamily在textFont属性中设置。 | +| caretStyle10+ | [CaretStyle](#caretstyle10对象说明) | 设置光标样式。
默认值:
{
width:1.5vp
color:'#007DFF'
} | | enableKeyboardOnFocus10+ | boolean | Search获焦时,是否绑定输入法
默认值:true。从API version 10开始,获焦默认绑定输入法。 | | selectionMenuHidden10+ | boolean | 设置长按输入框或者右键输入框时,是否弹出文本选择菜单。
默认值:false | ## IconOptions10+对象说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index b044077108773c9cdaf2f3623ebd1b78f6fa7131..d7e986a1cc3b9d1daa341b02ef97497319e33e71 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -26,6 +26,11 @@ StepperItem() | nextLabel | string | 设置右侧文本按钮内容,最后一页默认值为“开始”,其余页默认值为“下一步”。 | | status | [ItemState](#itemstate枚举说明) | 步骤导航器nextLabel的显示状态,参数可选。
默认值:ItemState.Normal | +> **说明:** +> +> - StepperItem组件不支持设置通用宽度属性,其宽度默认撑满Stepper父组件。 +> - StepperItem组件不支持设置通用高度属性,其高度由Stepper父组件高度减去label按钮组件高度。 +> - StepperItem组件不支持设置aspectRadio/constrainSize影响长宽的属性。 ## ItemState枚举说明 | 名称 | 描述 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index c348d3f6433b9a77f0dbe7c453de5882dcd9d3c5..726ef22b1622189d5080f9ef4986328194e38f01 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -40,7 +40,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | 正则表达式,匹配表达式的输入允许显示,不匹配的输入将被过滤。目前仅支持单个字符匹配,不支持字符串匹配。
- value:设置正则表达式。
- error:正则匹配失败时,返回被过滤的内容。 | | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 设置输入的文本是否可复制。
默认值:CopyOptions.LocalDevice,支持设备内复制。
设置CopyOptions.None时,当前TextInput中的文字无法被复制或剪切,仅支持粘贴。 | | showPasswordIcon9+ | boolean | 密码输入模式时,输入框末尾的图标是否显示。
默认值:true | -| style9+ | [TextInputStyle](#textinputstyle9枚举说明) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | 设置输入框为默认风格或内联输入风格。
默认值:TextInputStyle.Default | +| style9+ | [TextInputStyle](#textinputstyle9枚举说明) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | 设置输入框为默认风格或内联输入风格。
默认值:TextInputStyle.Default
TextInputStyle.Inline不支持设置文本对齐方式。 | | textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本在输入框中的水平对齐方式。
默认值:TextAlign.Start
**说明:**
仅支持TextAlign.Start、TextAlign.Center和TextAlign.End。
可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStart、Alignment.Top、Alignment.TopEnd效果相同,控制内容在顶部,Alignment.Start、Alignment.Center、Alignment.End效果相同,控制内容垂直居中,Alignment.BottomStart、Alignment.Bottom、Alignment.BottomEnd效果相同,控制内容在底部。 | | selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。
如果未设置透明度,默认为不透明(例如:“0x80000000”为50%透明度黑色)。 | | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | 设置光标风格。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md index 238a97c6c63944bd1c75906b5ea9f98dc2212d1c..40fe5b82e8cb8454557780eb4c1d19d5e83a219a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md @@ -47,7 +47,7 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance | --------- | ------------ | ---- | ------------------------------------------------------------ | | fingers | number | 否 | 触发滑动的最少手指数,最小为1指, 最大取值为10指。
默认值:1 | | direction | PanDirection | 否 | 设置滑动方向,此枚举值支持逻辑与(&)和逻辑或(\|)运算。
默认值:All | -| distance | number | 否 | 最小滑动识别距离,单位为vp。
默认值:5.0
**说明:**
> [Tabs组件](ts-container-tabs.md)滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | +| distance | number | 否 | 最小滑动识别距离,单位为vp。
默认值:5.0
**说明:**
[Tabs组件](ts-container-tabs.md)滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | **接口** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md index a3905ad72521723f47ae51ea87016513cc574a9a..cb28b74e70fdd9ccb2df68548a07b1fcbf65ba6f 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,36 +272,51 @@ - [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) + + 超链接组件,组件宽高范围内点击实现跳转。 + - [Menu](ts-basic-components-menu.md) 以垂直列表形式显示的菜单。 + - [MenuItem](ts-basic-components-menuitem.md) 用来展示菜单Menu中具体的item菜单项。 + - [MenuItemGroup](ts-basic-components-menuitemgroup.md) 用来展示菜单MenuItem的分组。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md index 72b91171c695749c6adc5588e21c68b7beadbec5..8dfd81cf963c576bf0c99c1636d91a1e3d9413d3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md @@ -6,13 +6,10 @@ > > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - - ## 子组件 可以包含子组件。 - ## 接口 ColumnSplit() @@ -20,17 +17,24 @@ ColumnSplit() ## 属性 -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | -| resizeable | boolean | 分割线是否可拖拽,默认为false。 | +| 名称 | 参数类型 | 描述 | +|-----------------------|-------------------------------------------------------------------|---------------------------------| +| resizeable | boolean | 分割线是否可拖拽,默认为false。 | +| divider10+ | [ColumnSplitDividerStyle](#columnsplitdividerstyle10对象说明) \| null | 设置分割线的margin。
- DividerStyle:设置分割线与上下子节点的距离。
- 默认为null:分割线上下margin为0。 | + +## ColumnSplitDividerStyle10+对象说明 + +| 名称 | 参数类型 | 必填 | 描述 | +| ----------- | ------------- | ---- |--------------------------| +| startMargin | [Dimension](ts-types.md#dimension10) | 否 | 分割线与其上方子组件的距离。
默认值:0 | +| endMargin | [Dimension](ts-types.md#dimension10) | 否 | 分割线与其下方子组件的距离。
默认值:0 | > **说明:** > -> 与RowSplit相同,ColumnSplit的分割线最小能拖动到刚好包含子组件。 -> -> 在真机中查看拖动效果,预览器中不支持拖动。 +> 与RowSplit相同,ColumnSplit的分割线可以改变上下两边子组件的高度,子组件可改变高度的范围取决于子组件的最大最小高度。 > -> 不支持clip、margin通用属性。 +> 支持clip、margin等通用属性,clip不设置的时候默认值为true。 + ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md index 3f6168527652f0cf646b72f836ca0632c468a67c..90a3114eb96433f17a70daafa229b06ee5e16e1d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md @@ -45,8 +45,8 @@ Grid(scroller?: Scroller) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| columnsTemplate | string | 设置当前网格布局列的数量,不设置时默认1列。
例如, '1fr 1fr 2fr' 是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。
**说明:**
设置为'0fr'时,该列的列宽为0,不显示GridItem。设置为其他非法值时,GridItem显示为固定1列。 | -| rowsTemplate | string | 设置当前网格布局行的数量,不设置时默认1行。
例如, '1fr 1fr 2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。
**说明:**
设置为'0fr',则这一行的行宽为0,这一行GridItem不显示。设置为其他非法值,按固定1行处理。 | +| columnsTemplate | string | 设置当前网格布局列的数量或最小列宽值,不设置时默认1列。
例如, '1fr 1fr 2fr' 是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。
‘repeat(auto-fit, 90px)’是设置最小列宽值为90,自动计算列数和实际列宽。
**说明:**
设置为'0fr'时,该列的列宽为0,不显示GridItem。设置为其他非法值时,GridItem显示为固定1列。 | +| rowsTemplate | string | 设置当前网格布局行的数量或最小行高值,不设置时默认1行。
例如, '1fr 1fr 2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。
‘repeat(auto-fit, 90px)’是设置最小行高值为90,自动计算行数和实际行高。
**说明:**
设置为'0fr',则这一行的行宽为0,这一行GridItem不显示。设置为其他非法值,按固定1行处理。 | | columnsGap | [Length](ts-types.md#length) | 设置列与列的间距。
默认值:0
**说明:**
设置为小于0的值时,按默认值显示。 | | rowsGap | [Length](ts-types.md#length) | 设置行与行的间距。
默认值:0
**说明:**
设置为小于0的值时,按默认值显示。 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off
**说明:**
API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 | @@ -55,8 +55,8 @@ Grid(scroller?: Scroller) | cachedCount | number | 设置预加载的GridItem的数量,只在[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)中生效。具体使用可参考[减少应用白块说明](../../ui/arkts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1
**说明:**
设置缓存后会在Grid显示区域上下各缓存cachedCount*列数个GridItem。
[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)超出显示和缓存范围的GridItem会被释放。
设置为小于0的值时,按默认值显示。 | | editMode 8+ | boolean | 设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部[GridItem](ts-container-griditem.md)。
默认值:flase | | layoutDirection8+ | [GridDirection](#griddirection8枚举说明) | 设置布局的主轴方向。
默认值:GridDirection.Row | -| maxCount8+ | number | 当layoutDirection是Row/RowReverse时,表示可显示的最大列数
当layoutDirection是Column/ColumnReverse时,表示可显示的最大行数。
默认值:Infinity
**说明:**
当maxCount小于minCount时,maxCount和minCount都按默认值处理。
设置为小于0的值时,按默认值显示。 | -| minCount8+ | number | 当layoutDirection是Row/RowReverse时,表示可显示的最小列数。
当layoutDirection是Column/ColumnReverse时,表示可显示的最小行数。
默认值:1
**说明:**
设置为小于0的值时,按默认值显示。 | +| maxCount8+ | number | 当layoutDirection是Row/RowReverse时,表示可显示的最大列数
当layoutDirection是Column/ColumnReverse时,表示可显示的最大行数。
默认值:Infinity
**说明:**
当maxCount小于minCount时,maxCount和minCount都按默认值处理。
设置为小于1的值时,按默认值显示。 | +| minCount8+ | number | 当layoutDirection是Row/RowReverse时,表示可显示的最小列数。
当layoutDirection是Column/ColumnReverse时,表示可显示的最小行数。
默认值:1
**说明:**
设置为小于1的值时,按默认值显示。 | | cellLength8+ | number | 当layoutDirection是Row/RowReverse时,表示一行的高度。
当layoutDirection是Column/ColumnReverse时,表示一列的宽度。
默认值:第一个元素的大小 | | multiSelectable8+ | boolean | 是否开启鼠标框选。
默认值:false
- false:关闭框选。
- true:开启框选。 | | supportAnimation8+ | boolean | 是否支持动画。当前支持GridItem拖拽动画。
默认值:false | @@ -111,7 +111,7 @@ Grid组件根据rowsTemplate、columnsTemplate属性的设置情况,可分为 | 名称 | 功能描述 | | -------- | -------- | | onScrollIndex(event: (first: number) => void) | 当前网格显示的起始位置item发生变化时触发。列表初始化时会触发一次。
- first: 当前显示的网格起始位置的索引值。
Grid显示区域上第一个子组件的索引值有变化就会触发。 | -| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | 开始拖拽网格元素时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。
- itemIndex: 被拖拽网格元素索引值。
**说明:**
返回void表示不能拖拽。
手指长按GridItem时触发该事件。 | +| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | 开始拖拽网格元素时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。
- itemIndex: 被拖拽网格元素索引值。
**说明:**
返回void表示不能拖拽。
手指长按GridItem时触发该事件。
由于拖拽检测也需要长按,且事件处理机制优先触发子组件事件,GridItem上绑定LongPressGesture时无法触发拖拽;如有长按和拖拽同时使用的需求可以使用通用拖拽事件。 | | onItemDragEnter(event: (event: ItemDragInfo) => void) | 拖拽进入网格元素范围内时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。 | | onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | 拖拽在网格元素范围内移动时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。
- itemIndex: 拖拽起始位置。
- insertIndex: 拖拽插入位置。 | | onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | 拖拽离开网格元素时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。
- itemIndex: 拖拽离开的网格元素索引值。 | @@ -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) @@ -277,6 +278,10 @@ struct GridExample { return this.pixelMapBuilder() //设置拖拽过程中显示的图片。 }) .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。 + // isSuccess=false时,说明drop的位置在grid外部;insertIndex > length时,说明有新增元素的事件发生 + if (!isSuccess || insertIndex >= this.numbers.length) { + return + } console.info('beixiang' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置 this.changeIndex(itemIndex, insertIndex) }) @@ -285,3 +290,16 @@ struct GridExample { } ``` +示例图: + +网格子组件开始拖拽: + +![gridDrag](figures/gridDrag.png) + +网格子组件拖拽过程中: + +![gridDrag](figures/gridDrag1.png) + +网格子组件1与子组件6拖拽交换位置后: + +![gridDrag](figures/gridDrag2.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-hyperlink.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-hyperlink.md new file mode 100644 index 0000000000000000000000000000000000000000..e1d7e030df59cb943de20dfb7224c71e616d8cef --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-hyperlink.md @@ -0,0 +1,66 @@ +# Hyperlink + +超链接组件,组件宽高范围内点击实现跳转。 + +> **说明:** +> +> - 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> - 该组件仅支持与系统浏览器配合使用。 + +## 需要权限 + +使用网络时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[权限申请声明](../../security/accesstoken-guidelines.md)。 + +## 子组件 + +可以包含子组件。 + + +## 接口 + +Hyperlink(address: string | Resource, content?: string | Resource) + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| address | string \| [Resource](ts-types.md#resource) | 是 | Hyperlink组件跳转的网页。 | +| content | string \| [Resource](ts-types.md#resource) | 否 | Hyperlink组件中超链接显示文本。
**说明:**
组件内有子组件时,不显示超链接文本。 | + +## 属性 + +仅支持以下属性: + +| 名称 | 参数类型 | 描述 | +| -------- | -------- | -------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | 设置超链接文本的颜色。 | + +## 示例 + +```ts +@Entry +@Component +struct HyperlinkExample { + build() { + Column() { + Column() { + Hyperlink('https://example.com/') { + Image($r('app.media.bg')) + .width(200) + .height(100) + } + } + + Column() { + Hyperlink('https://example.com/', 'Go to the developer website') { + } + .color(Color.Blue) + } + }.width('100%').height('100%').justifyContent(FlexAlign.Center) + } +} +``` + +![hyperlink](figures/hyperlink.PNG) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md index 1dcc034d37b1b63053f7b920ca846e770d81fe5a..53eb14cc12ee414e3ee96525fa34627199d6ad4e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md @@ -60,7 +60,7 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? | chainAnimation | boolean | 设置当前List是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:List内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。
默认值:false
- false:不启用链式联动。
- true:启用链式联动。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
链式动效生效后,List的分割线不显示。
链式动效生效需要满足以下前提条件:
-  List边缘效果为Spring类型
-  List没有启用多列模式 | | chainAnimationOptions10+ | [ChainAnimationOptions](#chainanimationoptions10对象说明) | 设置链式联动动效参数。
**系统API:** 此接口为系统接口。 | | multiSelectable8+ | boolean | 是否开启鼠标框选。
默认值:false
- false:关闭框选。
- true:开启框选。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain),
gutter10+?:[Dimension](ts-types.md#dimension) | 以列模式为例(listDirection为Axis.Vertical):
lanes用于决定List组件在交叉轴方向按几列布局。
默认值:1
规则如下:
- lanes为指定的数量时,根据指定的数量与List组件的交叉轴尺寸除以列数作为列的宽度。
- lanes设置了{minLength,maxLength}时,根据List组件的宽度自适应决定lanes数量(即列数),保证缩放过程中lane的宽度符合{minLength,maxLength}的限制。其中,minLength条件会被优先满足,即优先保证符合ListItem的交叉轴尺寸符合最小限制。
- lanes设置了{minLength,maxLength},如果父组件交叉轴方向尺寸约束为无穷大时,固定按一列排列,列宽度按显示区域内最大的ListItem计算
- ListItemGroup在多列模式下也是独占一行,ListItemGroup中的ListItem按照List组件的lanes属性设置值来布局。
- lanes设置了{minLength,maxLength}时,计算列数会按照ListItemGroup的交叉轴尺寸计算。当ListItemGroup交叉轴尺寸与List交叉轴尺寸不一致时ListItemGroup中的列数与List中的列数可能不一样。
gutter为列间距,当列数大于1时生效。
该接口支持在ArkTS卡片中使用。 | +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain),
gutter10+?:[Dimension](ts-types.md#dimension) | 以列模式为例(listDirection为Axis.Vertical):
lanes用于决定List组件在交叉轴方向按几列布局。
默认值:1
规则如下:
- lanes为指定的数量时,根据指定的数量与List组件的交叉轴尺寸除以列数作为列的宽度。
- lanes设置了{minLength,maxLength}时,根据List组件的宽度自适应决定lanes数量(即列数),保证缩放过程中lane的宽度符合{minLength,maxLength}的限制。其中,minLength条件会被优先满足,即优先保证符合ListItem的交叉轴尺寸符合最小限制。
- lanes设置了{minLength,maxLength},如果父组件交叉轴方向尺寸约束为无穷大时,固定按一列排列,列宽度按显示区域内最大的ListItem计算
- ListItemGroup在多列模式下也是独占一行,ListItemGroup中的ListItem按照List组件的lanes属性设置值来布局。
- lanes设置了{minLength,maxLength}时,计算列数会按照ListItemGroup的交叉轴尺寸计算。当ListItemGroup交叉轴尺寸与List交叉轴尺寸不一致时ListItemGroup中的列数与List中的列数可能不一样。
gutter为列间距,当列数大于1时生效。
默认值为 0
该接口支持在ArkTS卡片中使用。 | | alignListItem9+ | [ListItemAlign](#listitemalign9枚举说明) | List交叉轴方向宽度大于ListItem交叉轴宽度 * lanes时,ListItem在List交叉轴方向的布局方式,默认为首部对齐。
默认值:ListItemAlign.Start
该接口支持在ArkTS卡片中使用。 | | sticky9+ | [StickyStyle](#stickystyle9枚举说明) | 配合[ListItemGroup](ts-container-listitemgroup.md)组件使用,设置ListItemGroup中header和footer是否要吸顶或吸底。
默认值:StickyStyle.None
该接口支持在ArkTS卡片中使用。
**说明:**
sticky属性可以设置为 StickyStyle.Header \| StickyStyle.Footer 以同时支持header吸顶和footer吸底。 | | scrollSnapAlign10+ | [ScrollSnapAlign](#scrollsnapalign10枚举说明) | 设置列表项滚动结束对齐效果。
默认值:ScrollSnapAlign.NONE
**说明:**
只支持ListItem等高情况下,设置列表项滚动结束对齐效果。 | 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 dad048801feaee9e44ff1c72afcf50c1d77928e6..78cb06ee049134bc9fd87a72a02fc1af3db7e37d 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 @@ -73,12 +73,11 @@ List垂直布局,ListItem向右滑动,item左边的长距离滑动删除选 | 名称 | 参数类型 | 必填 | 描述 | | -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| deleteAreaDistance | [Length](ts-types.md#length) | 否 | 设置组件长距离滑动删除距离阈值。
默认值:56vp
**说明:**
不支持设置百分比。
删除距离阈值大于item宽度减去划出组件宽度,或删除距离阈值小于等于0就不会设置删除区域。| -| onDelete | () => void | 否 | 组件进入长距删除区后删除ListItem时调用,进入长距删除区后抬手时触发。
**说明:**
滑动后松手的位置超过或等于设置的距离阈值,并且设置的距离阈值有效时才会触发。| -| onEntryDeleteArea | () => void | 否 | 在滑动条目进入删除区域时调用,只触发一次,当再次进入时仍触发。 | -| onExitDeleteArea | () => void | 否 |当滑动条目退出删除区域时调用,只触发一次,当再次退出时仍触发。 | +| actionAreaDistance | [Length](ts-types.md#length) | 否 | 设置组件长距离滑动删除距离阈值。
默认值:56vp
**说明:**
不支持设置百分比。
删除距离阈值大于item宽度减去划出组件宽度,或删除距离阈值小于等于0就不会设置删除区域。| +| onAction | () => void | 否 | 组件进入长距删除区后删除ListItem时调用,进入长距删除区后抬手时触发。
**说明:**
滑动后松手的位置超过或等于设置的距离阈值,并且设置的距离阈值有效时才会触发。| +| onEnterActionArea | () => void | 否 | 在滑动条目进入删除区域时调用,只触发一次,当再次进入时仍触发。 | +| onExitActionArea | () => void | 否 |当滑动条目退出删除区域时调用,只触发一次,当再次退出时仍触发。 | | builder | CustomBuilder | 否 |当列表项向右或向右滑动(当列表方向为“垂直”时),向下或向下滑动(当列方向为“水平”时)时显示的操作项。 | -| useDefaultDeleteAnimation | boolean | 否 |设置是否使用默认的删除动画。
默认值:true | ## ListItemOptions10+对象说明 | 名称 | 参数类型 | 必填 | 描述 | @@ -193,3 +192,42 @@ struct ListItemExample2 { } ``` ![deleteListItem](figures/deleteListItem.gif) + +## 示例3 +```ts +// xxx.ets +@Entry +@Component +struct ListItemExample3 { + private arr: any = [ListItemStyle.CARD, ListItemStyle.CARD,ListItemStyle.NONE] + build() { + Column() { + List({ space: "4vp", initialIndex: 0 }) { + ListItemGroup({style:ListItemGroupStyle.CARD}){ + ForEach(this.arr, (itemStyle,index) => { + ListItem({style:itemStyle}) { + Text(""+index) + .width("100%") + .textAlign(TextAlign.Center) + } + }) + } + ForEach(this.arr, (itemStyle,index) => { + ListItem({style:itemStyle}) { + Text(""+index) + .width("100%") + .textAlign(TextAlign.Center) + } + }) + } + .width('100%') + .multiSelectable(true) + .backgroundColor(0xDCDCDC) // 浅蓝色的List + } + .width('100%') + .padding({ top: 5 }) + } +} + +``` +![ListItemStyle](figures/listItem3.jpeg) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md index 63692a39a290c7d321962254ae4176c49cc45528..dedf78ea7e1ca835a65c4167fb92f7a7c193aadf 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md @@ -10,7 +10,7 @@ 当ListItemGroup的父组件List的listDirection属性为Axis.Vertical时,不允许设置ListItemGroup组件的height属性。ListItemGroup的高度为header高度、footer高度和所有ListItem布局后总高度之和。当父组件List的listDirection属性为Axis.Horizontal时,不允许设置ListItemGroup组件的width属性。ListItemGroup的宽度为header宽度、footer宽度和所有ListItem布局后总宽度之和。 -当前ListItemGroup内部的ListItem组件不支持编辑、框选、拖拽功能,即ListItem组件的editable、selectable属性不生效。 +当前ListItemGroup内部的ListItem组件不支持编辑、拖拽功能,即ListItem组件的editable属性不生效。 ## 子组件 @@ -119,3 +119,55 @@ struct ListItemGroupExample { ``` ![zh-cn_image_0000001219864159](figures/zh-cn_image_listitemgroup.gif) + +- 示例2 + +```ts +// xxx.ets +@Entry +@Component +struct ListItemGroupExample2 { + private arr: any = [ + { + style:ListItemGroupStyle.CARD, + itemStyles:[ListItemStyle.CARD, ListItemStyle.CARD, ListItemStyle.CARD] + }, + { + style:ListItemGroupStyle.CARD, + itemStyles:[ListItemStyle.CARD, ListItemStyle.CARD, ListItemStyle.NONE] + }, + { + style:ListItemGroupStyle.CARD, + itemStyles:[ListItemStyle.CARD, ListItemStyle.NONE, ListItemStyle.CARD] + }, + { + style:ListItemGroupStyle.NONE, + itemStyles:[ListItemStyle.CARD, ListItemStyle.CARD, ListItemStyle.NONE] + } + ] + build() { + Column() { + List({ space: "4vp", initialIndex: 0 }) { + ForEach(this.arr, (item,index) => { + ListItemGroup({ style:item.style }) { + ForEach(item.itemStyles, (itemStyle,itemIndex) => { + ListItem({style:itemStyle}) { + Text("第"+(index+1)+"个Group中第"+(itemIndex+1)+"个item") + .width("100%") + .textAlign(TextAlign.Center) + } + }, item => item) + } + }) + } + .width('100%') + .multiSelectable(true) + .backgroundColor(0xDCDCDC) // 浅蓝色的List + } + .width('100%') + .padding({ top: 5 }) + } +} + +``` +![ListItemGroupStyle](figures/listItemGroup2.jpeg) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md index 35e7c2907c15ecee2803b71db4e8976e8135bcb6..d083259a697017d653ce839ded28ac08453d74ee 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md @@ -23,11 +23,9 @@ RowSplit() > **说明:** > -> RowSplit的分割线最小能拖动到刚好包含子组件。 -> -> 在真机中查看拖动效果,预览器中不支持拖动。 +> RowSplit的分割线可以改变左右两边子组件的宽度,子组件可改变宽度的范围取决于子组件的最大最小宽度。 > -> 不支持clip、margin通用属性。 +> 支持clip、margin等通用属性,clip不设置的时候默认值为true。 ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index a05a1cfbacd7f25135ac8d25ade930de41758ed8..729d55db9a1e91fd7f743a1dd2d34bc27a554a50 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -83,7 +83,7 @@ SideBarContainer( type?: SideBarContainerType ) > 针对侧边栏子组件设置[通用属性宽高](ts-universal-attributes-size.md)时,宽高都不生效。 > 针对侧边栏内容区设置[通用属性宽高](ts-universal-attributes-size.md)时,宽高都不生效,默认占满SideBarContainer的剩余空间。 > -> 当属性方法未设置时,依据组件大小进行自动显示: +> 当showSideBar属性未设置时,依据组件大小进行自动显示: > > - 小于520vp:默认不显示侧边栏。 > - 大于等于520vp:默认显示侧边栏。 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 186874cd732573ee91fa0f5e283e74f379f2933d..3735108a93820e37f711e00e867a5bdbe7b00934 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 @@ -50,7 +50,7 @@ Swiper(controller?: SwiperController) | disableSwipe8+ | boolean | 禁用组件滑动切换功能。
默认值:false | | curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | 设置Swiper的动画曲线,默认为淡入淡出曲线,常用曲线参考[Curve枚举说明](ts-appendix-enums.md#curve),也可以通过[插值计算](../apis/js-apis-curve.md)模块提供的接口创建自定义的插值曲线对象。
默认值: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)
} | 设置导航点样式:
\- left: 设置导航点距离Swiper组件左边的距离。
\- top: 设置导航点距离Swiper组件顶部的距离。
\- right: 设置导航点距离Swiper组件右边的距离。
\- bottom: 设置导航点距离Swiper组件底部的距离。
\- size: 设置导航点的直径,不支持设置百分比。默认值:6vp。
\- mask: 设置是否显示导航点蒙层样式。
\- color: 设置导航点的颜色。
\- selectedColor: 设置选中的导航点的颜色。
从API version 8开始支持,从API version 10开始不再维护,建议使用[indicator](#indicator10对象说明)代替。 | -| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | 设置一页内元素显示个数。
默认值:1
**说明:**
字符串类型仅支持设置为'auto',显示效果同SwiperDisplayMode.AutoLinear。
使用number类型且设置小于等于0时,按默认值1显示。
使用number类型时,子组件按照主轴均分Swiper宽度(减去displayCount-1的itemSpace)的方式进行主轴拉伸(收缩)布局。
使用SwiperAutoFill类型时,通过设置一个子组件最小宽度值minSize,会根据Swiper当前宽度和minSize值自动计算并更改一页内元素显示个数。当minSize为空或者小于等于0时,Swiper显示1列。 | +| displayCount8+ | number \| string \|
[SwiperAutoFill](#swiperautofill10)10+ | 设置一页内元素显示个数。
默认值:1
**说明:**
字符串类型仅支持设置为'auto',显示效果同SwiperDisplayMode.AutoLinear。
使用number类型且设置小于等于0时,按默认值1显示。
使用number类型时,子组件按照主轴均分Swiper宽度(减去displayCount-1个itemSpace)的方式进行主轴拉伸(收缩)布局。
使用SwiperAutoFill类型时,通过设置一个子组件最小宽度值minSize,会根据Swiper当前宽度和minSize值自动计算并更改一页内元素显示个数。当minSize为空或者小于等于0时,Swiper显示1列。 | | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。
默认值:EdgeEffect.Spring
**说明:**
控制器接口调用时不生效回弹。 | | displayArrow10+ | value:[ArrowStyle](#arrowstyle10) \| boolean,
isHoverShow?: boolean | 设置导航点箭头样式。
-value: 支持设置箭头和底板样式,异常场景使用ArrowStyle对象中的默认值。
\-isHoverShow:设置鼠标悬停时是否显示箭头。
默认值:false
**说明:**
isHoverShow为false时,常驻显示箭头,支持点击翻页。
isHoverShow为true时,只有在鼠标悬停时才会显示箭头,并支持点击翻页。 | | nextMargin10+ |
[Length](ts-types.md#length)
| 后边距,用于露出后一项的一小部分。
默认值:0
**说明:**
仅当SwiperDisplayMode为STRETCH模式时生效。
当主轴方向为横向布局时,nextmargin/prevmargin中任意一个大于子组件测算的宽度,nextmargin和prevmargin均不显示。
当主轴方向为纵向布局时,nextmargin/prevmargin中任意一个大于子组件测算的高度,nextmargin和prevmargin均不显示。 | 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 40a59a001dbd68ceebc9086c87ea4bf36348c9f0..9cfb9370daadf9a476edd194670a93a6bfa9b9fd 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 @@ -74,7 +74,7 @@ SubTabBarStyle的静态构造函数。 | indicator10+ | [IndicatorStyle](#indicatorstyle10对象说明)| 设置选中子页签的下划线风格。子页签的下划线风格仅在水平模式下有效。
| | selectedMode10+ | [SelectedMode](#selectedmode10枚举说明) | 设置选中子页签的显示方式。
默认值:SelectedMode.INDICATOR | | board10+ | [BoardStyle](#boardstyle10对象说明) | 设置选中子页签的背板风格。 | -| labelStyle10+ | [LabelStyle](#labelstyle10对象说明) | 设置选中子页签的label文本和字体的样式。 | +| labelStyle10+ | [LabelStyle](#labelstyle10对象说明) | 设置子页签的label文本和字体的样式。 | ## IndicatorStyle10+对象说明 @@ -399,3 +399,290 @@ struct TabBarStyleExample { ``` ![tabbarStyle](figures/TabBarStyle.jpeg) + +示例4: + +```ts +// xxx.ets +@Entry +@Component +struct TabsAttr { + private controller: TabsController = new TabsController() + @State indicatorColor: Color = Color.Blue; + @State indicatorWidth: number = 40; + @State indicatorHeight: number = 10; + @State indicatorBorderRadius: number = 5; + @State indicatorSpace: number = 10; + @State subTabBorderRadius: number = 20; + @State selectedMode: SelectedMode = SelectedMode.INDICATOR; + private colorFlag: boolean = true; + private widthFlag: boolean = true; + private heightFlag: boolean = true; + private borderFlag: boolean = true; + private spaceFlag: boolean = true; + build() { + Column() { + Button("下划线颜色变化").width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + // 对Button组件的宽高属性进行动画配置 + if (this.colorFlag) { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorColor = Color.Red + }) + } else { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorColor = Color.Yellow + }) + } + this.colorFlag = !this.colorFlag + }) + Button("下划线高度变化").width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + // 对Button组件的宽高属性进行动画配置 + if (this.heightFlag) { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorHeight = 20 + }) + } else { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorHeight = 10 + }) + } + this.heightFlag = !this.heightFlag + }) + Button("下划线宽度变化").width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + // 对Button组件的宽高属性进行动画配置 + if (this.widthFlag) { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorWidth = 30 + }) + } else { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorWidth = 50 + }) + } + this.widthFlag = !this.widthFlag + }) + Button("下划线圆角半径变化").width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + // 对Button组件的宽高属性进行动画配置 + if (this.borderFlag) { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorBorderRadius = 0 + }) + } else { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorBorderRadius = 5 + }) + } + this.borderFlag = !this.borderFlag + }) + Button("下划线间距变化").width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + // 对Button组件的宽高属性进行动画配置 + if (this.spaceFlag) { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorSpace = 20 + }) + } else { + animateTo({ + duration: 1000, // 动画时长 + curve: Curve.Linear, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal, // 动画模式 + onFinish: () => { + console.info('play end') + } + }, () => { + this.indicatorSpace = 10 + }) + } + this.spaceFlag = !this.spaceFlag + }) + Tabs({ barPosition: BarPosition.End, controller: this.controller }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink).borderRadius('12vp') + }.tabBar(SubTabBarStyle.of('pink') + .indicator({ + color: this.indicatorColor, //下划线颜色 + height: this.indicatorHeight, //下划线高度 + width: this.indicatorWidth, //下划线宽度 + borderRadius: this.indicatorBorderRadius, //下划线圆角半径 + marginTop: this.indicatorSpace //下划线与文字间距 + }) + .selectedMode(this.selectedMode) + .board({ borderRadius: this.subTabBorderRadius }) + .labelStyle({}) + ) + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow).borderRadius('12vp') + }.tabBar('yellow') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue).borderRadius('12vp') + }.tabBar('blue') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green).borderRadius('12vp') + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Gray).borderRadius('12vp') + }.tabBar('gray') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Orange).borderRadius('12vp') + }.tabBar('orange') + } + .vertical(false).scrollable(true) + .barMode(BarMode.Scrollable) + .barHeight(140).animationDuration(400) + .onChange((index: number) => { + console.info(index.toString()) + }) + .backgroundColor(0xF5F5F5).height(320) + }.width('100%').height(250).padding({top: '24vp', left: '24vp', right: '24vp'}) + } +} +``` + +![tabContent3](figures/tabContent3.gif) + +示例5: + +```ts +// xxx.ets +@Entry +@Component +struct TabsTextOverflow { + @State message: string = 'Hello World' + private controller: TabsController = new TabsController() + @State subTabOverflowOpaque: boolean = true; + build() { + Column() { + Tabs({ barPosition: BarPosition.Start, controller: this.controller }) { + TabContent() { + Column(){ + Text('单行省略号截断').fontSize(30).fontColor(0xFF000000) + }.width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(SubTabBarStyle.of('开始【单行省略号截断单行省略号截断单行省略号截断单行省略号截断单行省略号截断单行省略号截断单行省略号截断单行省略号截断单行省略号截断单行省略号截断】结束') + .labelStyle({ overflow: TextOverflow.Ellipsis, maxLines: 1, minFontSize: 10, heightAdaptivePolicy: TextHeightAdaptivePolicy.MAX_LINES_FIRST, + font: { size: 20 } })) + TabContent() { + Column() + { + Text('先缩小再截断').fontSize(30).fontColor(0xFF000000) + }.width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(SubTabBarStyle.of('开始【先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断先缩小再截断】结束') + .labelStyle({ overflow: TextOverflow.Clip, maxLines: 1, minFontSize: 15, maxFontSize: 15, heightAdaptivePolicy: TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST, + font: { size: 20 } })) + TabContent() { + Column(){ + Text('先缩小再换行再截断').fontSize(30).fontColor(0xFF000000) + }.width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(SubTabBarStyle.of('开始【先缩小再换行再截断先缩小再换行再截断先缩小再换行再截断先缩小再换行再截断先缩小再换行再截断先缩小再换行再截断先缩小再换行再截断先缩小再换行再截断】结束') + .labelStyle({ overflow: TextOverflow.Clip, maxLines: 2, minFontSize: 15, maxFontSize: 15, heightAdaptivePolicy: TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST, + font: { size: 20 } })) + TabContent() { + Column() { + Text('换行').fontSize(30).fontColor(0xFF000000) + } + .width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(SubTabBarStyle.of('开始【换行换行换行换行换行换行换行换行换行换行换行换行换行换行换行】结束') + .labelStyle({ overflow: TextOverflow.Clip, maxLines: 10, minFontSize: 10, heightAdaptivePolicy: TextHeightAdaptivePolicy.MAX_LINES_FIRST, + font: { size: 20 } })) + } + .vertical(true).scrollable(true) + .barMode(BarMode.Fixed) + .barHeight(720) + .barWidth(200).animationDuration(400) + .onChange((index: number) => { + console.info(index.toString()) + }) + .height('100%').width('100%') + } + .height('100%') + } +} +``` + +![tabContent4](figures/tabContent4.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md index f6043af0d2353d3396b947403af537f83446b257..f1c4f5d7121cdc140850dcdd5b3d80d7b559275f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -18,11 +18,11 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| ----------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| barPosition | BarPosition | 否 | 设置Tabs的页签位置。
默认值:BarPosition.Start | -| index | number | 否 | 设置初始页签索引。
默认值:0
**说明:**
设置为小于0的值时按默认值显示。
可选值为[0, TabContent子节点数量-1]。
设置不同值时,默认生效切换动效,可以设置animationDuration为0关闭动画。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 | -| controller | [TabsController](#tabscontroller) | 否 | 设置Tabs控制器。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ----------- | --------------------------------- | ---- | ---------------------------------------- | +| barPosition | BarPosition | 否 | 设置Tabs的页签位置。
默认值:BarPosition.Start | +| index | number | 否 | 设置初始页签索引。
默认值:0
**说明:**
设置为小于0的值时按默认值显示。
可选值为[0, TabContent子节点数量-1]。
设置不同值时,默认生效切换动效,可以设置animationDuration为0关闭动画。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 | +| controller | [TabsController](#tabscontroller) | 否 | 设置Tabs控制器。 | ## BarPosition枚举说明 @@ -36,25 +36,25 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 名称 | 参数类型 | 描述 | -| ------------------------ | ---------------------------------------- | ---------------------------------------- | -| vertical | boolean | 设置为false是为横向Tabs,设置为true时为纵向Tabs。
默认值:false | -| scrollable | boolean | 设置为true时可以通过滑动页面进行页面切换,为false时不可滑动切换页面。
默认值:true | -| barMode | BarMode | TabBar布局模式,具体描述见BarMode枚举说明。
默认值:BarMode.Fixed | -| barWidth | number \| Length8+ | TabBar的宽度值。
默认值:
未设置带样式的TabBar且vertical属性为false时,默认值为Tabs的宽度。
未设置带样式的TabBar且vertical属性为true时,默认值为56vp。
设置SubTabbarStyle样式且vertical属性为false时,默认值为Tabs的宽度。
设置SubTabbarStyle样式且vertical属性为true时,默认值为56vp。
设置BottomTabbarStyle样式且vertical属性为true时,默认值为96vp。
设置BottomTabbarStyle样式且vertical属性为false时,默认值为Tabs的宽度。
**说明:**
设置为小于0或大于Tabs宽度值时,按默认值显示。 | -| barHeight | number \| Length8+ | TabBar的高度值。
默认值:
未设置带样式的TabBar且vertical属性为false时,默认值为56vp。
未设置带样式的TabBar且vertical属性为true时,默认值为Tabs的高度。
设置SubTabbarStyle样式且vertical属性为false时,默认值为56vp。
设置SubTabbarStyle样式且vertical属性为true时,默认值为Tabs的高度。
设置BottomTabbarStyle样式且vertical属性为true时,默认值为Tabs的高度。
设置BottomTabbarStyle样式且vertical属性为false时,默认值为56vp。
**说明:**
设置为小于0或大于Tabs高度值时,按默认值显示。| -| animationDuration | number | TabContent滑动动画时长。不设置时,点击切换页签无动画,滑动切换有动画;设置时,点击切换和滑动切换都有动画。
默认值:300
**说明:**
设置为小于0或百分比时,按默认值显示。 | -| divider10+ | [DividerStyle](#dividerstyle10对象说明) \| null | 用于设置区分TabBar和TabContent的分割线样式设置分割线样式,默认不显示分割线。
DividerStyle: 分割线的样式;
null: 不显示分割线。 | -| fadingEdge10+ | boolean | 设置页签超过容器宽度时是否渐隐消失。
默认值:true | -| barOverlap10+ | boolean | 设置TabBar是否背后变模糊并叠加在TabContent之上。
默认值:false | -| barBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置TabBar的背景颜色。
默认值:透明| +| 名称 | 参数类型 | 描述 | +| -------------------------------- | ---------------------------------------- | ---------------------------------------- | +| vertical | boolean | 设置为false是为横向Tabs,设置为true时为纵向Tabs。
默认值:false | +| scrollable | boolean | 设置为true时可以通过滑动页面进行页面切换,为false时不可滑动切换页面。
默认值:true | +| barMode | BarMode | TabBar布局模式,具体描述见BarMode枚举说明。
默认值:BarMode.Fixed | +| barWidth | number \| Length8+ | TabBar的宽度值。
默认值:
未设置带样式的TabBar且vertical属性为false时,默认值为Tabs的宽度。
未设置带样式的TabBar且vertical属性为true时,默认值为56vp。
设置SubTabbarStyle样式且vertical属性为false时,默认值为Tabs的宽度。
设置SubTabbarStyle样式且vertical属性为true时,默认值为56vp。
设置BottomTabbarStyle样式且vertical属性为true时,默认值为96vp。
设置BottomTabbarStyle样式且vertical属性为false时,默认值为Tabs的宽度。
**说明:**
设置为小于0或大于Tabs宽度值时,按默认值显示。 | +| barHeight | number \| Length8+ | TabBar的高度值。
默认值:
未设置带样式的TabBar且vertical属性为false时,默认值为56vp。
未设置带样式的TabBar且vertical属性为true时,默认值为Tabs的高度。
设置SubTabbarStyle样式且vertical属性为false时,默认值为56vp。
设置SubTabbarStyle样式且vertical属性为true时,默认值为Tabs的高度。
设置BottomTabbarStyle样式且vertical属性为true时,默认值为Tabs的高度。
设置BottomTabbarStyle样式且vertical属性为false时,默认值为56vp。
**说明:**
设置为小于0或大于Tabs高度值时,按默认值显示。 | +| animationDuration | number | TabContent滑动动画时长。不设置时,点击切换页签无动画,滑动切换有动画;设置时,点击切换和滑动切换都有动画。
默认值:300
**说明:**
设置为小于0或百分比时,按默认值显示。 | +| divider10+ | [DividerStyle](#dividerstyle10对象说明) \| null | 用于设置区分TabBar和TabContent的分割线样式设置分割线样式,默认不显示分割线。
DividerStyle: 分割线的样式;
null: 不显示分割线。 | +| fadingEdge10+ | boolean | 设置页签超过容器宽度时是否渐隐消失。
默认值:true | +| barOverlap10+ | boolean | 设置TabBar是否背后变模糊并叠加在TabContent之上。
默认值:false | +| barBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置TabBar的背景颜色。
默认值:透明 | ## DividerStyle10+对象说明 -| 名称 | 参数类型 | 必填 | 描述 | -| ----------- | ---------------------------------------- | ---- | ----------------------------------- | -| strokeWidth | [Length](ts-types.md#length) | 是 | 分割线的线宽(不支持百分比设置)。 | -| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 分割线的颜色。
默认值:#33182431 | +| 名称 | 参数类型 | 必填 | 描述 | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| strokeWidth | [Length](ts-types.md#length) | 是 | 分割线的线宽(不支持百分比设置)。 | +| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 分割线的颜色。
默认值:#33182431 | | startMargin | [Length](ts-types.md#length) | 否 | 分割线与侧边栏顶端的距离(不支持百分比设置)。
默认值:0.0
单位:vp | | endMargin | [Length](ts-types.md#length) | 否 | 分割线与侧边栏底端的距离(不支持百分比设置)。
默认值:0.0
单位:vp | @@ -98,6 +98,8 @@ changeIndex(value: number): void ## 示例 +### 示例1 + ```ts // xxx.ets @Entry @@ -159,4 +161,264 @@ struct TabsExample { } ``` -![tabs2](figures/tabs2.gif) \ No newline at end of file +![tabs2](figures/tabs2.gif) + +### 示例2 + +```ts +// xxx.ets +@Entry +@Component +struct TabsDivider1 { + private controller1: TabsController = new TabsController() + @State dividerColor: string = 'red' + @State strokeWidth: number = 2 + @State startMargin: number = 0 + @State endMargin: number = 0 + @State nullFlag: boolean = false + + build() { + Column() { + Tabs({ controller: this.controller1 }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar('pink') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow) + }.tabBar('yellow') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + }.tabBar('blue') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Red) + }.tabBar('red') + } + .vertical(true) + .scrollable(true) + .barMode(BarMode.Fixed) + .barWidth(70) + .barHeight(200) + .animationDuration(400) + .onChange((index: number) => { + console.info(index.toString()) + }) + .height('200vp') + .margin({bottom: '12vp'}) + .divider(this.nullFlag ? null :{ + strokeWidth: this.strokeWidth, + color: this.dividerColor, + startMargin: this.startMargin, + endMargin: this.endMargin + }) + + Button('常规Divider').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + this.nullFlag = false, + this.strokeWidth = 2, + this.dividerColor = 'red', + this.startMargin = 0, + this.endMargin = 0 + }) + Button('空Divider').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + this.nullFlag = true + }) + Button('颜色变为蓝色').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + this.dividerColor = 'blue' + }) + Button('宽度增加').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + this.strokeWidth += 2 + }) + Button('宽度减小').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + if(this.strokeWidth > 2) { + this.strokeWidth -= 2 + } + }) + Button('上边距增加').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + this.startMargin += 2 + }) + Button('上边距减少').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + if (this.startMargin > 2) { + this.startMargin -= 2 + } + }) + Button('下边距增加').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + this.endMargin += 2 + }) + Button('下边距减少').width('100%').margin({bottom: '12vp'}) + .onClick(() => { + if(this.endMargin > 2) { + this.endMargin -= 2 + } + }) + }.padding({top: '24vp', left: '24vp', right: '24vp'}) + } +} +``` + +![tabs3](figures/tabs3.gif) + +### 示例3 + +```ts +// xxx.ets +@Entry +@Component +struct TabsOpaque { + @State message: string = 'Hello World' + private controller: TabsController = new TabsController() + private controller1: TabsController = new TabsController() + @State selfFadingFade: boolean = true; + build() { + Column() { + Button('子页签设置渐隐').width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + this.selfFadingFade = true; + }) + Button('子页签设置不渐隐').width('100%').margin({bottom: '12vp'}) + .onClick((event: ClickEvent) => { + this.selfFadingFade = false; + }) + Tabs({ barPosition: BarPosition.End, controller: this.controller }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar('pink') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow) + }.tabBar('yellow') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + }.tabBar('blue') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + } + .vertical(false).scrollable(true) + .barMode(BarMode.Scrollable) + .barHeight(80).animationDuration(400) + .onChange((index: number) => { + console.info(index.toString()) + }) + .fadingEdge(this.selfFadingFade) + .height('30%').width('100%') + Tabs({ barPosition: BarPosition.Start, controller: this.controller1 }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar('pink') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow) + }.tabBar('yellow') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + }.tabBar('blue') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar('green') + } + .vertical(true).scrollable(true) + .barMode(BarMode.Scrollable) + .barHeight(200) + .barWidth(80).animationDuration(400) + .onChange((index: number) => { + console.info(index.toString()) + }) + .fadingEdge(this.selfFadingFade) + .height('30%').width('100%') + } + .padding({top: '24vp', left: '24vp', right: '24vp'}) + } +} +``` + +![tabs4](figures/tabs4.gif) + +### 示例4 + +```ts +// xxx.ets +@Entry +@Component +struct barBackgroundColorTest { + private controller: TabsController = new TabsController() + @State barOverlap: boolean = true; + @State barBackgroundColor: string = '#88888888'; + + build() { + Column() { + Button("barOverlap变化").width('100%').margin({bottom: '12vp'}) + .onClick((event:ClickEvent) =>{ + if (this.barOverlap) { + this.barOverlap = false; + } else { + this.barOverlap = true; + } + }) + + Tabs({ barPosition: BarPosition.Start, index:0, controller: this.controller }) { + TabContent() { + Column() { + Text(`barOverlap ${this.barOverlap}`).fontSize(16).margin({ top: this.barOverlap ? '56vp' : 0 }) + Text(`barBackgroundColor ${this.barBackgroundColor}`).fontSize(16) + }.width('100%').width('100%').height('100%') + .backgroundColor(Color.Pink) + } + .tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), "1")) + TabContent() { + Column() { + Text(`barOverlap ${this.barOverlap}`).fontSize(16).margin({ top: this.barOverlap ? '56vp' : 0 }) + Text(`barBackgroundColor ${this.barBackgroundColor}`).fontSize(16) + }.width('100%').width('100%').height('100%') + .backgroundColor(Color.Yellow) + } + .tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), "2")) + TabContent() { + Column() { + Text(`barOverlap ${this.barOverlap}`).fontSize(16).margin({ top: this.barOverlap ? '56vp' : 0 }) + Text(`barBackgroundColor ${this.barBackgroundColor}`).fontSize(16) + }.width('100%').width('100%').height('100%') + .backgroundColor(Color.Green) + } + .tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), "3")) + } + .vertical(false) + .barMode(BarMode.Fixed) + .height('60%') + .barOverlap(this.barOverlap) + .scrollable(true) + .animationDuration(10) + .barBackgroundColor(this.barBackgroundColor) + } + .height(500) + .padding({top: '24vp', left: '24vp', right: '24vp'}) + } +} +``` + +![tabs5](figures/tabs5.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md b/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md index b4aec04b13ee746461f1d159b5de2d59971f846f..8f12af688da130069aa195994a29139254b1439c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md @@ -52,7 +52,7 @@ | repeat | boolean | 是否为重复触发事件,用于LongPressGesture手势触发场景。 | | offsetX | number | 手势事件x轴相对偏移量,单位为vp,用于PanGesture手势触发场景,从左向右滑动offsetX为正,反之为负。 | | offsetY | number | 手势事件y轴相对偏移量,单位为vp,用于PanGesture手势触发场景,从上向下滑动offsetY为正,反之为负。 | -| angle | number | 用于RotationGesture手势触发场景时,表示旋转角度。
用于SwipeGesture手势触发场景时,表示滑动手势的角度,即两根手指间的线段与水平方向的夹角变化的度数。
>  **说明:**
> 角度计算方式:滑动手势被识别到后,连接两根手指之间的线被识别为起始线条,随着手指的滑动,手指之间的线条会发生旋转,根据起始线条两端点和当前线条两端点的坐标,使用反正切函数分别计算其相对于水平方向的夹角,最后arctan2(cy2-cy1,cx2-cx1)-arctan2(y2-y1,x2-x1)为旋转的角度。以起始线条为坐标系,顺时针旋转为0到180度,逆时针旋转为-180到0度。 | +| angle | number | 用于RotationGesture手势触发场景时,表示旋转角度。
用于SwipeGesture手势触发场景时,表示滑动手势的角度,即两根手指间的线段与水平方向的夹角变化的度数。
**说明:**
角度计算方式:滑动手势被识别到后,连接两根手指之间的线被识别为起始线条,随着手指的滑动,手指之间的线条会发生旋转,根据起始线条两端点和当前线条两端点的坐标,使用反正切函数分别计算其相对于水平方向的夹角,最后arctan2(cy2-cy1,cx2-cx1)-arctan2(y2-y1,x2-x1)为旋转的角度。以起始线条为坐标系,顺时针旋转为0到180度,逆时针旋转为-180到0度。 | | scale | number | 缩放比例,用于PinchGesture手势触发场景。 | | pinchCenterX | number | 捏合手势中心点相对于当前组件元素左上角x轴坐标,单位为vp,用于PinchGesture手势触发场景。 | | pinchCenterY | number | 捏合手势中心点相对于当前组件元素左上角y轴坐标,单位为vp,用于PinchGesture手势触发场景。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index dae32a79e47ae36b2e4c10d6c1a574a8dd995d20..3c035792fe81b346239a5e39bedcf08bcd10be34 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -22,7 +22,7 @@ show(value: { title: string | Resource, message: string  | ---------- | -------------------------- | ------- | ----------------------------- | | title | [Resource](ts-types.md#resource) \| string | 是 | 弹窗标题。 | | message | [Resource](ts-types.md#resource) \| string | 是 | 弹窗内容。 | -| autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true | +| autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true
值为true时,点击遮障层关闭弹窗,值为false时,点击遮障层不关闭弹窗。 | | confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
action: () => void
} | 否 | 确认按钮的文本内容和点击回调。
默认值:
value:按钮文本内容。
action: 按钮选中时的回调。 | | cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Bottom | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md index 97bcde01a594ee0a82190e4a0bde3a56a9315294..7d512ff1b3914c23beef10f3ea693b72f49e531e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md @@ -25,8 +25,8 @@ | confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?:  [ResourceColor](ts-types.md#resourcecolor),
action: () => void
} | 否 | 确认按钮的文本内容、文本色、按钮背景色和点击回调。 | | cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | | alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | -| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | -| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 | +| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。
默认值:{ dx: 0 , dy: 0 } | +| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。
默认值:4 | ## AlertDialogParamWithButtons对象说明 | 参数名 | 参数类型 | 必填 | 参数描述 | 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 d5be648cdb9f74ba8e20b79200d4f3162a9f726f..5fa377760f5659035aca6ad1aa8f2ced4841a889 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 @@ -33,6 +33,26 @@ show(options?: DatePickerDialogOptions) | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。 | +**异常情形说明:** + +| 异常情形 | 对应结果 | +| -------- | ------------------------------------------------------------ | +| 起始日期晚于结束日期,选中日期未设置 | 起始日期、结束日期和选中日期都为默认值 | +| 起始日期晚于结束日期,选中日期早于起始日期默认值 | 起始日期、结束日期都为默认值,选中日期为起始日期默认值 | +| 起始日期晚于结束日期,选中日期晚于结束日期默认值 | 起始日期、结束日期都为默认值,选中日期为结束日期默认值 | +| 起始日期晚于结束日期,选中日期在起始日期与结束日期默认值范围内 | 起始日期、结束日期都为默认值,选中日期为设置的值 | +| 选中日期早于起始日期 | 选中日期为起始日期 | +| 选中日期晚于结束日期 | 选中日期为结束日期 | +| 起始日期晚于当前系统日期,选中日期未设置 | 选中日期为起始日期 | +| 结束日期早于当前系统日期,选中日期未设置 | 选中日期为结束日期 | +| 日期格式不符合规范,如‘1999-13-32’ | 取默认值 | +| 起始日期或结束日期早于系统有效范围 | 起始日期或结束日期取系统有效范围最早日期 | +| 起始日期或结束日期晚于系统有效范围 | 起始日期或结束日期取系统有效范围最晚日期 | + +系统日期范围:1900-1-31 ~ 2100-12-31 + +选中日期会在起始日期与结束日期异常处理完成后再进行异常情形判断处理 + ## 示例 ```ts diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 5a4dc3f73ca81909c7ca90630ecebedd74b4a957..337f99791d63badfb3050f245efe11efbfb7b58d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -2021,20 +2021,6 @@ filter(filter: string): void ![filterDemo](figures/filterDemo.jpeg) -### getTransform - -getTransform(): Matrix2D - -获取当前被应用到上下文的转换矩阵。该接口为空接口。 - -从API version 9开始,该接口支持在ArkTS卡片中使用。 - -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------- | ----- | -| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 矩阵对象。 | - ### resetTransform resetTransform(): void @@ -2313,6 +2299,86 @@ setTransform方法使用的参数和transform()方法相同,但setTransform() ![zh-cn_image_0000001193872526](figures/zh-cn_image_0000001193872526.png) +### setTransform + +setTransform(transform?: Matrix2D): void + +以Matrix2D对象为模板重置现有的变换矩阵并创建新的变换矩阵。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| --------- | ---------------------------------------- | ---- | ---- | ----- | +| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 否 | null | 变换矩阵。 | + +### getTransform + +getTransform(): Matrix2D + +获取当前被应用到上下文的转换矩阵。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ----- | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 矩阵对象。 | + +**示例:** + + ```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%') + } + } + ``` + + ![zh-cn_image_0000001219982726.png](figures/zh-cn_image_0000001219982726.png) + ### translate translate(x: number, y: number): void diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md index d3eea99c4aed770799a8d4dbc631ccea8c58f526..f567b17cfd740fd1085b29a8df822d4d4890f2df 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md @@ -10,8 +10,8 @@ | 名称 | 参数 | 必填 | 参数描述 | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | 否 | 设置当前页面的自定义入场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线。string类型的取值支持"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"。
默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | -| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string,
delay?: number
} | 否 | 设置当前页面的自定义退场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线,string类型取值与PageTransitionEnter相同。
 默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | +| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | 否 | 设置当前页面的自定义入场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线。string类型的取值支持"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"。
默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | +| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | 否 | 设置当前页面的自定义退场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线,string类型取值与PageTransitionEnter相同。
 默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | ## RouteType枚举说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index f9c7b26b894cdde60667e49b4c61cc4c40247d31..6fe560c25eaca837892b1c8e88903b09151fc387 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -21,6 +21,9 @@ ## AppStorage +AppStorage具体UI使用说明,详见[AppStorage(应用全局的UI状态存储)](../../quick-start/arkts-appstorage.md) + + ### link10+ static link(propName: string): SubscribedAbstractProperty @@ -698,6 +701,9 @@ let res: number = AppStorage.Size(); // 1 ## LocalStorage9+ +LocalStorage具体UI使用说明,详见[LocalStorage(页面级UI状态存储)](../../quick-start/arkts-localstorage.md) + + ### constructor9+ constructor(initializingProperties?: Object) @@ -735,9 +741,7 @@ static getShared(): LocalStorage | [LocalStorage](#localstorage9) | 返回LocalStorage实例。 | -```ts -let storage: LocalStorage = LocalStorage.getShared(); -``` +getShared具体使用,见[在UI页面通过getShared接口获取在通过loadContent共享的LocalStorage实例](../../quick-start/arkts-localstorage.md#将localstorage实例从uiability共享到一个或多个视图) ### has9+ @@ -1161,6 +1165,10 @@ link.set(50); // PropB -> 49, link.get() --> undefined ## PersistentStorage + +PersistentStorage具体UI使用说明,详见[PersistentStorage(持久化存储UI状态)](../../quick-start/arkts-persiststorage.md) + + ### PersistPropsOptions | 参数名 | 类型 | 必填 | 参数描述 | @@ -1196,9 +1204,7 @@ static persistProp<T>(key: string, defaultValue: T): void **示例:** -```ts -PersistentStorage.persistProp('highScore', '0'); -``` +persistProp具体使用,见[从AppStorage中访问PersistentStorage初始化的属性](../../quick-start/arkts-persiststorage.md#从appstorage中访问persistentstorage初始化的属性) ### deleteProp10+ @@ -1352,6 +1358,9 @@ let keys: Array = PersistentStorage.Keys(); ## Environment +Environment具体使用说明,详见[Environment(设备环境查询)](../../quick-start/arkts-environment.md) + + ### EnvPropsOptions | 参数名 | 类型 | 必填 | 参数描述 | @@ -1386,21 +1395,7 @@ static envProp<S>(key: string, value: S): boolean **示例:** -```ts -Environment.envProp('accessibilityEnabled', 'default'); -``` - - -### 内置环境变量说明 - -| key | 类型 | 说明 | -| -------------------- | --------------- | ---------------------------------------- | -| accessibilityEnabled | string | 无障碍屏幕朗读是否启用。 | -| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | -| fontScale | number | 字体大小比例。 | -| fontWeightScale | number | 字重比例。 | -| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | -| languageCode | string | 当前系统语言,小写字母,例如zh。 | +envProp具体使用,见[从UI中访问Environment参数](../../quick-start/arkts-environment.md#从ui中访问environment参数) ### envProps10+ @@ -1525,4 +1520,16 @@ Environment.EnvProps([{ key: 'accessibilityEnabled', defaultValue: 'default' }, }, { key: 'prop', defaultValue: 'hhhh' }]); let keys: Array = Environment.Keys(); // accessibilityEnabled, languageCode, prop -``` \ No newline at end of file +``` + + +## 内置环境变量说明 + +| key | 类型 | 说明 | +| -------------------- | --------------- | ---------------------------------------- | +| accessibilityEnabled | string | 无障碍屏幕朗读是否启用。 | +| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | +| fontScale | number | 字体大小比例。 | +| fontWeightScale | number | 字重比例。 | +| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | +| languageCode | string | 当前系统语言,小写字母,例如zh。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index 9d6836a92a0a5aaacd33614f770b3ae42ba2590d..f0a595dad67fa70f2a08afac1d40bcb332af7dfd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -12,7 +12,7 @@ | 名称 | 参数 | 参数描述 | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| sharedTransition | id: string,
{
 duration?: number,
 curve?: Curve \| string,
 delay?: number,
 motionPath?:
{
 path: string,
 form?: number,
 to?: number,
 rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
- id:设置组件的id。
- duration:描述共享元素转场动效播放时长。
默认值:1000
单位:毫秒
取值范围:[0, +∞)
值为0时表示无动画。设置小于0的值时,按默认值1000处理。
- curve:默认曲线为Linear,有效值参见[Curve](ts-animatorproperty.md)说明。
- delay:用来描述共享元素转场动效延迟播放的时长。
默认值:0
单位:毫秒
取值范围:[0, +∞)
设置小于0的值时,按值为0处理。
- motionPath:运动路径信息,详细说明请参考[路径动画](ts-motion-path-animation.md)。
- path:设置路径。
- from:设置起始值。
- to:设置终止值。
- rotatable:是否旋转。
- zIndex:设置Z轴。
- 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)
} | 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
- id:设置组件的id。
- duration:描述共享元素转场动效播放时长。
默认值:1000
单位:毫秒
取值范围:[0, +∞)
值为0时表示无动画。设置小于0的值时,按默认值1000处理。
- curve:默认曲线为Curve.Linear。
- delay:用来描述共享元素转场动效延迟播放的时长。
默认值:0
单位:毫秒
取值范围:[0, +∞)
设置小于0的值时,按值为0处理。
- motionPath:运动路径信息,详细说明请参考[路径动画](ts-motion-path-animation.md)。
- path:设置路径。
- from:设置起始值。
- to:设置终止值。
- rotatable:是否旋转。
- zIndex:设置Z轴。
- type:动画类型。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index 5f0a1994fc126dd769aad8b9dd70558fa7637cb6..a8fcc9eee8156d13a53ae6d28697ace0561d6650 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -8,22 +8,22 @@ ## 属性 -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | -| background10+ | builder: [CustomBuilder](ts-types.md#custombuilder8),
options?: {align?:[Alignment](ts-appendix-enums.md#alignment)} | builder:自定义背景。
align:设置自定义背景与组件的对齐方式。
同时设置了background,backgroundColor,backgroundImage时,叠加显示,background在最上层。 | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件的背景色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | src:图片地址,支持网络图片资源地址和本地图片资源地址和Base64,不支持svg类型的图片。
repeat:设置背景图片的重复样式,默认不重复。当设置的背景图片为透明底色图片,且同时设置了backgroundColor时,二者叠加显示,背景颜色在最底部。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | 设置背景图像的高度和宽度。当输入为{width: Length, height: Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。
width和height取值范围: [0, +∞)
默认值:ImageSize.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按值为0显示。当设置了height未设置width时,width根据图片原始宽高比进行调整。 | -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | 设置背景图在组件中显示位置,即相对于组件左上角的坐标。
默认值:
{
x: 0,
y: 0
}
x和y值设置百分比时,偏移量是相对组件自身宽高计算的。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| 名称 | 参数类型 | 描述 | +| -------------------------------- | ---------------------------------------- | ---------------------------------------- | +| background10+ | builder: [CustomBuilder](ts-types.md#custombuilder8),
options?: {align?:[Alignment](ts-appendix-enums.md#alignment)} | builder:自定义背景。
align:设置自定义背景与组件的对齐方式。
同时设置了background,backgroundColor,backgroundImage时,叠加显示,background在最上层。
不支持嵌套使用该属性。 | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件的背景色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | src:图片地址,支持网络图片资源地址和本地图片资源地址和Base64,不支持svg类型的图片。
repeat:设置背景图片的重复样式,默认不重复。当设置的背景图片为透明底色图片,且同时设置了backgroundColor时,二者叠加显示,背景颜色在最底部。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | 设置背景图像的高度和宽度。当输入为{width: Length, height: Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。
width和height取值范围: [0, +∞)
默认值:ImageSize.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按值为0显示。当设置了height未设置width时,width根据图片原始宽高比进行调整。 | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | 设置背景图在组件中显示位置,即相对于组件左上角的坐标。
默认值:
{
x: 0,
y: 0
}
x和y值设置百分比时,偏移量是相对组件自身宽高计算的。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | backgroundBlurStyle9+ | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),
options10+?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10对象说明) | 为当前组件提供一种在背景和内容之间的模糊能力。
value: 背景模糊样式。模糊样式中封装了模糊半径、蒙版颜色、蒙版透明度、饱和度、亮度五个参数。
options: 可选参数,背景模糊选项。
该接口支持在ArkTS卡片中使用。 | ## BackgroundBlurStyleOptions10+对象说明 -| 名称 | 参数类型 | 必填 | 描述 | -| --------------------------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| colorMode10+ | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | 否 | 背景模糊效果使用的深浅色模式。
默认值:ThemeColorMode.System | -| adaptiveColor10+ | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | 否 | 背景模糊效果使用的取色模式。
默认值:AdaptiveColor.Default | -| scale10+ | number | 否 | 背景材质模糊效果程度。此参数为系统接口。
默认值:1.0
取值范围:[0.0, 1.0]
| +| 名称 | 参数类型 | 必填 | 描述 | +| ------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| colorMode | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | 否 | 背景模糊效果使用的深浅色模式。
默认值:ThemeColorMode.System | +| adaptiveColor | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | 否 | 背景模糊效果使用的取色模式。
默认值:AdaptiveColor.Default | +| scale | number | 否 | 背景材质模糊效果程度。此参数为系统接口。
默认值:1.0
取值范围:[0.0, 1.0]
| ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 2ade5dcdb6bc59452b253df6a4c73cacd7baae72..ee1b03d2927828a14f2a9624ae16061b11cce4b9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -8,22 +8,22 @@ ## 属性 -| 名称 | 参数类型 | 描述 | -| ---------- | ---------------------------------------- | --------------------------------------- | -| borderImage | [BorderImageOption](#borderimageoption对象说明) | 图片边框或者渐变色边框设置接口。
该接口支持在ArkTS卡片中使用。 | +| 名称 | 参数类型 | 描述 | +| ----------- | ---------------------------------------- | -------------------------------------- | +| borderImage | [BorderImageOption](#borderimageoption对象说明) | 图片边框或者渐变色边框设置接口。
该接口支持在ArkTS卡片中使用。 | ## BorderImageOption对象说明 该接口支持在ArkTS卡片中使用。 -| 名称 | 类型 | 描述 | -| ---------- | ---------------------------------------- | --------------------------------------- | -| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | 边框图源或者渐变色设置。
**说明:** 边框图源仅适用于容器组件,如Row、Column、Flex,在非容器组件上使用会失效。 | -| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框切割宽度。
默认值:0 | -| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框宽度。
默认值:0 | -| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片向外延伸距离。
默认值:0 | -| repeat | [RepeatMode](#repeatmode枚举说明) | 设置边框图片的重复方式。
默认值:RepeatMode.Stretch | -| fill | boolean | 设置边框图片中心填充。
默认值:false | +| 名称 | 类型 | 描述 | +| ------ | ---------------------------------------- | ---------------------------------------- | +| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | 边框图源或者渐变色设置。
**说明:**
边框图源仅适用于容器组件,如Row、Column、Flex,在非容器组件上使用会失效。 | +| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框切割宽度。
默认值:0 | +| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置图片边框宽度。
默认值:0 | +| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | 设置边框图片向外延伸距离。
默认值:0 | +| repeat | [RepeatMode](#repeatmode枚举说明) | 设置边框图片的重复方式。
默认值:RepeatMode.Stretch | +| fill | boolean | 设置边框图片中心填充。
默认值:false | ## RepeatMode枚举说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md index e2c3ad8c2af064fb89ebf808a57ab073e52a6efa..63676c33dd1f6e595003388720254b7d710b6aa7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md @@ -8,13 +8,13 @@ ## 属性 -| 名称 | 参数说明 | 描述 | -| ---------- | ------------------------------------------- | ------------------------------------------------------------ | -| flexBasis | number \| string | 设置组件在父容器主轴方向上的基准尺寸。
默认值:'auto'(表示组件在主轴方向上的基准尺寸为组件原本的大小)。
不支持百分比设置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| flexGrow | number | 设置父容器的剩余空间分配给此属性所在组件的比例。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| flexShrink | number | 设置父容器压缩尺寸分配给此属性所在组件的比例。
父容器为Row、Column时,默认值:0
父容器为flex时,默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | 子组件在父容器交叉轴的对齐格式,会覆盖Flex、Column、Row、GridRow布局容器中的alignItems设置。
GridCol可以绑定alignsSelf属性来改变它自身在交叉轴方向上的布局。
默认值:ItemAlign.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| layoutWeight | number \| string | 父容器尺寸确定时,设置了layoutWeight属性的子元素与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,表示自适应占满剩余空间。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在Row/Column/Flex布局中生效。
可选值为大于等于0的数字,或者可以转换为数字的字符串。 | +| 名称 | 参数说明 | 描述 | +| ------------ | ---------------------------------------- | ---------------------------------------- | +| flexBasis | number \| string | 设置组件在父容器主轴方向上的基准尺寸。
默认值:'auto'(表示组件在主轴方向上的基准尺寸为组件原本的大小)。
不支持百分比设置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| flexGrow | number | 设置父容器的剩余空间分配给此属性所在组件的比例。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| flexShrink | number | 设置父容器压缩尺寸分配给此属性所在组件的比例。
父容器为Row、Column时,默认值:0
父容器为Flex时,默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | 子组件在父容器交叉轴的对齐格式,会覆盖Flex、Column、Row、GridRow布局容器中的alignItems设置。
GridCol可以绑定alignsSelf属性来改变它自身在交叉轴方向上的布局。
默认值:ItemAlign.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| layoutWeight | number \| string | 父容器尺寸确定时,设置了layoutWeight属性的子元素与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,表示自适应占满剩余空间。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在Row/Column/Flex布局中生效。
可选值为大于等于0的数字,或者可以转换为数字的字符串。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index 334beb7fb8ca110b74e63e8668d0f43baa7822ca..ed24ec2eb887a44704bad164563a909488608ec2 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -9,14 +9,15 @@ ## 属性 -| 名称 | 参数说明 | 描述 | -| --------------- | -------- | ------------------------------------------------------------ | -| aspectRatio | number | 指定当前组件的宽高比,aspectRatio = width/height。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| displayPriority | number | 设置当前组件在布局容器中显示的优先级,当父容器空间不足时,低优先级的组件会被隐藏。
小数点后的数字不作优先级区分,即区间为[x, x + 1)内的数字视为相同优先级。例如:1.0与1.9为同一优先级。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在Row/Column/Flex(单行)容器组件中生效。 | - +| 名称 | 参数说明 | 描述 | +| --------------- | ------ | ---------------------------------------- | +| aspectRatio | number | 指定当前组件的宽高比,aspectRatio = width/height。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| displayPriority | number | 设置当前组件在布局容器中显示的优先级,当父容器空间不足时,低优先级的组件会被隐藏。
小数点后的数字不作优先级区分,即区间为[x, x + 1)内的数字视为相同优先级。例如:1.0与1.9为同一优先级。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
仅在Row/Column/Flex(单行)容器组件中生效。 | ## 示例 +### 示例1 + ```ts // xxx.ets @Entry @@ -76,6 +77,8 @@ struct AspectRatioExample { **图2** 横屏显示
![zh-cn_image_0000001174264382](figures/zh-cn_image_0000001174264382.gif) +### 示例2 + ```ts class ContainerInfo { label: string = ''; diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md index aae6b01cae3434ad7fd39b515eae6a6c141d0307..fb7418b17964c9946ce87442c1122eaa7537c276 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md @@ -14,8 +14,8 @@ | 名称 | 参数类型 | 描述 | | ---------------------------- | ---------------------------------------- | ---------------------------------------- | -| bindMenu | content: Array<[MenuItem](#menuitem)> \| [CustomBuilder](ts-types.md#custombuilder8),
options: [MenuOptions](#menuoptions10) | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持图标+文本排列和自定义两种功能。
content: 必填,配置菜单项图标和文本的数组,或者自定义组件。
options: 非必填,配置弹出菜单的参数。 | -| bindContextMenu8+ | content: [CustomBuilder](ts-types.md#custombuilder8),
responseType: [ResponseType](ts-appendix-enums.md#responsetype8)
options: [ContextMenuOptions](#contextmenuoptions10) | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。
responseType: 必填。菜单弹出条件,长按或者右键点击。
options: 非必填,配置弹出菜单的参数。 | +| bindMenu | content: Array<[MenuItem](#menuitem)> \| [CustomBuilder](ts-types.md#custombuilder8),
options?: [MenuOptions](#menuoptions10) | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持图标+文本排列和自定义两种功能。
content: 配置菜单项图标和文本的数组,或者自定义组件。
options: 配置弹出菜单的参数。 | +| bindContextMenu8+ | content: [CustomBuilder](ts-types.md#custombuilder8),
responseType: [ResponseType](ts-appendix-enums.md#responsetype8)
options?: [ContextMenuOptions](#contextmenuoptions10) | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。
responseType: 菜单弹出条件,长按或者右键点击。
options: 配置弹出菜单的参数。 | ## MenuItem @@ -27,13 +27,13 @@ ## MenuOptions10+ -| 名称 | 类型 | 必填 | 描述 | -| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| title | string | 否 | 菜单标题。
**说明:**
仅在content设置为Array<[MenuItem](#menuitem)> 时生效。 | -| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | -| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按默认值[BottomLeft](ts-appendix-enums.md#placement8)处理,相对父组件区域弹出。 | -| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | -| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | 否 | 菜单标题。
**说明:**
仅在content设置为Array<[MenuItem](#menuitem)> 时生效。 | +| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | +| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按默认值[BottomLeft](ts-appendix-enums.md#placement8)处理,相对父组件区域弹出。 | +| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | +| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | ## ContextMenuOptions10+ @@ -41,8 +41,8 @@ | ----------- | ---------------------------------------- | ---- | ---------------------------------------- | | offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | | placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按未设置placement处理,菜单跟随点击位置弹出。 | -| enableArrow | boolean | 否 | 是否显示箭头。如果菜单的大小和位置不足以放置箭头时,不会显示箭头。
默认值:false, 不显示箭头。
**说明:**
箭头显示时,placement未设置或者值为非法值,默认在目标物上方显示,否则按照placement的位置优先显示。当前位置显示不下时,会自动调整位置。| -| arrowOffset | [Length](ts-types.md#length) | 否 | 箭头在菜单处的偏移。箭头在菜单水平方向时,偏移量为箭头至最左侧的距离,默认居中。箭头在菜单竖直方向时,偏移量为箭头至最上侧的距离,默认居中。偏移量必须合法且转换为具体数值时大于0才会生效,另外该值生效时不会导致箭头超出菜单四周的安全距离。根据配置的placement来计算是在水平还是竖直方向上偏移。 | +| enableArrow | boolean | 否 | 是否显示箭头。如果菜单的大小和位置不足以放置箭头时,不会显示箭头。
默认值:false, 不显示箭头。
**说明:**
箭头显示时,placement未设置或者值为非法值,默认在目标物上方显示,否则按照placement的位置优先显示。当前位置显示不下时,会自动调整位置。 | +| arrowOffset | [Length](ts-types.md#length) | 否 | 箭头在菜单处的偏移。箭头在菜单水平方向时,偏移量为箭头至最左侧的距离,默认居中。箭头在菜单竖直方向时,偏移量为箭头至最上侧的距离,默认居中。偏移量必须合法且转换为具体数值时大于0才会生效,另外该值生效时不会导致箭头超出菜单四周的安全距离。根据配置的placement来计算是在水平还是竖直方向上偏移。 | | onAppear | () => void | 否 | 菜单弹出时的事件回调。 | | onDisappear | () => void | 否 | 菜单消失时的事件回调。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-modal-transition.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-modal-transition.md index 486fb91c866cfd8fe92d2e161e4a1b469e13996f..b8a54dbbc3f3710602348cd339cd7943f91ed2e6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-modal-transition.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-modal-transition.md @@ -9,16 +9,16 @@ ## 属性 -| 名称 | 参数 | 参数描述 | -| ----- | ----- | ----- | -| bindContentCover | isShow: boolean,
builder: [CustomBuilder](ts-types.md#custombuilder8),
options?: [ContentCoverOptions](#contentcoveroptions) | 给组件绑定全屏模态页面,点击后显示模态页面。模态页面内容自定义,显示方式可设置无动画过渡,上下切换过渡以及透明渐变过渡方式。
isShow: 必填,是否显示全屏模态页面。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量
builder: 必填,配置全屏模态页面内容。
options: 非必填,配置全屏模态页面的可选属性。 | +| 名称 | 参数 | 参数描述 | +| ---------------- | ---------------------------------------- | ---------------------------------------- | +| bindContentCover | isShow: boolean,
builder: [CustomBuilder](ts-types.md#custombuilder8),
options?: [ContentCoverOptions](#contentcoveroptions) | 给组件绑定全屏模态页面,点击后显示模态页面。模态页面内容自定义,显示方式可设置无动画过渡,上下切换过渡以及透明渐变过渡方式。
isShow: 是否显示全屏模态页面。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量
builder: 配置全屏模态页面内容。
options: 配置全屏模态页面的可选属性。 | ## ContentCoverOptions -| 名称 | 类型 | 必填 | 描述 | -|-----|-----|-----|-----| -| modalTransition | [ModalTransition](ts-types.md#modaltransition10) | 否 | 全屏模态页面的转场方式。 | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 全屏模态页面的背板颜色。 | -| onAppear | () => void | 否 | 全屏模态页面显示回调函数。 | -| onDisappear | () => void | 否 | 全屏模态页面回退回调函数。 | +| 名称 | 类型 | 必填 | 描述 | +| --------------- | ---------------------------------------- | ---- | ------------- | +| modalTransition | [ModalTransition](ts-types.md#modaltransition10) | 否 | 全屏模态页面的转场方式。 | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 全屏模态页面的背板颜色。 | +| onAppear | () => void | 否 | 全屏模态页面显示回调函数。 | +| onDisappear | () => void | 否 | 全屏模态页面回退回调函数。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md index 4b3b45e97f5ef7c632a2060b12d1ae2aacd71661..f44317a43b3e546a684373966c1fe97d3a453d0f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md @@ -4,16 +4,18 @@ > **说明:** > -> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 ## 属性 -| 名称 | 参数类型 | 默认值 | 描述 | -| -------- | -------- | -------- | -------- | -| overlay | value: string | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8)10+,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment), 
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | 在当前组件上,增加遮罩文本。
value: 遮罩文本内容或自定义组件构造函数。
options: 文本定位,align设置文本相对于组件的方位,[offset](ts-universal-attributes-location.md)为文本基于自身左上角的偏移量。文本默认处于组件左上角。
两者都设置时效果重叠,文本相对于组件方位定位后再基于当前位置文本的左上角进行偏移。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| 名称 | 参数类型 | 默认值 | 描述 | +| ------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| overlay | value: string | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8)10+,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment), 
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | 在当前组件上,增加遮罩文本或者叠加自定义组件作为该组件的浮层。
value: 遮罩文本内容或自定义组件构造函数。
options: 浮层的定位,align设置浮层相对于组件的方位,[offset](ts-universal-attributes-location.md)为浮层基于自身左上角的偏移量。浮层默认处于组件左上角。
两者都设置时效果重叠,浮层相对于组件方位定位后再基于当前位置的左上角进行偏移。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
自定义组件作为浮层时,不支持键盘走焦到自定义组件中。 | ## 示例 +### 示例1 + ```ts // xxx.ets @Entry @@ -40,6 +42,8 @@ struct OverlayExample { ![zh-cn_image_0000001205769446](figures/zh-cn_image_0000001205769446.png) +### 示例2 + ```ts // xxx.ets @Entry diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-restoreId.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-restoreId.md index 9231c68c571d19422895f22b8d76744ad9ed783e..038985775753f90b9d3c2b631e8b532f96310f3e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-restoreId.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-restoreId.md @@ -4,23 +4,23 @@ > **说明:** > -> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 ## 属性 -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | +| 名称 | 参数类型 | 描述 | +| --------- | ------ | ---------------------------------------- | | restoreId | number | 标记支持分布式迁移的组件Id,用于两端设备组件的配对。同一个应用中各个支持分布式迁移组件的Id必须不同。 | ## 支持的组件 -| 组件名称 | 起始API版本 | 迁移状态 | -| -------- | -------- | -------- | -| List | 8 | 迁移当前设备显示在顶部ListItem的索引值,迁移后在对端设备上,将迁移索引值对应的ListItem在List中完整地置顶显示。 | -| Grid | 9 | 迁移当前设备显示在顶部GridItem的索引值,迁移后在对端设备上,将迁移索引值对应的GridItem在Grid中完整地置顶显示。ScrollBar位置无法迁移。 | -| Scroll | 9 | 迁移距顶部滚动的绝对距离。两端设备显示规格不同等原因导致布局不一致,会影响迁移效果。 | -| TextArea | 9 | 迁移输入的文本内容和光标位置。 | -| TextInput | 9 | 迁移输入的文本内容和光标位置。 | +| 组件名称 | 起始版本 | 迁移状态 | +| --------- | ---- | ---------------------------------------- | +| List | 8 | 迁移当前设备显示在顶部ListItem的索引值,迁移后在对端设备上,将迁移索引值对应的ListItem在List中完整地置顶显示。 | +| Grid | 9 | 迁移当前设备显示在顶部GridItem的索引值,迁移后在对端设备上,将迁移索引值对应的GridItem在Grid中完整地置顶显示。ScrollBar位置无法迁移。 | +| Scroll | 9 | 迁移距顶部滚动的绝对距离。两端设备显示规格不同等原因导致布局不一致,会影响迁移效果。 | +| TextArea | 9 | 迁移输入的文本内容和光标位置。 | +| TextInput | 9 | 迁移输入的文本内容和光标位置。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md index cd4b54120254738aa2475338eb1735175ec46add..fa047a20d64d73fa857980255429bc647b1efbe8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md @@ -4,15 +4,15 @@ > **说明:** > -> 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > -> 不支持横竖屏切换。 +> 不支持横竖屏切换。 ## 属性 -| 名称 | 参数 | 参数描述 | -| ----- | ----- | ----- | -| bindSheet | isShow: boolean,
builder: [CustomBuilder](ts-types.md#custombuilder8),
options?: [SheetOptions](#sheetoptions) | 给组件绑定半模态页面,点击后显示模态页面。
isShow: 必填,是否显示半模态页面。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量
builder: 必填,配置半模态页面内容。
options: 非必填,配置半模态页面的可选属性。 | +| 名称 | 参数 | 参数描述 | +| --------- | ---------------------------------------- | ---------------------------------------- | +| bindSheet | isShow: boolean,
builder: [CustomBuilder](ts-types.md#custombuilder8),
options?: [SheetOptions](#sheetoptions) | 给组件绑定半模态页面,点击后显示模态页面。
isShow: 是否显示半模态页面。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量
builder: 配置半模态页面内容。
options: 配置半模态页面的可选属性。 | > **说明:** > > 在非双向绑定情况下,以拖拽方式关闭半模态页面不会改变isShow参数的值。 @@ -20,20 +20,20 @@ > 为了使isShow参数值与半模态界面的状态同步,建议使用[$$](../../quick-start/arkts-two-way-sync.md)双向绑定isShow参数。 ## SheetOptions -| 名称 | 类型 | 必填 | 描述 | -| ----- | ----- | ----- | ------ | -| height | [SheetSize](#sheetsize) \| [Length](ts-types.md#length) | 否 | 半模态高度,默认是LARGE。 | -| dragBar | boolean | 否 | 是否显示控制条,默认显示。 | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 半模态页面的背板颜色。 | -| onAppear | () => void | 否 | 半模态页面显示回调函数。 | -| onDisappear | () => void | 否 | 半模态页面回退回调函数。 | +| 名称 | 类型 | 必填 | 描述 | +| --------------- | ---------------------------------------- | ---- | --------------- | +| height | [SheetSize](#sheetsize) \| [Length](ts-types.md#length) | 否 | 半模态高度,默认是LARGE。 | +| dragBar | boolean | 否 | 是否显示控制条,默认显示。 | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 半模态页面的背板颜色。 | +| onAppear | () => void | 否 | 半模态页面显示回调函数。 | +| onDisappear | () => void | 否 | 半模态页面回退回调函数。 | ## SheetSize -| 名称 | 参数描述 | -| -------- | -------- | -| MEDIUM | 指定半模态高度为屏幕高度一半。 | -| LARGE | 指定半模态高度几乎为屏幕高度。 | +| 名称 | 参数描述 | +| ------ | --------------- | +| MEDIUM | 指定半模态高度为屏幕高度一半。 | +| LARGE | 指定半模态高度几乎为屏幕高度。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md index f5edd064e7e05ff3a92c0c2c2b4ce591ac1baac5..fbda8561443bee93c0ca8c621ce35e6470e09ea4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-size.md @@ -16,24 +16,22 @@ | height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。
从API version 9开始,该接口支持在ArkTS卡片中使用。
从API version 10开始,该接口支持calc计算特性。 | | size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | 设置高宽尺寸。
从API version 9开始,该接口支持在ArkTS卡片中使用。
从API version 10开始,该接口支持calc计算特性。 | | padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | 设置内边距属性。
参数为Length类型时,四个方向内边距同时生效。
默认值:0
padding设置百分比时,上下左右内边距均以父容器的width作为基础值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
从API version 10开始,该接口支持calc计算特性。 | -| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | 设置外边距属性。
参数为Length类型时,四个方向外边距同时生效。
默认值:0
margin设置百分比时,上下左右外边距均以父容器的width作为基础值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
从API version 10开始,该接口支持calc计算特性。 | +| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | 设置外边距属性。
参数为Length类型时,四个方向外边距同时生效。
默认值:0
margin设置百分比时,上下左右外边距均以父容器的width作为基础值。在Row、Column、Flex交叉轴上布局时,子组件交叉轴的大小与margin的和为整体。
例如Column容器宽100,其中子组件宽50,margin left为10,right为20,子组件实际的水平方向offset为20。
从API version 9开始,该接口支持在ArkTS卡片中使用。
从API version 10开始,该接口支持calc计算特性。 | | constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。取值结果参考[constraintSize取值对width/height影响](ts-universal-attributes-size.md#constraintsize取值对widthheight影响)。
默认值:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
}
从API version 9开始,该接口支持在ArkTS卡片中使用。
从API version 10开始,该接口支持calc计算特性。 | ## constraintSize取值对width/height影响 -| 大小排列 | 结果 | +| 缺省值 | 结果 | | ---------------------------------------- | ------------------ | -| minWidth/minHeight < width/height < maxWidth/maxHeight | width/height | -| minWidth/minHeight < maxWidth/maxHeight < width/height | maxWidth/maxHeight | -| maxWidth/maxHeight < minWidth/minHeight < width/height | minWidth/minHeight | -| maxWidth/maxHeight < width/height < minWidth/minHeight | minWidth/minHeight | -| width/height < maxWidth/maxHeight < minWidth/minHeight | minWidth/minHeight | -| width/height < minWidth/minHeight < maxWidth/maxHeight | minWidth/minHeight | -| minWidth/minHeight = maxWidth/maxHeight | minWidth/minHeight | -| minWidth/minHeight < maxWidth/maxHeight = width/height | maxWidth/maxHeight | -| maxWidth/maxHeight < minWidth/minHeight = width/height | minWidth/minHeight | -| width/height = minWidth/minHeight < maxWidth/maxHeight | minWidth/minHeight | -| width/height = maxWidth/maxHeight < minWidth/minHeight | minWidth/minHeight | +| / | max(minWidth/minHeight, min(maxWidth/maxHeight, width/height)) | +| maxWidth/maxHeight | max(minWidth/minHeight, width/height) | +| minWidth/minHeight | min(maxWidth/maxHeight, width/height) | +|width/height|maxWidth/maxHeight > minWidth/minHeight时使用组件自身布局逻辑,
结果在maxWidth/maxHeight与minWidth/minHeight之间。
其他情况结果为max(minWidth/minHeight, maxWidth, maxHeight)。 | +|maxWidth/maxHeight && width/height| minWidth/minHeight | +|minWidth/minHeight && width/height| 使用组件自身布局逻辑,最终结果不超过maxWidth/maxHeight | +|maxWidth/maxHeight && minWidth/minHeight| width/height,根据其他布局属性可能拉伸或者压缩。 | +maxWidth/maxHeight && minWidth/minHeight && width/height|使用父容器传递的布局限制进行布局。| + ## 示例 ```ts 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 7cede4af00df263cca23a3ff17ae654fe1c435b9..abdecdbb2ca35499df938b03c7170ac8565203b2 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 @@ -7,12 +7,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)。 - +> +> 应用中的预置资源文件不支持拖拽(即应用在安装前的HAP包中已经存在的资源文件)。 ## 事件 | 名称 | 支持冒泡 | 功能描述 | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| onDragStart(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) =>  [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo说明)) | 否 | 第一次拖拽此事件绑定的组件时,触发回调。
- event:拖拽事件信息,详见[DragEvent](#dragevent说明)。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
返回值:拖拽过程中显示的组件信息。
触发条件:长按时间 >= 500ms。
事件优先级:长安触发时间 < 500ms,长按事件 > 拖拽事件
其他: 拖拽事件 > 长按事件。 | +| onDragStart(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) =>  [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo说明)) | 否 | 第一次拖拽此事件绑定的组件时,触发回调。
- event:拖拽事件信息,详见[DragEvent](#dragevent说明)。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
返回值:拖拽过程中显示的组件信息。
触发条件:长按时间 >= 500ms。
事件优先级:长按触发时间 < 500ms,长按事件 > 拖拽事件
其他: 拖拽事件 > 长按事件。 | | onDragEnter(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽进入组件范围内时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | | onDragMove(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽在组件范围内移动时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | | onDragLeave(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽离开组件范围内时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | @@ -90,7 +91,15 @@ struct Index { let records: Array = event.getData().getRecords(); if (records.length !== 0) { callback(event); - return; + return true; + } + return false; + } + + getDataFromUdmf(event: DragEvent, callback: (data: DragEvent)=>void) + { + if(this.getDataFromUdmfRetry(event, callback)) { + return; } setTimeout(()=>{ this.getDataFromUdmfRetry(event, callback); @@ -174,7 +183,7 @@ struct Index { .border({color: Color.Black, width: 1}) .allowDrop([udmf.UnifiedDataType.IMAGE]) .onDrop((dragEvent: DragEvent)=> { - this.getDataFromUdmfRetry(dragEvent, (event)=>{ + this.getDataFromUdmf(dragEvent, (event)=>{ let records: Array = event.getData().getRecords(); let rect: Rectangle = event.getPreviewRect(); this.imageWidth = Number(rect.width); @@ -197,7 +206,7 @@ struct Index { .margin(15) .allowDrop([udmf.UnifiedDataType.TEXT]) .onDrop((dragEvent: DragEvent)=>{ - this.getDataFromUdmfRetry(dragEvent, event => { + this.getDataFromUdmf(dragEvent, event => { let records:Array = event.getData().getRecords(); this.targetText = ((records[0])).details['value']; }) @@ -215,7 +224,7 @@ struct Index { }.width('100%').height(100).margin(20).border({color: Color.Black, width: 1}) .allowDrop([udmf.UnifiedDataType.PLAIN_TEXT]) .onDrop((dragEvent)=>{ - this.getDataFromUdmfRetry(dragEvent, event=>{ + this.getDataFromUdmf(dragEvent, event=>{ let records: Array = event.getData().getRecords(); let plainText: udmf.PlainText = (records[0]); this.abstractContent = plainText.abstract; diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md index c24e03d58602e936896db47b5ee6232b4747c58f..119a985af2195768d9cc81a8629239c178dcff2f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-touch.md @@ -44,7 +44,7 @@ | 名称 | 类型 | 描述 | | ----------- | ----------------------------------- | ----------------------------------------------------------------------------- | | touchObject | [TouchObject](#touchobject对象说明) | 历史点对应触摸事件的基础信息。 | -| size | number | 历史点对应触摸事件的手指与屏幕的触摸区域大小。 | +| size | number | 历史点对应触摸事件的手指与屏幕的触摸区域大小。
默认值:0 | | force | number | 历史点对应触摸事件的压力大小。
默认值:0
取值范围:[0,1],压力越大值越大。
此接口根据硬件设备不同,支持情况不同。当前只支持Tablet。| | timestamp | number | 历史点对应触摸事件的时间戳。触发事件时距离系统启动的时间间隔,单位毫秒。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-mouse-key.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-mouse-key.md index 9706db4024e2a5b4f93adf11fb476e19f03d339f..f308cb69df725bfb4b8b03c2b90c1cdf5aecce6e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-mouse-key.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-mouse-key.md @@ -13,32 +13,32 @@ ## 事件 -| 名称 | 支持冒泡 | 描述 | -| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| onHover(event: (isHover?: boolean, event10+?: HoverEvent) => void) | 是 | 鼠标进入或退出组件时触发该回调。
isHover:表示鼠标是否悬浮在组件上,鼠标进入时为true, 退出时为false。
event:设置阻塞事件冒泡属性。 | -| onMouse(event: (event?: MouseEvent) => void) | 是 | 当前组件被鼠标按键点击时或者鼠标在组件上悬浮移动时,触发该回调,event返回值包含触发事件时的时间戳、鼠标按键、动作、鼠标位置在整个屏幕上的坐标和相对于当前组件的坐标。 | +| 名称 | 支持冒泡 | 描述 | +| ---------------------------------------- | ---- | ---------------------------------------- | +| onHover(event: (isHover?: boolean, event10+?: HoverEvent) => void) | 是 | 鼠标进入或退出组件时触发该回调。
isHover: 表示鼠标是否悬浮在组件上,鼠标进入时为true, 退出时为false。
event: 设置阻塞事件冒泡属性。 | +| onMouse(event: (event?: MouseEvent) => void) | 是 | 当前组件被鼠标按键点击时或者鼠标在组件上悬浮移动时,触发该回调,event返回值包含触发事件时的时间戳、鼠标按键、动作、鼠标位置在整个屏幕上的坐标和相对于当前组件的坐标。 | ## MouseEvent对象说明 -| 名称 | 属性类型 | 描述 | -| --------- | ------------------------------- | -------------------- | -| screenX | number | 鼠标位置相对于应用窗口左上角的x轴坐标。 | -| screenY | number | 鼠标位置相对于应用窗口左上角的y轴坐标。 | -| x | number | 鼠标位置相对于当前组件左上角的x轴坐标。 | -| y | number | 鼠标位置相对于当前组件左上角的y轴坐标。 | -| button | [MouseButton](ts-appendix-enums.md#mousebutton) | 鼠标按键。 | -| action | [MouseAction](ts-appendix-enums.md#mouseaction) | 鼠标动作。 | -| stopPropagation | () => void | 阻塞事件冒泡。 | -| timestamp8+ | number | 事件时间戳。触发事件时距离系统启动的时间间隔,单位纳秒。 | -| target8+ | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 触发事件的元素对象显示区域。 | -| source8+ | [SourceType](ts-gesture-settings.md#sourcetype枚举说明) | 事件输入设备。 | +| 名称 | 属性类型 | 描述 | +| ---------------------- | ---------------------------------------- | ---------------------------- | +| screenX | number | 鼠标位置相对于应用窗口左上角的x轴坐标。 | +| screenY | number | 鼠标位置相对于应用窗口左上角的y轴坐标。 | +| x | number | 鼠标位置相对于当前组件左上角的x轴坐标。 | +| y | number | 鼠标位置相对于当前组件左上角的y轴坐标。 | +| button | [MouseButton](ts-appendix-enums.md#mousebutton) | 鼠标按键。 | +| action | [MouseAction](ts-appendix-enums.md#mouseaction) | 鼠标动作。 | +| stopPropagation | () => void | 阻塞事件冒泡。 | +| timestamp8+ | number | 事件时间戳。触发事件时距离系统启动的时间间隔,单位纳秒。 | +| target8+ | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 触发事件的元素对象显示区域。 | +| source8+ | [SourceType](ts-gesture-settings.md#sourcetype枚举说明) | 事件输入设备。 | ## HoverEvent10+对象说明 -| 名称 | 属性类型 | 描述 | -| --------- | ------------------------------- | -------------------- | -| stopPropagation | () => void | 阻塞事件冒泡。 | +| 名称 | 属性类型 | 描述 | +| --------------- | ---------- | ------- | +| stopPropagation | () => void | 阻塞事件冒泡。 | ## 示例 diff --git a/zh-cn/application-dev/reference/errorcodes/Readme-CN.md b/zh-cn/application-dev/reference/errorcodes/Readme-CN.md index 91f2c6b56965fea3e78e5d146ce0daf696742c4c..256ca83efa84e8bb6b1b02b574aae0c57786d226 100644 --- a/zh-cn/application-dev/reference/errorcodes/Readme-CN.md +++ b/zh-cn/application-dev/reference/errorcodes/Readme-CN.md @@ -57,7 +57,8 @@ - [网络共享错误码](errorcode-net-sharing.md) - [策略管理错误码](errorcode-net-policy.md) - [MDNS错误码](errorcode-net-mdns.md) - - [流量管理](errorcode-net-statistics.md) + - [流量管理错误码](errorcode-net-statistics.md) + - [VPN错误码](errorcode-net-vpn.md) - 通信与连接 - [Bluetooth错误码](errorcode-bluetoothManager.md) - [WIFI错误码](errorcode-wifi.md) diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md b/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md index 397f89356ff359417ed9b7e5c55fc26babcbef2b..7f0eb4b2e11eb508e284a06cfd85f0c9f06130e5 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md @@ -116,5 +116,78 @@ WAL文件大小超过默认上限(200M)。 **处理步骤** -1. 检查结果集或者事务是否未关闭。 -2. 关闭所有的结果集或者事务。 +检查结果集或者事务是否未关闭。 + +关闭所有的结果集或者事务。 + +## 14800050 获取订阅服务失败 + +**错误信息** + +Failed to obtain subscription service. + +**错误描述** + +获取订阅服务失败。 + +**可能原因** + +当前平台不支持订阅服务。 + +**处理步骤** + +需要在当前平台部署订阅服务。 + +## 14801001 上下文环境非Stage模型 + +**错误信息** + + Only supported in stage mode. + +**错误描述** + +该操作仅支持Stage模型。 + +**可能原因** + +当前上下文环境非Stage模型。 + +**处理步骤** + +切换当前上下文环境,使用Stage模型。 + +## 14801002 storeConfig中传入的dataGroupId参数非法 + +**错误信息** + +The data group id is not valid. + +**错误描述** + +使用非法dataGroupId参数。 + +**可能原因** + +使用的dataGroupId不是从应用市场正常申请的。 + +**处理步骤** + +从应用市场申请dataGroupId,并正确传入该参数。 + +## 14800051 分布式表类型不匹配 + +**错误信息** + +The type of the distributed table does not match. + +**错误描述** + +对同一数据库表设置的分布式表类型前后不一致。 + +**可能原因** + +对同一数据库表设置的分布式表类型前后不一致,分布式表类型可见[DistributedType](../apis/js-apis-data-relationalStore.md#distributedtype10)。 + +**处理步骤** + +对同一数据库表设置的分布式表类型保持一致,属于端端同步的分布式表不可再设置为用于端云的同步表。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md b/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md index bd7edf5760e8b30bbc6350aa10a91f36f0e3ebd0..395699533fb2373072579f01d305492cb3af11ce 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @@ -18,11 +18,15 @@ The DataShareHelper is not initialized successfully. 1. 创建DataShareHelper时,接口createDataHelper的入参uri不正确。 2. 创建DataShareHelper时,接口createDataHelper的入参context不正确。 +3. 创建DataShareHelper时,客户端从后台拉起DataShareExtension时,未配置后台拉起权限。 **处理步骤** 1. 咨询DataShare服务端提供者,获取正确的uri路径。 2. DataShare仅支持Stage模型,检查context是否为Stage模型的context。 +3. 检查客户端是否有数据的读或者写权限,具体步骤如下: + (1) 找到数据提供者包名,在uri的path里面找,例如:uri = "datashareproxy://com.acts.ohos.data.datasharetest/test"。 + (2) 根据包名找到配置,例如:bm dump --bundle-name com.acts.ohos.data.datasharetest,在里面找到DataShareExtension的配置,确认数据访问者是否有readPermission或writePermission中配置的权限. ## 15700011 添加/删除模板异常 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md index 9ce9ce18fed30455f5da33e35a495caf36d01cc6..c01a2749edb34f4313eb5a9ef9d0184a94d3fd74 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md @@ -12,19 +12,19 @@ Location service is unavailable. **错误描述** -位置服务不可用,位置服务相关的接口无法调用. +位置服务不可用,位置服务相关的接口无法调用。 **可能原因** -1.位置服务启动异常,导致应用和位置服务子系统通信失败,导致位置服务不可用. +1.位置服务启动异常,导致应用和位置服务子系统通信失败,导致位置服务不可用。 -2.GNSS芯片初始化失败导致GNSS定位功能失效. +2.GNSS芯片初始化失败导致GNSS定位功能失效。 -3.网络定位服务异常,导致网络定位功能失效. +3.网络定位服务异常,导致网络定位功能失效。 **处理步骤** -请停止调用该接口. +请停止调用该接口。 ## 3301100 位置功能的开关未开启导致功能失败 @@ -34,17 +34,17 @@ The location switch is off. **错误描述** -位置功能的开关未开启导致功能失败. +位置功能的开关未开启导致功能失败。 **可能原因** -位置功能的开关未开启,导致持续定位,单次定位等基本功能不可用. +位置功能的开关未开启,导致持续定位,单次定位等基本功能不可用。 **处理步骤** -请提示用户开启位置功能的开关. +请提示用户开启位置功能的开关。 -## 3301200 定位失败,未获取到定位结果 +## 3301200 定位失败,未获取到定位结果 **错误信息** @@ -52,17 +52,17 @@ Failed to obtain the geographical location. **错误描述** -定位失败,未获取到定位结果. +定位失败,未获取到定位结果。 **可能原因** -1.GNSS信号弱,导致定位超时. +1.GNSS信号弱,导致定位超时。 -2.网络定位异常导致定位超时. +2.网络定位异常导致定位超时。 **处理步骤** -请重新发起定位请求. +请重新发起定位请求。 ## 3301300 逆地理编码查询失败 @@ -72,15 +72,15 @@ Reverse geocoding query failed. **错误描述** -逆地理编码查询失败. +逆地理编码查询失败。 **可能原因** -数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧. +数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧。 **处理步骤** -请重试逆地理编码查询. +请重试逆地理编码查询。 ## 3301400 地理编码查询失败 @@ -90,15 +90,15 @@ Geocoding query failed. **错误描述** -地理编码查询失败. +地理编码查询失败。 **可能原因** -数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧. +数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧。 **处理步骤** -请重试地理编码查询. +请重试地理编码查询。 ## 3301500 区域信息(包含国家码)查询失败 @@ -108,15 +108,15 @@ Failed to query the area information. **错误描述** -区域信息(包含国家码)查询失败. +区域信息(包含国家码)查询失败。 **可能原因** -未查询到正确的区域信息. +未查询到正确的区域信息。 **处理步骤** -请停止调用查询区域码的接口. +请停止调用查询区域码的接口。 ## 3301600 地理围栏操作失败 @@ -126,17 +126,17 @@ Failed to operate the geofence. **错误描述** -地理围栏操作失败,包含添加,删除,暂停和恢复等操作. +地理围栏操作失败,包含添加,删除,暂停和恢复等操作。 **可能原因** -1.GNSS芯片不支持地理围栏功能. +1.GNSS芯片不支持地理围栏功能。 -2.底层业务逻辑异常导致操作地理围栏失败. +2.底层业务逻辑异常导致操作地理围栏失败。 **处理步骤** -请停止调用地理围栏操作接口. +请停止调用地理围栏操作接口。 ## 3301700 请求无响应 @@ -146,16 +146,38 @@ No response to the request. **错误描述** -某些异步请求需要用户点击按钮确认,或者需要GNSS芯片和网络服务器响应,这些场景下未收到响应导致业务失败. +某些异步请求需要用户点击按钮确认,或者需要GNSS芯片和网络服务器响应,这些场景下未收到响应导致业务失败。 **可能原因** -1.用户未点击按钮确认. +1.用户未点击按钮确认。 -2.GNSS芯片未响应. +2.GNSS芯片未响应。 -3.网络服务器未响应. +3.网络服务器未响应。 **处理步骤** -请停止调用相关接口. \ No newline at end of file +请停止调用相关接口。 + +## 3301800 启动WiFi或蓝牙扫描失败 + +**错误信息** + +Failed to start WiFi or Bluetooth scanning. + +**错误描述** + +在订阅WiFi蓝牙扫描信息时,可能会先启动WiFi蓝牙扫描,如果启动扫描失败则会返回错误码给APP。 + +**可能原因** + +1.WiFi或蓝牙服务内部错误导致启动扫描失败。 + +2.低电量场景下,受功耗管控,导致无法发起扫描。 + +3.WiFi或蓝牙开关未开启。 + +**处理步骤** + +重新关闭开启WiFi或蓝牙开关。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-net-policy.md b/zh-cn/application-dev/reference/errorcodes/errorcode-net-policy.md index fba4b50282ddac53ac67a44f7f3216fe9c3734ed..6db232c05a517ad9db2144fbe0d2ed8d0686faaf 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-net-policy.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-net-policy.md @@ -1,4 +1,4 @@ -# netpolicy错误码 +# 策略管理错误码 > **说明:** > diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-net-statistics.md b/zh-cn/application-dev/reference/errorcodes/errorcode-net-statistics.md index 1ac4a00513d81bb2a24cf4d246d434b488636a1e..152e3f3b95f595c7eb0b166bcf678a978f570a02 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-net-statistics.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-net-statistics.md @@ -1,4 +1,4 @@ -# statistics错误码 +# 流量管理错误码 > **说明:** > diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-net-vpn.md b/zh-cn/application-dev/reference/errorcodes/errorcode-net-vpn.md new file mode 100644 index 0000000000000000000000000000000000000000..d46bb9d5ecef1b72da9ae03a369767463b0b3f03 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-net-vpn.md @@ -0,0 +1,61 @@ +# VPN错误码 + +> **说明:** +> +> 以下仅介绍本模块特有错误码,通用错误码请参考[通用错误码说明文档](errorcode-universal.md)。 + +## 2203001 VPN创建失败 + +**错误信息** + +VPN creation denied, please check the user type. + +**错误描述** + +拒绝创建VPN,请检测当前用户的类型。 + +**可能原因** + +登录系统的用户类型不匹配, GUEST用户不能调用setUp接口。 + +**处理步骤** + +检查当前登录系统用户的类型。 + + +## 2203002 VPN已存在 + +**错误信息** + +VPN exist already, please execute destroy first. + +**错误描述** + +VPN连接已存在,请先调用destroy接口销毁VPN连接。 + +**可能原因** + +VPN已经被创建。 + +**处理步骤** + +先执行destory接口,再调用该接口。 + + +## 2203004 无效描述符 + +**错误信息** + +Invalid socket file descriptor. + +**错误描述** + +无效的文件描述符。 + +**可能原因** + +tcp链路建立失败。 + +**处理步骤** + +检查socket链路是否建立成功。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md b/zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md index 071575710ca79ca294017cbf906527e06cbe7d15..92ef788b526bfb11000c4f0396602883dc31a88c 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @@ -22,4 +22,58 @@ Failed to delete preferences file. **处理步骤** 1. 检查文件名称是否正确。 -2. 检查文件路径是否正确。 \ No newline at end of file +2. 检查文件路径是否正确。 + +## 15500019 获取订阅服务失败 + +**错误信息** + +Failed to obtain subscription service. + +**错误描述** + +进行进程间订阅时,获取订阅服务失败。 + +**可能原因** + +当前平台不支持订阅服务。 + +**处理步骤** + +需要在当前平台部署订阅服务。 + +## 15501001 上下文环境非Stage模型 + +**错误信息** + + Only supported in stage mode. + +**错误描述** + +该操作仅支持Stage模型。 + +**可能原因** + +当前上下文环境非Stage模型。 + +**处理步骤** + +请切换当前上下文环境,使用Stage模型。 + +## 15501002 Options中传入的dataGroupId参数非法 + +**错误信息** + +The data group id is not valid. + +**错误描述** + +使用非法dataGroupId参数。 + +**可能原因** + +使用的dataGroupId不是从应用市场正常申请的。 + +**处理步骤** + +应用从应用市场申请dataGroupId,并正确传入该参数。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-apis/Readme-CN.md b/zh-cn/application-dev/reference/native-apis/Readme-CN.md index e3bc11d96020f0556ac02ca15cdfb3be0c69da76..ca14570f8c6c8989b36fa8fc5ee57f81de78a93f 100644 --- a/zh-cn/application-dev/reference/native-apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/native-apis/Readme-CN.md @@ -44,11 +44,17 @@ - [drawing_text_typography.h](drawing__text__typography_8h.md) - [drawing_types.h](drawing__types_8h.md) - [external_window.h](external__window_8h.md) + - [image_mdk.h](image__mdk_8h.md) + - [image_mdk_common.h](image__mdk__common_8h.md) + - [image_pixel_map_mdk.h](image__pixel__map__mdk_8h.md) - [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) + - [image_receiver_mdk.h](image__receiver__mdk_8h.md) + - [image_source_mdk.h](image__source__mdk_8h.md) - [log.h](log_8h.md) - [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) @@ -104,8 +110,23 @@ - [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) - [OHExtDataHandle](_o_h_ext_data_handle.md) - [OHHDRMetaData](_o_h_h_d_r_meta_data.md) + - [OHOS::Media::OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) + - [OHOS::Media::OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) + - [OHOS::Media::OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) + - [OhosImageDecodingOps](_ohos_image_decoding_ops.md) + - [OhosImageReceiverInfo](_ohos_image_receiver_info.md) + - [OhosImageRegion](_ohos_image_region.md) + - [OhosImageSize](_ohos_image_size.md) + - [OhosImageSource](_ohos_image_source.md) + - [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) + - [OhosImageSourceInfo](_ohos_image_source_info.md) + - [OhosImageSourceOps](_ohos_image_source_ops.md) + - [OhosImageSourceProperty](_ohos_image_source_property.md) + - [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md) + - [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) + - [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) - [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) - - [OhosPixelMapInfo](_ohos_pixel_map_info.md) + - [OhosPixelMapInfos](_ohos_pixel_map_infos.md) - [RawFileDescriptor](_raw_file_descriptor.md) - [Region](_region.md) - [Rect](_rect.md) diff --git a/zh-cn/application-dev/reference/native-apis/_mind_spore.md b/zh-cn/application-dev/reference/native-apis/_mind_spore.md index 5a39e666d0951b461e9a3112e635d49e3986f300..6274c710321d5802bcd4be4cba627eb3430fa80b 100644 --- a/zh-cn/application-dev/reference/native-apis/_mind_spore.md +++ b/zh-cn/application-dev/reference/native-apis/_mind_spore.md @@ -109,6 +109,7 @@ | [OH_AI_DeviceInfoSetFrequency](#oh_ai_deviceinfosetfrequency) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, int frequency) | 设置NPU的频率,仅NPU设备可用。 | | [OH_AI_DeviceInfoGetFrequency](#oh_ai_deviceinfogetfrequency) (const [OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info) | 获取NPU的频率类型,仅NPU设备可用。 | | [OH_AI_GetAllNNRTDeviceDescs](#oh_ai_getallnnrtdevicedescs) (size_t \*num) | 获取系统中所有NNRT硬件设备的描述信息。 | +| [OH_AI_GetElementOfNNRTDeviceDescs](#oh_ai_getelementofnnrtdevicedescs) (NNRTDeviceDesc \*descs, size_t index) | 获取NNRT设备描述信息数组中的元素指针。 | | [OH_AI_DestroyAllNNRTDeviceDescs](#oh_ai_destroyallnnrtdevicedescs) ([NNRTDeviceDesc](#nnrtdevicedesc) \*\*desc) | 销毁从[OH_AI_GetAllNNRTDeviceDescs](#oh_ai_getallnnrtdevicedescs)获取的NNRT描写信息实例数组。 | | [OH_AI_GetDeviceIdFromNNRTDeviceDesc](#oh_ai_getdeviceidfromnnrtdevicedesc) (const [NNRTDeviceDesc](#nnrtdevicedesc) \*desc) | 从特定的NNRT设备描述信息实例获取NNRT设备ID。注意,此ID只对NNRT有效。 | | [OH_AI_GetNameFromNNRTDeviceDesc](#oh_ai_getnamefromnnrtdevicedesc) (const [NNRTDeviceDesc](#nnrtdevicedesc) \*desc) | 从特定的NNRT设备描述信息实例获取NNRT设备名称。 | @@ -131,6 +132,7 @@ | [OH_AI_ModelGetOutputs](#oh_ai_modelgetoutputs) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model) | 获取模型的输出张量数组结构体。 | | [OH_AI_ModelGetInputByTensorName](#oh_ai_modelgetinputbytensorname) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*tensor_name) | 通过张量名获取模型的输入张量。 | | [OH_AI_ModelGetOutputByTensorName](#oh_ai_modelgetoutputbytensorname) (const [OH_AI_ModelHandle](#oh_ai_modelhandle) model, const char \*tensor_name) | 通过张量名获取模型的输出张量。 | +| [OH_AI_DeviceInfoAddExtension](#oh_ai_deviceinfoaddextension) ([OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle) device_info, const char \*name, const char \*value, size_t value_size) | 向设备信息中添加键/值对形式的扩展配置。只对NNRT设备信息有效。 | | [OH_AI_TensorCreate](#oh_ai_tensorcreate) (const char \*name, [OH_AI_DataType](#oh_ai_datatype) type, const int64_t \*shape, size_t shape_num, const void \*data, size_t data_len) | 创建一个张量对象。 | | [OH_AI_TensorDestroy](#oh_ai_tensordestroy) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) \*tensor) | 释放张量对象。 | | [OH_AI_TensorClone](#oh_ai_tensorclone) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | 深拷贝一个张量。 | @@ -147,7 +149,7 @@ | [OH_AI_TensorGetMutableData](#oh_ai_tensorgetmutabledata) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | 获取可变的张量数据指针。如果数据为空则会开辟内存。 | | [OH_AI_TensorGetElementNum](#oh_ai_tensorgetelementnum) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | 获取张量元素数量。 | | [OH_AI_TensorGetDataSize](#oh_ai_tensorgetdatasize) (const [OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor) | 获取张量中的数据的字节数大小。 | - +| [OH_AI_TensorSetUserData](#oh_ai_tensorsetuserdata) ([OH_AI_TensorHandle](#oh_ai_tensorhandle) tensor, void \*data, size_t data_size) | 设置张量为用户自行管理的数据。此接口常用于复用用户数据作为模型输入,可减少一次数据拷贝。 | ## 宏定义说明 @@ -1951,3 +1953,90 @@ OH_AI_API void OH_AI_TensorSetShape (OH_AI_TensorHandle tensor, const int64_t * | tensor | 张量对象句柄。 | | shape | 形状数组。 | | shape_num | 张量形状数组长度。 | + + +### OH_AI_TensorSetUserData() + +``` +OH_AI_API OH_AI_Status OH_AI_TensorSetUserData (OH_AI_TensorHandle tensor, void * data, size_t data_size ) +``` + +**描述:** + +设置张量为用户自行管理的数据。 + +此接口常用于复用用户数据作为模型输入,可减少一次数据拷贝。 + +注意:此数据对于张量来说是外部数据,张量销毁时不会主动释放,由调用者负责释放。另外,在此张量使用过程中,调用者须确保此数据有效。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| tensor | 张量对象句柄。 | +| data | 用户数据首地址。 | +| data_size | 用户数据长度。 | + +**返回:** + +执行状态码。若成功返回OH_AI_STATUS_SUCCESS,否则返回具体错误码。 + +**起始版本:** + +10 + + +### OH_AI_DeviceInfoAddExtension() + +``` +OH_AI_API OH_AI_Status OH_AI_DeviceInfoAddExtension (OH_AI_DeviceInfoHandle device_info, const char * name, const char * value, size_t value_size ) +``` + +**描述:** + +向设备信息中添加键/值对形式的扩展配置。只对NNRT设备信息有效。 + +注意:当前仅支持{"CachePath": "YourCachePath"},{"CacheVersion": "YouCacheVersion"}, {"QuantParam": "YourQuantConfig"} 三种键值对配置,用户根据使用情况替换具体的值。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| device_info | 指向设备信息实例的[OH_AI_DeviceInfoHandle](#oh_ai_deviceinfohandle)。 | +| name | 单个扩展项的键,格式为C字符串。 | +| value | 单个扩展项的值内容首地址。 | +| value_size | 单个扩展项的值内容长度。 | + +**返回:** + +**OH_AI_Status** 执行状态码,若成功返回OH_AI_STATUS_SUCCESS,失败则返回具体错误码。 + +**起始版本:** + +10 + + +### OH_AI_GetElementOfNNRTDeviceDescs() + +``` +OH_AI_API NNRTDeviceDesc* OH_AI_GetElementOfNNRTDeviceDescs (NNRTDeviceDesc * descs, size_t index ) +``` + +**描述:** + +获取NNRT设备描述信息数组中的元素指针。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| descs | NNRT设备描述信息数组。 | +| index | 数组元素索引。 | + +**返回:** + +NNRT设备描述信息类型指针。 + +**起始版本:** + +10 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___cursor.md b/zh-cn/application-dev/reference/native-apis/_o_h___cursor.md index f5f8d5d51951c7516fd39ab47be8e483edeb216b..e3316c9efed934b74a76b4ef8359e0bfd6ee37e1 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___cursor.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___cursor.md @@ -36,4 +36,4 @@ | [getReal](_r_d_b.md#getreal) | 函数指针,以double形式获取当前行中指定列的值。 | | [getBlob](_r_d_b.md#getblob) | 函数指针,以字节数组的形式获取当前行中指定列的值。 | | [isNull](_r_d_b.md#isnull-12) | 函数指针,检查当前行中指定列的值是否为null。 | -| [close](_r_d_b.md#close) | 函数指针,关闭结果集。 | +| [destroy](_r_d_b.md#destroy-14) | 函数指针,关闭结果集。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md index 52acf0c68b759c06a6d9287806e90bef3dd8697a..6280ad94b20d45818034c8c7e17a003e2ad3ce8b 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md @@ -1,9 +1,11 @@ # Native XComponent +## 概述 + 描述ArkUI XComponent持有的surface和触摸事件,该事件可用于EGL/OpenGLES和媒体数据输入,并显示在ArkUI XComponent上,具体使用请参考[XComponent开发指导](../../napi/xcomponent-guidelines.md)。 -**起始版本:** +**起始版本:** 8 @@ -13,103 +15,113 @@ ### 文件 -| 文件名称 | 描述 | -| ------------------------------------------------------------ | ------------------------------------ | -| [native_interface_xcomponent.h](native__interface__xcomponent_8h.md) | 声明用于访问Native XComponent的API。
引用文件: | +| 名称 | 描述 | +| ---------------------------------------- | ---------------------------------------- | +| [native_interface_xcomponent.h](native__interface__xcomponent_8h.md) | 声明用于访问Native XComponent的API。
引用文件:<ace/xcomponent/native_interface_xcomponent.h> | +| [native_xcomponent_key_event.h](native__xcomponent__key__event_8h.md) | 声明用于访问Native XComponent键盘事件所使用到的枚举类型。
引用文件:<ace/xcomponent/native_xcomponent_key_event.h> | ### 结构体 -| 结构体名称 | 描述 | -| ------------------------------------------------------------ | ----------------------------------- | -| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | 触摸事件中触摸点的信息。 | -| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | 触摸事件。 | -| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | 鼠标事件。 | +| 名称 | 描述 | +| ---------------------------------------- | --------------------- | +| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | 触摸事件中触摸点的信息。 | +| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | 触摸事件。 | +| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | 鼠标事件。 | | [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) | 注册surface生命周期和触摸事件回调。 | -| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | 注册鼠标事件的回调。 | +| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | 注册鼠标事件的回调。 | ### 类型定义 -| 类型定义名称 | 描述 | -| ------------------------------------------------------------ | ----------------------------------- | -| [OH_NativeXComponent](#oh_nativexcomponent) | 提供封装的OH_NativeXComponent实例。 | -| [OH_NativeXComponent_Callback](#oh_nativexcomponent_callback) | 注册surface生命周期和触摸事件回调。 | -| [OH_NativeXComponent_MouseEvent_Callback](#oh_nativexcomponent_mouseevent_callback) | 注册鼠标事件的回调。 | +| 名称 | 描述 | +| ---------------------------------------- | ------------------------------------ | +| [OH_NativeXComponent](#oh_nativexcomponent) | 提供封装的OH_NativeXComponent实例。 | +| [OH_NativeXComponent_Callback](#oh_nativexcomponent_callback) | 注册surface生命周期和触摸事件回调。 | +| [OH_NativeXComponent_MouseEvent_Callback](#oh_nativexcomponent_mouseevent_callback) | 注册鼠标事件的回调。 | +| [OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) | 提供封装的OH_NativeXComponent_KeyEvent实例。 | ### 枚举 -| 枚举名称 | 描述 | -| ------------------------------------------------------------ | ------------------------------------ | -| {OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0,
OH_NATIVEXCOMPONENT_RESULT_FAILED = -1,
OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2 } | [枚举](#anonymous-enum)API访问状态。 | -| [OH_NativeXComponent_TouchEventType](#oh_nativexcomponent_toucheventtype) {
OH_NATIVEXCOMPONENT_DOWN = 0,
OH_NATIVEXCOMPONENT_UP,
OH_NATIVEXCOMPONENT_MOVE,
OH_NATIVEXCOMPONENT_CANCEL,
OH_NATIVEXCOMPONENT_UNKNOWN } | 触摸事件类型。 | -| [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 } | 触摸点工具类型。 | -| [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_MouseEventAction](#oh_nativexcomponent_mouseeventaction) {
OH_NATIVEXCOMPONENT_MOUSE_NONE = 0,
OH_NATIVEXCOMPONENT_MOUSE_PRESS,
OH_NATIVEXCOMPONENT_MOUSE_RELEASE,
OH_NATIVEXCOMPONENT_MOUSE_MOVE } | 鼠标事件动作。 | -| [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 } | 鼠标事件按键。 | +| 名称 | 描述 | +| ---------------------------------------- | ---------- | +| { OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0, OH_NATIVEXCOMPONENT_RESULT_FAILED = -1, OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2 } | 枚举API访问状态。 | +| [OH_NativeXComponent_TouchEventType](#oh_nativexcomponent_toucheventtype) {
OH_NATIVEXCOMPONENT_DOWN = 0, OH_NATIVEXCOMPONENT_UP, OH_NATIVEXCOMPONENT_MOVE, OH_NATIVEXCOMPONENT_CANCEL,
OH_NATIVEXCOMPONENT_UNKNOWN
} | 触摸事件类型。 | +| [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
} | 触摸点工具类型。 | +| [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
} | 触摸事件源类型。 | +| [OH_NativeXComponent_MouseEventAction](#oh_nativexcomponent_mouseeventaction) { OH_NATIVEXCOMPONENT_MOUSE_NONE = 0, OH_NATIVEXCOMPONENT_MOUSE_PRESS, OH_NATIVEXCOMPONENT_MOUSE_RELEASE, OH_NATIVEXCOMPONENT_MOUSE_MOVE } | 鼠标事件动作。 | +| [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
} | 鼠标事件按键。 | +| [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
} | 按键事件的键码。 | +| [OH_NativeXComponent_KeyAction](#oh_nativexcomponent_keyaction) { OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN = -1, OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN = 0, OH_NATIVEXCOMPONENT_KEY_ACTION_UP } | 按键事件动作。 | ### 函数 -| 函数名称 | 描述 | -| ------------------------------------------------------------ | -------------------------------------------------- | -| [OH_NativeXComponent_GetXComponentId](#oh_nativexcomponent_getxcomponentid) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, char \*id, uint64_t \*size) | 获取ArkUI XComponent的id。 | -| [OH_NativeXComponent_GetXComponentSize](#oh_nativexcomponent_getxcomponentsize) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, uint64_t \*width, uint64_t \*height) | 获取ArkUI XComponent持有的surface的大小。 | -| [OH_NativeXComponent_GetXComponentOffset](#oh_nativexcomponent_getxcomponentoffset) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, double \*x, double \*y) | 获取ArkUI XComponent组件相对屏幕左上顶点的偏移量。 | -| [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) | 获取ArkUI XComponent调度的触摸事件。 | -| [OH_NativeXComponent_GetTouchPointToolType](#oh_nativexcomponent_gettouchpointtooltype) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, [OH_NativeXComponent_TouchPointToolType](#oh_nativexcomponent_touchpointtooltype) \*toolType) | 获取ArkUI XComponent触摸点工具类型。 | -| [OH_NativeXComponent_GetTouchPointTiltX](#oh_nativexcomponent_gettouchpointtiltx) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltX) | 获取ArkUI XComponent触摸点倾斜与X轴角度。 | -| [OH_NativeXComponent_GetTouchPointTiltY](#oh_nativexcomponent_gettouchpointtilty) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltY) | 获取ArkUI XComponent触摸点倾斜与Y轴角度。 | -| [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) | 获取ArkUI XComponent调度的鼠标事件 | -| [OH_NativeXComponent_RegisterCallback](#oh_nativexcomponent_registercallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) \*callback) | 为此OH_NativeXComponent实例注册回调。 | -| [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) | 为此OH_NativeXComponent实例注册鼠标事件回调。 | +| 名称 | 描述 | +| ---------------------------------------- | -------------------------------------- | +| [OH_NativeXComponent_GetXComponentId](#oh_nativexcomponent_getxcomponentid) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, char \*id, uint64_t \*size) | 获取ArkUI XComponent的id。 | +| [OH_NativeXComponent_GetXComponentSize](#oh_nativexcomponent_getxcomponentsize) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, uint64_t \*width, uint64_t \*height) | 获取ArkUI XComponent持有的surface的大小。 | +| [OH_NativeXComponent_GetXComponentOffset](#oh_nativexcomponent_getxcomponentoffset) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, const void \*window, double \*x, double \*y) | 获取ArkUI XComponent组件相对屏幕左上顶点的偏移量。 | +| [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) | 获取ArkUI XComponent调度的触摸事件。 | +| [OH_NativeXComponent_GetTouchPointToolType](#oh_nativexcomponent_gettouchpointtooltype) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, [OH_NativeXComponent_TouchPointToolType](#oh_nativexcomponent_touchpointtooltype) \*toolType) | 获取ArkUI XComponent触摸点工具类型。 | +| [OH_NativeXComponent_GetTouchPointTiltX](#oh_nativexcomponent_gettouchpointtiltx) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltX) | 获取ArkUI XComponent触摸点倾斜与X轴角度。 | +| [OH_NativeXComponent_GetTouchPointTiltY](#oh_nativexcomponent_gettouchpointtilty) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, uint32_t pointIndex, float \*tiltY) | 获取ArkUI XComponent触摸点倾斜与Y轴角度。 | +| [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) | 获取ArkUI XComponent调度的鼠标事件。 | +| [OH_NativeXComponent_RegisterCallback](#oh_nativexcomponent_registercallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) \*callback) | 为此OH_NativeXComponent实例注册回调。 | +| [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) | 为此OH_NativeXComponent实例注册鼠标事件回调。 | +| [OH_NativeXComponent_RegisterFocusEventCallback](#oh_nativexcomponent_registerfocuseventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](#oh_nativexcomponent) \*component, void \*window)) | 为此OH_NativeXComponent实例注册获焦事件回调。 | +| [OH_NativeXComponent_RegisterKeyEventCallback](#oh_nativexcomponent_registerkeyeventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](#oh_nativexcomponent) \*component, void \*window)) | 为此OH_NativeXComponent实例注册按键事件回调。 | +| [OH_NativeXComponent_RegisterBlurEventCallback](#oh_nativexcomponent_registerblureventcallback) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, void(\*callback)([OH_NativeXComponent](#oh_nativexcomponent) \*component, void \*window)) | 为此OH_NativeXComponent实例注册失焦事件回调。 | +| [OH_NativeXComponent_GetKeyEvent](#oh_nativexcomponent_getkeyevent) ([OH_NativeXComponent](#oh_nativexcomponent) \*component, [OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*\*keyEvent) | 获取ArkUI XComponent调度的按键事件。 | +| [OH_NativeXComponent_GetKeyEventAction](#oh_nativexcomponent_getkeyeventaction) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_KeyAction](#oh_nativexcomponent_keyaction) \*action) | 获取传入按键事件的动作。 | +| [OH_NativeXComponent_GetKeyEventCode](#oh_nativexcomponent_getkeyeventcode) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_KeyCode](#oh_nativexcomponent_keycode) \*code) | 获取传入按键事件的按键码。 | +| [OH_NativeXComponent_GetKeyEventSourceType](#oh_nativexcomponent_getkeyeventsourcetype) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, [OH_NativeXComponent_EventSourceType](#oh_nativexcomponent_eventsourcetype) \*sourceType) | 获取传入按键事件的事件源类型。 | +| [OH_NativeXComponent_GetKeyEventDeviceId](#oh_nativexcomponent_getkeyeventdeviceid) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, int64_t \*deviceId) | 获取传入按键事件的设备id。 | +| [OH_NativeXComponent_GetKeyEventTimeStamp](#oh_nativexcomponent_getkeyeventtimestamp) ([OH_NativeXComponent_KeyEvent](#oh_nativexcomponent_keyevent) \*keyEvent, int64_t \*timeStamp) | 获取传入按键事件的时间戳。 | ### 变量 -| 变量名称 | 描述 | -| ------------------------------------------------------------ | ----------------------------------------- | -| [OH_XCOMPONENT_ID_LEN_MAX](#oh_xcomponent_id_len_max) = 128 | ArkUI XComponent的id最大长度。 | -| [OH_MAX_TOUCH_POINTS_NUMBER](#oh_max_touch_points_number) = 10 | 触摸事件中的可识别的触摸点个数最大值。 | -| [OH_NativeXComponent_TouchPoint::id](#id-12) = 0 | 手指的唯一标识符。 | -| [OH_NativeXComponent_TouchPoint::screenX](#screenx-13) = 0.0 | 触摸点相对于XComponent所在应用窗口左上角的x坐标。 | -| [OH_NativeXComponent_TouchPoint::screenY](#screeny-13) = 0.0 | 触摸点相对于XComponent所在应用窗口左上角的y坐标。 | -| [OH_NativeXComponent_TouchPoint::x](#x-13) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | -| [OH_NativeXComponent_TouchPoint::y](#y-13) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | -| [OH_NativeXComponent_TouchPoint::type](#type-12) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | -| [OH_NativeXComponent_TouchPoint::size](#size-12) = 0.0 | 指垫和屏幕之间的接触面积。 | -| [OH_NativeXComponent_TouchPoint::force](#force-12) = 0.0 | 当前触摸事件的压力。 | -| [OH_NativeXComponent_TouchPoint::timeStamp](#timestamp-12) = 0 | 当前触摸事件的时间戳。 | -| [OH_NativeXComponent_TouchPoint::isPressed](#ispressed) = false | 当前点是否被按下。 | -| [OH_NativeXComponent_TouchEvent::id](#id-22) = 0 | 手指的唯一标识符。 | -| [OH_NativeXComponent_TouchEvent::screenX](#screenx-23) = 0.0 | 触摸点相对于XComponent所在应用窗口左上角的x坐标。 | -| [OH_NativeXComponent_TouchEvent::screenY](#screeny-23) = 0.0 | 触摸点相对于XComponent所在应用窗口左上角的y坐标。 | -| [OH_NativeXComponent_TouchEvent::x](#x-23) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | -| [OH_NativeXComponent_TouchEvent::y](#y-23) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | -| [OH_NativeXComponent_TouchEvent::type](#type-22) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | -| [OH_NativeXComponent_TouchEvent::size](#size-22) = 0.0 | 指垫和屏幕之间的接触面积。 | -| [OH_NativeXComponent_TouchEvent::force](#force-22) = 0.0 | 当前触摸事件的压力。 | -| [OH_NativeXComponent_TouchEvent::deviceId](#deviceid) = 0 | 产生当前触摸事件的设备的ID。 | -| [OH_NativeXComponent_TouchEvent::timeStamp](#timestamp-22) = 0 | 当前触摸事件的时间戳。 | -| [OH_NativeXComponent_TouchEvent::touchPoints](#touchpoints) [OH_MAX_TOUCH_POINTS_NUMBER] | 当前触摸点的数组。 | -| [OH_NativeXComponent_TouchEvent::numPoints](#numpoints) = 0 | 当前接触点的数量。 | -| [OH_NativeXComponent_MouseEvent::x](#x-33) = 0.0 | 点击触点相对于当前组件左上角的x轴坐标。 | -| [OH_NativeXComponent_MouseEvent::y](#y-33) = 0.0 | 点击触点相对于当前组件左上角的y轴坐标。 | -| [OH_NativeXComponent_MouseEvent::screenX](#screenx-33) = 0.0 | 点击触点相对于XComponent所在应用窗口左上角的x轴坐标。 | -| [OH_NativeXComponent_MouseEvent::screenY](#screeny-33) = 0.0 | 点击触点相对于XComponent所在应用窗口左上角的y轴坐标。 | -| [OH_NativeXComponent_MouseEvent::timestamp](#timestamp) = 0 | 当前鼠标事件的时间戳。 | -| [OH_NativeXComponent_MouseEvent::action](#action) = [OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE](#oh_nativexcomponent_mouseeventaction) | 当前鼠标事件动作。 | -| [OH_NativeXComponent_MouseEvent::button](#button) = [OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON](#oh_nativexcomponent_mouseeventbutton) | 鼠标事件按键。 | -| [OH_NativeXComponent_Callback::OnSurfaceCreated](#onsurfacecreated) | 创建surface时调用。 | -| [OH_NativeXComponent_Callback::OnSurfaceChanged](#onsurfacechanged) | 当surface改变时调用。 | -| [OH_NativeXComponent_Callback::OnSurfaceDestroyed](#onsurfacedestroyed) | 当surface被销毁时调用。 | -| [OH_NativeXComponent_Callback::DispatchTouchEvent](#dispatchtouchevent) | 当触摸事件被触发时调用。 | -| [OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent](#dispatchmouseevent) | 当鼠标事件被触发时调用。 | -| [OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent](#dispatchhoverevent) | 当悬停事件被触发时调用。 | - - -## 详细描述 +| 名称 | 描述 | +| ---------------------------------------- | ------------------------------ | +| **OH_XCOMPONENT_ID_LEN_MAX** = 128 | ArkUI XComponent的id最大长度。 | +| **OH_MAX_TOUCH_POINTS_NUMBER** = 10 | 触摸事件中的可识别的触摸点个数最大值。 | +| [OH_NativeXComponent_TouchPoint::id](#id-12) = 0 | 手指的唯一标识符。 | +| [OH_NativeXComponent_TouchPoint::screenX](#screenx-13) = 0.0 | 触摸点相对于XComponent所在应用窗口左上角的x坐标。 | +| [OH_NativeXComponent_TouchPoint::screenY](#screeny-13) = 0.0 | 触摸点相对于XComponent所在应用窗口左上角的y坐标。 | +| [OH_NativeXComponent_TouchPoint::x](#x-13) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | +| [OH_NativeXComponent_TouchPoint::y](#y-13) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | +| [OH_NativeXComponent_TouchPoint::type](#type-12) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | +| [OH_NativeXComponent_TouchPoint::size](#size-12) = 0.0 | 指垫和屏幕之间的接触面积。 | +| [OH_NativeXComponent_TouchPoint::force](#force-12) = 0.0 | 当前触摸事件的压力。 | +| [OH_NativeXComponent_TouchPoint::timeStamp](#timestamp-12) = 0 | 当前触摸事件的时间戳。 | +| [OH_NativeXComponent_TouchPoint::isPressed](#ispressed) = false | 当前点是否被按下。 | +| [OH_NativeXComponent_TouchEvent::id](#id-22) = 0 | 手指的唯一标识符。 | +| [OH_NativeXComponent_TouchEvent::screenX](#screenx-23) = 0.0 | 触摸点相对于屏幕左边缘的x坐标。 | +| [OH_NativeXComponent_TouchEvent::screenY](#screeny-23) = 0.0 | 触摸点相对于屏幕上边缘的y坐标。 | +| [OH_NativeXComponent_TouchEvent::x](#x-23) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | +| [OH_NativeXComponent_TouchEvent::y](#y-23) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | +| [OH_NativeXComponent_TouchEvent::type](#type-22) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | +| [OH_NativeXComponent_TouchEvent::size](#size-22) = 0.0 | 指垫和屏幕之间的接触面积。 | +| [OH_NativeXComponent_TouchEvent::force](#force-22) = 0.0 | 当前触摸事件的压力。 | +| [OH_NativeXComponent_TouchEvent::deviceId](#deviceid) = 0 | 产生当前触摸事件的设备的ID。 | +| [OH_NativeXComponent_TouchEvent::timeStamp](#timestamp-22) = 0 | 当前触摸事件的时间戳。 | +| [OH_NativeXComponent_TouchEvent::touchPoints](#touchpoints) [OH_MAX_TOUCH_POINTS_NUMBER] | 当前触摸点的数组。 | +| [OH_NativeXComponent_TouchEvent::numPoints](#numpoints) = 0 | 当前接触点的数量。 | +| [OH_NativeXComponent_MouseEvent::x](#x-33) = 0.0 | 点击触点相对于当前组件左上角的x轴坐标。 | +| [OH_NativeXComponent_MouseEvent::y](#y-33)= 0.0 | 点击触点相对于当前组件左上角的y轴坐标。 | +| [OH_NativeXComponent_MouseEvent::screenX](#screenx-33)= 0.0 | 点击触点相对于屏幕左上角的x轴坐标。 | +| [OH_NativeXComponent_MouseEvent::screenY](#screeny-33)= 0.0 | 点击触点相对于屏幕左上角的y轴坐标。 | +| [OH_NativeXComponent_MouseEvent::timestamp](#timestamp)= 0 | 当前鼠标事件的时间戳。 | +| [OH_NativeXComponent_MouseEvent::action](#action)= [OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE](#oh_nativexcomponent_mouseeventaction) | 当前鼠标事件动作。 | +| [OH_NativeXComponent_MouseEvent::button](#button)= [OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON](#oh_nativexcomponent_mouseeventbutton) | 鼠标事件按键。 | +| [OH_NativeXComponent_Callback::OnSurfaceCreated](#onsurfacecreated) | 创建surface时调用。 | +| [OH_NativeXComponent_Callback::OnSurfaceChanged](#onsurfacechanged) | 当surface改变时调用。 | +| [OH_NativeXComponent_Callback::OnSurfaceDestroyed](#onsurfacedestroyed) | 当surface被销毁时调用。 | +| [OH_NativeXComponent_Callback::DispatchTouchEvent](#dispatchtouchevent) | 当触摸事件被触发时调用。 | +| [OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent](#dispatchmouseevent) | 当鼠标事件被触发时调用。 | +| [OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent](#dispatchhoverevent) | 当悬停事件被触发时调用。 | ## 类型定义说明 @@ -117,12 +129,11 @@ ### OH_NativeXComponent - ``` typedef struct OH_NativeXComponent OH_NativeXComponent ``` -**描述:** +**描述:** 提供封装的OH_NativeXComponent实例。 @@ -133,12 +144,11 @@ typedef struct OH_NativeXComponent OH_NativeXComponent ### OH_NativeXComponent_Callback - ``` typedef struct OH_NativeXComponent_Callback OH_NativeXComponent_Callback ``` -**描述:** +**描述:** 注册surface生命周期和触摸事件回调。 @@ -147,14 +157,28 @@ typedef struct OH_NativeXComponent_Callback OH_NativeXComponent_Callback 8 -### OH_NativeXComponent_MouseEvent_Callback +### OH_NativeXComponent_KeyEvent +``` +typedef struct OH_NativeXComponent_KeyEvent OH_NativeXComponent_KeyEvent +``` + +**描述:** + +提供封装的OH_NativeXComponent_KeyEvent实例。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_MouseEvent_Callback ``` typedef struct OH_NativeXComponent_MouseEvent_Callback OH_NativeXComponent_MouseEvent_Callback ``` -**描述:** +**描述:** 注册鼠标事件的回调。 @@ -168,17 +192,16 @@ typedef struct OH_NativeXComponent_MouseEvent_Callback OH_NativeXComponent_Mouse ### anonymous enum - ``` anonymous enum ``` -**描述:** +**描述:** 枚举API访问状态。 -| 枚举值 | 描述 | -| ---------------------------------------- | ---------- | +| 枚举值 | 描述 | +| ---------------------------------------- | ----- | | OH_NATIVEXCOMPONENT_RESULT_SUCCESS | 成功结果。 | | OH_NATIVEXCOMPONENT_RESULT_FAILED | 失败结果。 | | OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER | 无效参数。 | @@ -187,47 +210,415 @@ anonymous enum 8 -### OH_NativeXComponent_EventSourceType - -OH_NativeXComponent_EventSourceType +### OH_NativeXComponent_EventSourceType ``` enum OH_NativeXComponent_EventSourceType ``` -**描述:** +**描述:** 触摸事件源类型。 -| 枚举值 | 描述 | -| -------- | -------- | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN | 未知的输入源类型。 | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_MOUSE | 表示输入源生成鼠标多点触摸事件。 | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHSCREEN | 表示输入源生成一个触摸屏多点触摸事件。 | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_TOUCHPAD | 表示输入源生成一个触摸板多点触摸事件。 | -| OH_NATIVEXCOMPONENT_SOURCE_TYPE_JOYSTICK | 表示输入源生成一个操纵杆多点触摸事件。 | +| 枚举值 | 描述 | +| ---------------------------------------- | ------------------- | +| OH_NATIVEXCOMPONENT_SOURCE_TYPE_UNKNOWN | 未知的输入源类型。 | +| 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 | 表示输入源生成一个键盘事件。 | **起始版本:** 9 -### OH_NativeXComponent_MouseEventAction +### OH_NativeXComponent_KeyAction + +``` +enum OH_NativeXComponent_KeyAction +``` + +**描述:** + +按键事件动作。 + +| 枚举值 | 描述 | +| -------------------------------------- | -------- | +| OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN | 未知的按键动作。 | +| OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN | 按键按下动作。 | +| OH_NATIVEXCOMPONENT_KEY_ACTION_UP | 按键抬起动作。 | + +**起始版本:** + +10 + + +### OH_NativeXComponent_KeyCode + +``` +enum OH_NativeXComponent_KeyCode +``` + +**描述:** + +按键事件的键码。 + +| 枚举值 | 描述 | +| ---------------------------- | --------------------------- | +| KEY_UNKNOWN | 未知按键 | +| KEY_FN | 功能(Fn)键 | +| KEY_HOME | 功能(Home)键 | +| KEY_BACK | 返回键 | +| KEY_MEDIA_PLAY_PAUSE | 多媒体键 播放/暂停 | +| KEY_MEDIA_STOP | 多媒体键 停止 | +| KEY_MEDIA_NEXT | 多媒体键 下一首 | +| KEY_MEDIA_PREVIOUS | 多媒体键 上一首 | +| KEY_MEDIA_REWIND | 多媒体键 快退 | +| KEY_MEDIA_FAST_FORWARD | 多媒体键 快进 | +| KEY_VOLUME_UP | 音量增加键 | +| KEY_VOLUME_DOWN | 音量减小键 | +| KEY_POWER | 电源键 | +| KEY_CAMERA | 拍照键 | +| KEY_VOLUME_MUTE | 扬声器静音键 | +| KEY_MUTE | 话筒静音键 | +| KEY_BRIGHTNESS_UP | 亮度调节按键 调亮 | +| KEY_BRIGHTNESS_DOWN | 亮度调节按键 调暗 | +| KEY_0 | 按键'0' | +| KEY_1 | 按键'1' | +| KEY_2 | 按键'2' | +| KEY_3 | 按键'3' | +| KEY_4 | 按键'4' | +| KEY_5 | 按键'5' | +| KEY_6 | 按键'6' | +| KEY_7 | 按键'7' | +| KEY_8 | 按键'8' | +| KEY_9 | 按键'9' | +| KEY_STAR | 按键'\*' | +| KEY_POUND | 按键'\#' | +| KEY_DPAD_UP | 导航键 向上 | +| KEY_DPAD_DOWN | 导航键 向下 | +| KEY_DPAD_LEFT | 导航键 向左 | +| KEY_DPAD_RIGHT | 导航键 向右 | +| KEY_DPAD_CENTER | 导航键 确定键 | +| KEY_A | 按键'A' | +| KEY_B | 按键'B' | +| KEY_C | 按键'C' | +| KEY_D | 按键'D' | +| KEY_E | 按键'E' | +| KEY_F | 按键'F' | +| KEY_G | 按键'G' | +| KEY_H | 按键'H' | +| KEY_I | 按键'I' | +| KEY_J | 按键'J' | +| KEY_K | 按键'K' | +| KEY_L | 按键'L' | +| KEY_M | 按键'M' | +| KEY_N | 按键'N' | +| KEY_O | 按键'O' | +| KEY_P | 按键'P' | +| KEY_Q | 按键'Q' | +| KEY_R | 按键'R' | +| KEY_S | 按键'S' | +| KEY_T | 按键'T' | +| KEY_U | 按键'U' | +| KEY_V | 按键'V' | +| KEY_W | 按键'W' | +| KEY_X | 按键'X' | +| KEY_Y | 按键'Y' | +| KEY_Z | 按键'Z' | +| KEY_COMMA | 按键',' | +| KEY_PERIOD | 按键'.' | +| KEY_ALT_LEFT | 左Alt键 | +| KEY_ALT_RIGHT | 右Alt键 | +| KEY_SHIFT_LEFT | 左Shift键 | +| KEY_SHIFT_RIGHT | 右Shift键 | +| KEY_TAB | Tab键 | +| KEY_SPACE | 空格键 | +| KEY_SYM | 符号修改器按键 | +| KEY_EXPLORER | 浏览器功能键,此键用于启动浏览器应用程序。 | +| KEY_ENVELOPE | 电子邮件功能键,此键用于启动电子邮件应用程序。 | +| KEY_ENTER | 回车键 | +| KEY_DEL | 退格键 | +| KEY_GRAVE | 按键'‘’ | +| KEY_MINUS | 按键'-' | +| KEY_EQUALS | 按键'=' | +| KEY_LEFT_BRACKET | 按键'[' | +| KEY_RIGHT_BRACKET | 按键']' | +| KEY_BACKSLASH | 按键'\' | +| KEY_SEMICOLON | 按键';' | +| KEY_APOSTROPHE | 按键''' (单引号) | +| KEY_SLASH | 按键'/' | +| KEY_AT | 按键'\@' | +| KEY_PLUS | 按键'+' | +| KEY_MENU | 菜单键 | +| KEY_PAGE_UP | 向上翻页键 | +| KEY_PAGE_DOWN | 向下翻页键 | +| KEY_ESCAPE | ESC键 | +| KEY_FORWARD_DEL | 删除键 | +| KEY_CTRL_LEFT | 左Ctrl键 | +| KEY_CTRL_RIGHT | 右Ctrl键 | +| KEY_CAPS_LOCK | 大写锁定键 | +| KEY_SCROLL_LOCK | 滚动锁定键 | +| KEY_META_LEFT | 左元修改器键 | +| KEY_META_RIGHT | 右元修改器键 | +| KEY_FUNCTION | 功能键 | +| KEY_SYSRQ | 系统请求/打印屏幕键 | +| KEY_BREAK | Break/Pause键 | +| KEY_MOVE_HOME | 光标移动到开始键 | +| KEY_MOVE_END | 光标移动到末尾键 | +| KEY_INSERT | 插入键 | +| KEY_FORWARD | 前进键 | +| KEY_MEDIA_PLAY | 多媒体键 播放 | +| KEY_MEDIA_PAUSE | 多媒体键 暂停 | +| KEY_MEDIA_CLOSE | 多媒体键 关闭 | +| KEY_MEDIA_EJECT | 多媒体键 弹出 | +| KEY_MEDIA_RECORD | 多媒体键 录音 | +| KEY_F1 | 按键'F1' | +| KEY_F2 | 按键'F2' | +| KEY_F3 | 按键'F3' | +| KEY_F4 | 按键'F4' | +| KEY_F5 | 按键'F5' | +| KEY_F6 | 按键'F6' | +| KEY_F7 | 按键'F7' | +| KEY_F8 | 按键'F8' | +| KEY_F9 | 按键'F9' | +| KEY_F10 | 按键'F10' | +| KEY_F11 | 按键'F11' | +| KEY_F12 | 按键'F12' | +| KEY_NUM_LOCK | 小键盘锁 | +| KEY_NUMPAD_0 | 小键盘按键'0' | +| KEY_NUMPAD_1 | 小键盘按键'1' | +| KEY_NUMPAD_2 | 小键盘按键'2' | +| KEY_NUMPAD_3 | 小键盘按键'3' | +| KEY_NUMPAD_4 | 小键盘按键'4' | +| KEY_NUMPAD_5 | 小键盘按键'5' | +| KEY_NUMPAD_6 | 小键盘按键'6' | +| KEY_NUMPAD_7 | 小键盘按键'7' | +| KEY_NUMPAD_8 | 小键盘按键'8' | +| KEY_NUMPAD_9 | 小键盘按键'9' | +| KEY_NUMPAD_DIVIDE | 小键盘按键'/' | +| KEY_NUMPAD_MULTIPLY | 小键盘按键'\*' | +| KEY_NUMPAD_SUBTRACT | 小键盘按键'-' | +| KEY_NUMPAD_ADD | 小键盘按键'+' | +| KEY_NUMPAD_DOT | 小键盘按键'.' | +| KEY_NUMPAD_COMMA | 小键盘按键',' | +| KEY_NUMPAD_ENTER | 小键盘按键回车 | +| KEY_NUMPAD_EQUALS | 小键盘按键'=' | +| KEY_NUMPAD_LEFT_PAREN | 小键盘按键'(' | +| KEY_NUMPAD_RIGHT_PAREN | 小键盘按键')' | +| KEY_VIRTUAL_MULTITASK | 虚拟多任务键 | +| KEY_SLEEP | 睡眠键 | +| KEY_ZENKAKU_HANKAKU | 日文全宽/半宽键 | +| KEY_102ND | 102nd按键 | +| KEY_RO | 日文Ro键 | +| KEY_KATAKANA | 日文片假名键 | +| KEY_HIRAGANA | 日文平假名键 | +| KEY_HENKAN | 日文转换键 | +| KEY_KATAKANA_HIRAGANA | 日语片假名/平假名键 | +| KEY_MUHENKAN | 日文非转换键 | +| KEY_LINEFEED | 换行键 | +| KEY_MACRO | 宏键 | +| KEY_NUMPAD_PLUSMINUS | 数字键盘上的加号/减号键 | +| KEY_SCALE | 扩展键 | +| KEY_HANGUEL | 日文韩语键 | +| KEY_HANJA | 日文汉语键 | +| KEY_YEN | 日元键 | +| KEY_STOP | 停止键 | +| KEY_AGAIN | 重复键 | +| KEY_PROPS | 道具键 | +| KEY_UNDO | 撤消键 | +| KEY_COPY | 复制键 | +| KEY_OPEN | 打开键 | +| KEY_PASTE | 粘贴键 | +| KEY_FIND | 查找键 | +| KEY_CUT | 剪切键 | +| KEY_HELP | 帮助键 | +| KEY_CALC | 计算器特殊功能键,用于启动计算器应用程序 | +| KEY_FILE | 文件按键 | +| KEY_BOOKMARKS | 书签键 | +| KEY_NEXT | 下一个按键 | +| KEY_PLAYPAUSE | 播放/暂停键 | +| KEY_PREVIOUS | 上一个按键 | +| KEY_STOPCD | CD停止键 | +| KEY_CONFIG | 配置键 | +| KEY_REFRESH | 刷新键 | +| KEY_EXIT | 退出键 | +| KEY_EDIT | 编辑键 | +| KEY_SCROLLUP | 向上滚动键 | +| KEY_SCROLLDOWN | 向下滚动键 | +| KEY_NEW | 新建键 | +| KEY_REDO | 恢复键 | +| KEY_CLOSE | 关闭键 | +| KEY_PLAY | 播放键 | +| KEY_BASSBOOST | 低音增强键 | +| KEY_PRINT | 打印键 | +| KEY_CHAT | 聊天键 | +| KEY_FINANCE | 金融键 | +| KEY_CANCEL | 取消键 | +| KEY_KBDILLUM_TOGGLE | 键盘灯光切换键 | +| KEY_KBDILLUM_DOWN | 键盘灯光调亮键 | +| KEY_KBDILLUM_UP | 键盘灯光调暗键 | +| KEY_SEND | 发送键 | +| KEY_REPLY | 答复键 | +| KEY_FORWARDMAIL | 邮件转发键 | +| KEY_SAVE | 保存键 | +| KEY_DOCUMENTS | 文件键 | +| KEY_VIDEO_NEXT | 下一个视频键 | +| KEY_VIDEO_PREV | 上一个视频键 | +| KEY_BRIGHTNESS_CYCLE | 背光渐变键 | +| KEY_BRIGHTNESS_ZERO | 亮度调节为0键 | +| KEY_DISPLAY_OFF | 显示关闭键 | +| KEY_BTN_MISC | 游戏手柄上的各种按键 | +| KEY_GOTO | 进入键 | +| KEY_INFO | 信息查看键 | +| KEY_PROGRAM | 程序键 | +| KEY_PVR | 个人录像机(PVR)键 | +| KEY_SUBTITLE | 字幕键 | +| KEY_FULL_SCREEN | 全屏键 | +| KEY_KEYBOARD | 键盘 | +| KEY_ASPECT_RATIO | 屏幕纵横比调节键 | +| KEY_PC | 端口控制键 | +| KEY_TV | TV键 | +| KEY_TV2 | TV键2 | +| KEY_VCR | 录像机开启键 | +| KEY_VCR2 | 录像机开启键2 | +| KEY_SAT | SIM卡应用工具包(SAT)键 | +| KEY_CD | CD键 | +| KEY_TAPE | 磁带键 | +| KEY_TUNER | 调谐器键 | +| KEY_PLAYER | 播放器键 | +| KEY_DVD | DVD键 | +| KEY_AUDIO | 音频键 | +| KEY_VIDEO | 视频键 | +| KEY_MEMO | 备忘录键 | +| KEY_CALENDAR | 日历键 | +| KEY_RED | 红色指示器 | +| KEY_GREEN | 绿色指示器 | +| KEY_YELLOW | 黄色指示器 | +| KEY_BLUE | 蓝色指示器 | +| KEY_CHANNELUP | 频道向上键 | +| KEY_CHANNELDOWN | 频道向下键 | +| KEY_LAST | 末尾键 | +| KEY_RESTART | 重启键 | +| KEY_SLOW | 慢速键 | +| KEY_SHUFFLE | 随机播放键 | +| KEY_VIDEOPHONE | 可视电话键 | +| KEY_GAMES | 游戏键 | +| KEY_ZOOMIN | 放大键 | +| KEY_ZOOMOUT | 缩小键 | +| KEY_ZOOMRESET | 缩放重置键 | +| KEY_WORDPROCESSOR | 文字处理键 | +| KEY_EDITOR | 编辑器键 | +| KEY_SPREADSHEET | 电子表格键 | +| KEY_GRAPHICSEDITOR | 图形编辑器键 | +| KEY_PRESENTATION | 演示文稿键 | +| KEY_DATABASE | 数据库键标 | +| KEY_NEWS | 新闻键 | +| KEY_VOICEMAIL | 语音信箱 | +| KEY_ADDRESSBOOK | 通讯簿 | +| KEY_MESSENGER | 通信键 | +| KEY_BRIGHTNESS_TOGGLE | 亮度切换键 | +| KEY_SPELLCHECK | AL拼写检查 | +| KEY_COFFEE | 终端锁/屏幕保护程序 | +| KEY_MEDIA_REPEAT | 媒体循环键 | +| KEY_IMAGES | 图像键 | +| KEY_BUTTONCONFIG | 按键配置键 | +| KEY_TASKMANAGER | 任务管理器 | +| KEY_JOURNAL | 日志按键 | +| KEY_CONTROLPANEL | 控制面板键 | +| KEY_APPSELECT | 应用程序选择键 | +| KEY_SCREENSAVER | 屏幕保护程序键 | +| KEY_ASSISTANT | 辅助键 | +| KEY_KBD_LAYOUT_NEXT | 下一个键盘布局键 | +| KEY_BRIGHTNESS_MIN | 最小亮度键 | +| KEY_BRIGHTNESS_MAX | 最大亮度键 | +| KEY_KBDINPUTASSIST_PREV | 键盘输入Assist_Previous | +| KEY_KBDINPUTASSIST_NEXT | 键盘输入Assist_Next | +| KEY_KBDINPUTASSIST_PREVGROUP | 键盘输入Assist_Previous | +| KEY_KBDINPUTASSIST_NEXTGROUP | 键盘输入Assist_Next | +| KEY_KBDINPUTASSIST_ACCEPT | 键盘输入Assist_Accept | +| KEY_KBDINPUTASSIST_CANCEL | 键盘输入Assist_Cancel | +| KEY_FRONT | 挡风玻璃除雾器开关 | +| KEY_SETUP | 设置键 | +| KEY_WAKEUP | 唤醒键 | +| KEY_SENDFILE | 发送文件按键 | +| KEY_DELETEFILE | 删除文件按键 | +| KEY_XFER | 文件传输(XFER)按键 | +| KEY_PROG1 | 程序键1 | +| KEY_PROG2 | 程序键2 | +| KEY_MSDOS | MS-DOS键(微软磁盘操作系统 | +| KEY_SCREENLOCK | 屏幕锁定键 | +| KEY_DIRECTION_ROTATE_DISPLAY | 方向旋转显示键 | +| KEY_CYCLEWINDOWS | Windows循环键 | +| KEY_COMPUTER | 按键 | +| KEY_EJECTCLOSECD | 弹出CD键 | +| KEY_ISO | ISO键 | +| KEY_MOVE | 移动键 | +| KEY_F13 | 按键'F13' | +| KEY_F14 | 按键'F14' | +| KEY_F15 | 按键'F15' | +| KEY_F16 | 按键'F16' | +| KEY_F17 | 按键'F17' | +| KEY_F18 | 按键'F18' | +| KEY_F19 | 按键'F19' | +| KEY_F20 | 按键'F20' | +| KEY_F21 | 按键'F21' | +| KEY_F22 | 按键'F22' | +| KEY_F23 | 按键'F23' | +| KEY_F24 | 按键'F24' | +| KEY_PROG3 | 程序键3 | +| KEY_PROG4 | 程序键4 | +| KEY_DASHBOARD | 仪表板 | +| KEY_SUSPEND | 挂起键 | +| KEY_HP | 高阶路径键 | +| KEY_SOUND | 音量键 | +| KEY_QUESTION | 疑问按键 | +| KEY_CONNECT | 连接键 | +| KEY_SPORT | 运动按键 | +| KEY_SHOP | 商城键 | +| KEY_ALTERASE | 交替键 | +| KEY_SWITCHVIDEOMODE | 在可用视频之间循环输出(监视器/LCD/TV输出/等) | +| KEY_BATTERY | 电池按键 | +| KEY_BLUETOOTH | 蓝牙按键 | +| KEY_WLAN | 无线局域网 | +| KEY_UWB | 超宽带(UWB) | +| KEY_WWAN_WIMAX | WWAN WiMAX按键 | +| KEY_RFKILL | 控制所有收音机的键 | +| KEY_CHANNEL | 向上频道键 | +| KEY_BTN_0 | 按键0 | +| KEY_BTN_1 | 按键1 | +| KEY_BTN_2 | 按键2 | +| KEY_BTN_3 | 按键3 | +| KEY_BTN_4 | 按键4 | +| KEY_BTN_5 | 按键5 | +| KEY_BTN_6 | 按键6 | +| KEY_BTN_7 | 按键7 | +| KEY_BTN_8 | 按键8 | +| KEY_BTN_9 | 按键9 | + +**起始版本:** + +10 + + +### OH_NativeXComponent_MouseEventAction ``` enum OH_NativeXComponent_MouseEventAction ``` -**描述:** +**描述:** -鼠标事件动作. +鼠标事件动作。 -| 枚举值 | 描述 | -| --------------------------------- | -------------------------------- | -| OH_NATIVEXCOMPONENT_MOUSE_NONE | 无效鼠标事件 。 | -| OH_NATIVEXCOMPONENT_MOUSE_PRESS | 鼠标按键按下时触发鼠标事件。 | -| OH_NATIVEXCOMPONENT_MOUSE_RELEASE | 鼠标按键松开时触发鼠标事件。 | +| 枚举值 | 描述 | +| --------------------------------- | ---------------- | +| OH_NATIVEXCOMPONENT_MOUSE_NONE | 无效鼠标事件 。 | +| OH_NATIVEXCOMPONENT_MOUSE_PRESS | 鼠标按键按下时触发鼠标事件。 | +| OH_NATIVEXCOMPONENT_MOUSE_RELEASE | 鼠标按键松开时触发鼠标事件。 | | OH_NATIVEXCOMPONENT_MOUSE_MOVE | 鼠标在屏幕上移动时触发鼠标事件。 | **起始版本:** @@ -237,21 +628,20 @@ enum OH_NativeXComponent_MouseEventAction ### OH_NativeXComponent_MouseEventButton - ``` enum OH_NativeXComponent_MouseEventButton ``` -**描述:** +**描述:** 鼠标事件按键。 -| 枚举值 | 描述 | -| ---------------------------------- | ---------------------------------- | -| OH_NATIVEXCOMPONENT_NONE_BUTTON | 鼠标无按键操作时触发鼠标事件。 | -| OH_NATIVEXCOMPONENT_LEFT_BUTTON | 按下鼠标左键时触发鼠标事件。 | -| OH_NATIVEXCOMPONENT_RIGHT_BUTTON | 按下鼠标右键时触发鼠标事件。 | -| OH_NATIVEXCOMPONENT_MIDDLE_BUTTON | 按下鼠标中键时触发鼠标事件。 | +| 枚举值 | 描述 | +| ---------------------------------- | ----------------- | +| OH_NATIVEXCOMPONENT_NONE_BUTTON | 鼠标无按键操作时触发鼠标事件。 | +| OH_NATIVEXCOMPONENT_LEFT_BUTTON | 按下鼠标左键时触发鼠标事件。 | +| OH_NATIVEXCOMPONENT_RIGHT_BUTTON | 按下鼠标右键时触发鼠标事件。 | +| OH_NATIVEXCOMPONENT_MIDDLE_BUTTON | 按下鼠标中键时触发鼠标事件。 | | OH_NATIVEXCOMPONENT_BACK_BUTTON | 按下鼠标左侧后退键时触发鼠标事件。 | | OH_NATIVEXCOMPONENT_FORWARD_BUTTON | 按下鼠标左侧前进键时触发鼠标事件。 | @@ -262,49 +652,48 @@ enum OH_NativeXComponent_MouseEventButton ### OH_NativeXComponent_TouchEventType - ``` enum OH_NativeXComponent_TouchEventType ``` -**描述:** +**描述:** 触摸事件类型。 -| 枚举值 | 描述 | -| --------------------------- | ------------------------------------------ | -| OH_NATIVEXCOMPONENT_DOWN | 手指按下时触发触摸事件。 | -| OH_NATIVEXCOMPONENT_UP | 手指抬起时触发触摸事件。 | +| 枚举值 | 描述 | +| --------------------------- | --------------------- | +| OH_NATIVEXCOMPONENT_DOWN | 手指按下时触发触摸事件。 | +| OH_NATIVEXCOMPONENT_UP | 手指抬起时触发触摸事件。 | | OH_NATIVEXCOMPONENT_MOVE | 手指按下状态下在屏幕上移动时触发触摸事件。 | -| OH_NATIVEXCOMPONENT_CANCEL | 触摸事件取消时触发事件。 | -| OH_NATIVEXCOMPONENT_UNKNOWN | 无效的触摸类型。 | +| OH_NATIVEXCOMPONENT_CANCEL | 触摸事件取消时触发事件。 | +| OH_NATIVEXCOMPONENT_UNKNOWN | 无效的触摸类型。 | **起始版本:** 8 -### OH_NativeXComponent_TouchPointToolType +### OH_NativeXComponent_TouchPointToolType ``` enum OH_NativeXComponent_TouchPointToolType ``` -**描述:** +**描述:** 触摸点工具类型 -| 枚举值 | 描述 | -| -------- | -------- | -| OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN | 无效的工具类型。 | -| 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 | 表示用晶状体。 | +| 枚举值 | 描述 | +| -------------------------------------- | -------- | +| OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN | 未识别工具类型。 | +| 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 | 表示用晶状体。 | **起始版本:** @@ -314,26 +703,181 @@ enum OH_NativeXComponent_TouchPointToolType ## 函数说明 -### OH_NativeXComponent_GetMouseEvent() +### OH_NativeXComponent_GetKeyEvent() + +``` +int32_t OH_NativeXComponent_GetKeyEvent (OH_NativeXComponent * component, OH_NativeXComponent_KeyEvent ** keyEvent ) +``` + +**描述:** + +获取ArkUI XComponent调度的按键事件。 + +**参数:** + +| 名称 | 描述 | +| --------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| keyEvent | 表示指向当前按键事件指针的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_GetKeyEventAction() + +``` +int32_t OH_NativeXComponent_GetKeyEventAction (OH_NativeXComponent_KeyEvent * keyEvent, OH_NativeXComponent_KeyAction * action ) +``` + +**描述:** + +获取传入按键事件的动作。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------------------------------------- | +| keyEvent | 表示指向OH_NativeXComponent_KeyEvent实例的指针。 | +| action | 表示指向按键事件动作的指针。 | +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_GetKeyEventCode() + +``` +int32_t OH_NativeXComponent_GetKeyEventCode (OH_NativeXComponent_KeyEvent * keyEvent, OH_NativeXComponent_KeyCode * code ) +``` + +**描述:** + +获取传入按键事件的按键码。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------------------------------------- | +| keyEvent | 表示指向OH_NativeXComponent_KeyEvent实例的指针。 | +| code | 表示指向按键事件按键码的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_GetKeyEventDeviceId() + +``` +int32_t OH_NativeXComponent_GetKeyEventDeviceId (OH_NativeXComponent_KeyEvent * keyEvent, int64_t * deviceId ) +``` + +**描述:** + +获取传入按键事件的设备id。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------------------------------------- | +| keyEvent | 表示指向OH_NativeXComponent_KeyEvent实例的指针。 | +| deviceId | 表示指向按键事件设备id的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_GetKeyEventSourceType() + +``` +int32_t OH_NativeXComponent_GetKeyEventSourceType (OH_NativeXComponent_KeyEvent * keyEvent, OH_NativeXComponent_EventSourceType * sourceType ) +``` + +**描述:** + +获取传入按键事件的事件源类型。 + +**参数:** + +| 名称 | 描述 | +| ---------- | -------------------------------------- | +| keyEvent | 表示指向OH_NativeXComponent_KeyEvent实例的指针。 | +| sourceType | 表示指向按键事件事件源类型的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_GetKeyEventTimeStamp() + +``` +int32_t OH_NativeXComponent_GetKeyEventTimeStamp (OH_NativeXComponent_KeyEvent * keyEvent, int64_t * timeStamp ) +``` + +**描述:** + +获取传入按键事件的时间戳。 + +**参数:** + +| 名称 | 描述 | +| --------- | -------------------------------------- | +| keyEvent | 表示指向OH_NativeXComponent_KeyEvent实例的指针。 | +| timeStamp | 表示指向按键事件时间戳的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_GetMouseEvent() ``` int32_t OH_NativeXComponent_GetMouseEvent (OH_NativeXComponent * component, const void * window, OH_NativeXComponent_MouseEvent * mouseEvent ) ``` -**描述:** +**描述:** 获取ArkUI XComponent调度的鼠标事件 -**参数:** +**参数:** -| Name | 描述 | -| ---------- | --------------------------------------- | +| 名称 | 描述 | +| ---------- | ----------------------------- | | component | 表示指向OH_NativeXComponent实例的指针。 | -| window | 表示NativeWindow句柄。 | -| mouseEvent | 指示指向当前鼠标事件的指针。 | +| window | 表示NativeWindow句柄 | +| mouseEvent | 指示指向当前鼠标事件的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -344,24 +888,23 @@ int32_t OH_NativeXComponent_GetMouseEvent (OH_NativeXComponent * component, cons ### OH_NativeXComponent_GetTouchEvent() - ``` int32_t OH_NativeXComponent_GetTouchEvent (OH_NativeXComponent * component, const void * window, OH_NativeXComponent_TouchEvent * touchEvent ) ``` -**描述:** +**描述:** 获取ArkUI XComponent调度的触摸事件。 -**参数:** +**参数:** -| Name | 描述 | -| ---------- | --------------------------------------- | +| 名称 | 描述 | +| ---------- | ----------------------------- | | component | 表示指向OH_NativeXComponent实例的指针。 | -| window | 表示NativeWindow句柄。 | -| touchEvent | 指示指向当前触摸事件的指针。 | +| window | 表示NativeWindow句柄。 | +| touchEvent | 指示指向当前触摸事件的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -369,26 +912,26 @@ int32_t OH_NativeXComponent_GetTouchEvent (OH_NativeXComponent * component, cons 8 -### OH_NativeXComponent_GetTouchPointTiltX() +### OH_NativeXComponent_GetTouchPointTiltX() ``` int32_t OH_NativeXComponent_GetTouchPointTiltX (OH_NativeXComponent * component, uint32_t pointIndex, float * tiltX ) ``` -**描述:** +**描述:** 获取ArkUI XComponent触摸点倾斜与X轴角度。 -**参数:** +**参数:** -| Name | 描述 | -| -------- | -------- | -| component | 表示指向OH_NativeXComponent实例的指针。 | -| pointIndex | 表示触摸点的指针索引。 | -| tiltX | 表示指向X倾斜度的指针。 | +| 名称 | 描述 | +| ---------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| pointIndex | 表示触摸点的指针索引。 | +| tiltX | 表示指向X倾斜度的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -399,24 +942,23 @@ int32_t OH_NativeXComponent_GetTouchPointTiltX (OH_NativeXComponent * component, ### 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 ) ``` -**描述:** +**描述:** 获取ArkUI XComponent触摸点倾斜与Y轴角度。 -**参数:** +**参数:** -| Name | 描述 | -| -------- | -------- | -| component | 表示指向OH_NativeXComponent实例的指针。 | -| pointIndex | 表示触摸点的指针索引。 | -| tiltY | 表示指向Y倾斜度的指针。 | +| 名称 | 描述 | +| ---------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| pointIndex | 表示触摸点的指针索引。 | +| tiltY | 表示指向Y倾斜度的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -427,24 +969,23 @@ int32_t OH_NativeXComponent_GetTouchPointTiltX (OH_NativeXComponent * component, ### OH_NativeXComponent_GetTouchPointToolType() - ``` int32_t OH_NativeXComponent_GetTouchPointToolType (OH_NativeXComponent * component, uint32_t pointIndex, OH_NativeXComponent_TouchPointToolType * toolType ) ``` -**描述:** +**描述:** 获取ArkUI XComponent触摸点工具类型。 -**参数:** +**参数:** -| Name | 描述 | -| -------- | -------- | -| component | 表示指向OH_NativeXComponent实例的指针。 | -| pointIndex | 表示触摸点的指针索引。 | -| toolType | 表示指向工具类型的指针。 | +| 名称 | 描述 | +| ---------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| pointIndex | 表示触摸点的指针索引。 | +| toolType | 表示指向工具类型的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -455,24 +996,23 @@ int32_t OH_NativeXComponent_GetTouchPointToolType (OH_NativeXComponent * compone ### OH_NativeXComponent_GetXComponentId() - ``` int32_t OH_NativeXComponent_GetXComponentId (OH_NativeXComponent * component, char * id, uint64_t * size ) ``` -**描述:** +**描述:** 获取ArkUI XComponent的id。 -**参数:** +**参数:** -| Name | 描述 | -| --------- | ------------------------------------------------------------ | -| component | 表示指向OH_NativeXComponent实例的指针。 | -| id | 指示用于保存此OH_NativeXComponent实例的ID的字符缓冲区。 请注意,空终止符将附加到字符缓冲区,因此字符缓冲区的大小应至少比真实id长度大一个单位。 建议字符缓冲区的大小为[OH_XCOMPONENT_ID_LEN_MAX + 1]。 | -| size | 指示指向id长度的指针。 | +| 名称 | 描述 | +| --------- | ---------------------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| id | 指示用于保存此OH_NativeXComponent实例的ID的字符缓冲区。 请注意,空终止符将附加到字符缓冲区,因此字符缓冲区的大小应至少比真实id长度大一个单位。 建议字符缓冲区的大小为[OH_XCOMPONENT_ID_LEN_MAX + 1]。 | +| size | 指示指向id长度的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -483,25 +1023,24 @@ int32_t OH_NativeXComponent_GetXComponentId (OH_NativeXComponent * component, ch ### OH_NativeXComponent_GetXComponentOffset() - ``` int32_t OH_NativeXComponent_GetXComponentOffset (OH_NativeXComponent * component, const void * window, double * x, double * y ) ``` -**描述:** +**描述:** 获取ArkUI XComponent组件相对屏幕左上顶点的偏移量。 -**参数:** +**参数:** -| Name | 描述 | -| --------- | --------------------------------------- | +| 名称 | 描述 | +| --------- | ----------------------------- | | component | 表示指向OH_NativeXComponent实例的指针。 | -| window | 表示NativeWindow句柄。 | -| x | 指示指向当前surface的x坐标的指针。 | -| y | 指示指向当前surface的y坐标的指针。 | +| window | 表示NativeWindow句柄。 | +| x | 指示指向当前surface的x坐标的指针。 | +| y | 指示指向当前surface的y坐标的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -512,25 +1051,24 @@ int32_t OH_NativeXComponent_GetXComponentOffset (OH_NativeXComponent * component ### OH_NativeXComponent_GetXComponentSize() - ``` int32_t OH_NativeXComponent_GetXComponentSize (OH_NativeXComponent * component, const void * window, uint64_t * width, uint64_t * height ) ``` -**描述:** +**描述:** 获取ArkUI XComponent持有的surface的大小。 -**参数:** +**参数:** -| Name | 描述 | -| --------- | --------------------------------------- | +| 名称 | 描述 | +| --------- | ----------------------------- | | component | 表示指向OH_NativeXComponent实例的指针。 | -| window | 表示NativeWindow句柄。 | -| width | 指示指向当前surface宽度的指针。 | -| height | 指示指向当前surface高度的指针。 | +| window | 表示NativeWindow句柄。 | +| width | 指示指向当前surface宽度的指针。 | +| height | 指示指向当前surface高度的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -539,25 +1077,50 @@ int32_t OH_NativeXComponent_GetXComponentSize (OH_NativeXComponent * component, 8 -### OH_NativeXComponent_RegisterCallback() +### OH_NativeXComponent_RegisterBlurEventCallback() + +``` +int32_t OH_NativeXComponent_RegisterBlurEventCallback (OH_NativeXComponent * component, void(*)(OH_NativeXComponent *component, void *window) callback ) +``` + +**描述:** + +为此OH_NativeXComponent实例注册失焦事件回调。 +**参数:** + +| 名称 | 描述 | +| --------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| callback | 指示指向失焦事件回调的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +8 + + +### OH_NativeXComponent_RegisterCallback() ``` int32_t OH_NativeXComponent_RegisterCallback (OH_NativeXComponent * component, OH_NativeXComponent_Callback * callback ) ``` -**描述:** +**描述:** 为此OH_NativeXComponent实例注册回调。 -**参数:** +**参数:** -| Name | 描述 | -| --------- | --------------------------------------------- | -| component | 表示指向OH_NativeXComponent实例的指针。 | -| callback | 指示指向surface生命周期和触摸事件回调的指针。 | +| 名称 | 描述 | +| --------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| callback | 指示指向surface生命周期和触摸事件回调的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -566,25 +1129,76 @@ int32_t OH_NativeXComponent_RegisterCallback (OH_NativeXComponent * component, O 8 -### OH_NativeXComponent_RegisterMouseEventCallback() +### OH_NativeXComponent_RegisterFocusEventCallback() + +``` +int32_t OH_NativeXComponent_RegisterFocusEventCallback (OH_NativeXComponent * component, void(*)(OH_NativeXComponent *component, void *window) callback ) +``` +**描述:** + +为此OH_NativeXComponent实例注册获焦事件回调。 + +**参数:** + +| 名称 | 描述 | +| --------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| callback | 指示指向获焦事件回调的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_RegisterKeyEventCallback() + +``` +int32_t OH_NativeXComponent_RegisterKeyEventCallback (OH_NativeXComponent * component, void(*)(OH_NativeXComponent *component, void *window) callback ) +``` + +**描述:** + +为此OH_NativeXComponent实例注册按键事件回调。 + +**参数:** + +| 名称 | 描述 | +| --------- | ----------------------------- | +| component | 表示指向OH_NativeXComponent实例的指针。 | +| callback | 指示指向按键事件回调的指针。 | + +**返回:** + +返回执行的状态代码。 + +**起始版本:** + +10 + + +### OH_NativeXComponent_RegisterMouseEventCallback() ``` int32_t OH_NativeXComponent_RegisterMouseEventCallback (OH_NativeXComponent * component, OH_NativeXComponent_MouseEvent_Callback * callback ) ``` -**描述:** +**描述:** 为此OH_NativeXComponent实例注册鼠标事件回调。 -**参数:** +**参数:** -| Name | 描述 | -| --------- | --------------------------------------- | +| 名称 | 描述 | +| --------- | ----------------------------- | | component | 表示指向OH_NativeXComponent实例的指针。 | -| callback | 指示指向鼠标事件回调的指针。 | +| callback | 指示指向鼠标事件回调的指针。 | -**返回:** +**返回:** 返回执行的状态代码。 @@ -598,23 +1212,25 @@ int32_t OH_NativeXComponent_RegisterMouseEventCallback (OH_NativeXComponent * co ### OH_XCOMPONENT_ID_LEN_MAX - ``` const uint32_t OH_XCOMPONENT_ID_LEN_MAX = 128 ``` + **描述:** + ArkUI XComponent的id最大长度。 + **起始版本:** + 8 ### OH_MAX_TOUCH_POINTS_NUMBER - ``` const uint32_t OH_MAX_TOUCH_POINTS_NUMBER = 10 ``` @@ -630,12 +1246,11 @@ const uint32_t OH_MAX_TOUCH_POINTS_NUMBER = 10 ### action - ``` OH_NativeXComponent_MouseEventAction OH_NativeXComponent_MouseEvent::action ``` -**描述:** +**描述:** 当前鼠标事件动作。 @@ -646,14 +1261,13 @@ OH_NativeXComponent_MouseEventAction OH_NativeXComponent_MouseEvent::action ### button - ``` OH_NativeXComponent_MouseEventButton OH_NativeXComponent_MouseEvent::button ``` -**描述:** +**描述:** -鼠标事件按键 +鼠标事件按键。 **起始版本:** @@ -662,12 +1276,11 @@ OH_NativeXComponent_MouseEventButton OH_NativeXComponent_MouseEvent::button ### deviceId - ``` int64_t OH_NativeXComponent_TouchEvent::deviceId = 0 ``` -**描述:** +**描述:** 产生当前触摸事件的设备的ID。 @@ -678,12 +1291,11 @@ int64_t OH_NativeXComponent_TouchEvent::deviceId = 0 ### DispatchHoverEvent - ``` void(* OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent) (OH_NativeXComponent *component, bool isHover) ``` -**描述:** +**描述:** 当悬停事件被触发时调用。 @@ -694,12 +1306,11 @@ void(* OH_NativeXComponent_MouseEvent_Callback::DispatchHoverEvent) (OH_NativeXC ### DispatchMouseEvent - ``` void(* OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent) (OH_NativeXComponent *component, void *window) ``` -**描述:** +**描述:** 当鼠标事件被触发时调用。 @@ -710,12 +1321,11 @@ void(* OH_NativeXComponent_MouseEvent_Callback::DispatchMouseEvent) (OH_NativeXC ### DispatchTouchEvent - ``` void(* OH_NativeXComponent_Callback::DispatchTouchEvent) (OH_NativeXComponent *component, void *window) ``` -**描述:** +**描述:** 当触摸事件被触发时调用。 @@ -726,12 +1336,11 @@ void(* OH_NativeXComponent_Callback::DispatchTouchEvent) (OH_NativeXComponent *c ### force [1/2] - ``` float OH_NativeXComponent_TouchPoint::force = 0.0 ``` -**描述:** +**描述:** 当前触摸事件的压力。 @@ -742,12 +1351,11 @@ float OH_NativeXComponent_TouchPoint::force = 0.0 ### force [2/2] - ``` float OH_NativeXComponent_TouchEvent::force = 0.0 ``` -**描述:** +**描述:** 当前触摸事件的压力。 @@ -758,12 +1366,11 @@ float OH_NativeXComponent_TouchEvent::force = 0.0 ### id [1/2] - ``` int32_t OH_NativeXComponent_TouchPoint::id = 0 ``` -**描述:** +**描述:** 手指的唯一标识符。 @@ -774,12 +1381,11 @@ int32_t OH_NativeXComponent_TouchPoint::id = 0 ### id [2/2] - ``` int32_t OH_NativeXComponent_TouchEvent::id = 0 ``` -**描述:** +**描述:** 手指的唯一标识符。 @@ -790,12 +1396,11 @@ int32_t OH_NativeXComponent_TouchEvent::id = 0 ### isPressed - ``` bool OH_NativeXComponent_TouchPoint::isPressed = false ``` -**描述:** +**描述:** 当前点是否被按下。 @@ -806,12 +1411,11 @@ bool OH_NativeXComponent_TouchPoint::isPressed = false ### numPoints - ``` uint32_t OH_NativeXComponent_TouchEvent::numPoints = 0 ``` -**描述:** +**描述:** 当前接触点的数量。 @@ -822,12 +1426,11 @@ uint32_t OH_NativeXComponent_TouchEvent::numPoints = 0 ### OnSurfaceChanged - ``` void(* OH_NativeXComponent_Callback::OnSurfaceChanged) (OH_NativeXComponent *component, void *window) ``` -**描述:** +**描述:** 当surface改变时调用。 @@ -838,12 +1441,11 @@ void(* OH_NativeXComponent_Callback::OnSurfaceChanged) (OH_NativeXComponent *com ### OnSurfaceCreated - ``` void(* OH_NativeXComponent_Callback::OnSurfaceCreated) (OH_NativeXComponent *component, void *window) ``` -**描述:** +**描述:** 创建surface时调用。 @@ -854,12 +1456,11 @@ void(* OH_NativeXComponent_Callback::OnSurfaceCreated) (OH_NativeXComponent *com ### OnSurfaceDestroyed - ``` void(* OH_NativeXComponent_Callback::OnSurfaceDestroyed) (OH_NativeXComponent *component, void *window) ``` -**描述:** +**描述:** 当surface被销毁时调用。 @@ -870,12 +1471,11 @@ void(* OH_NativeXComponent_Callback::OnSurfaceDestroyed) (OH_NativeXComponent *c ### screenX [1/3] - ``` float OH_NativeXComponent_TouchPoint::screenX = 0.0 ``` -**描述:** +**描述:** 触摸点相对于XComponent所在应用窗口左上角的x坐标。 @@ -886,14 +1486,13 @@ float OH_NativeXComponent_TouchPoint::screenX = 0.0 ### screenX [2/3] - ``` float OH_NativeXComponent_TouchEvent::screenX = 0.0 ``` -**描述:** +**描述:** -触摸点相对于XComponent所在应用窗口左上角的x坐标。 +触摸点相对于屏幕左边缘的x坐标。 **起始版本:** @@ -902,14 +1501,13 @@ float OH_NativeXComponent_TouchEvent::screenX = 0.0 ### screenX [3/3] - ``` float OH_NativeXComponent_MouseEvent::screenX ``` -**描述:** +**描述:** -点击触点相对于XComponent所在应用窗口左上角的x轴坐标。 +点击触点相对于屏幕左上角的x轴坐标。 **起始版本:** @@ -918,12 +1516,11 @@ float OH_NativeXComponent_MouseEvent::screenX ### screenY [1/3] - ``` float OH_NativeXComponent_TouchPoint::screenY = 0.0 ``` -**描述:** +**描述:** 触摸点相对于XComponent所在应用窗口左上角的y坐标。 @@ -934,14 +1531,13 @@ float OH_NativeXComponent_TouchPoint::screenY = 0.0 ### screenY [2/3] - ``` float OH_NativeXComponent_TouchEvent::screenY = 0.0 ``` -**描述:** +**描述:** -触摸点相对于XComponent所在应用窗口左上角的y坐标。 +触摸点相对于屏幕上边缘的y坐标。 **起始版本:** @@ -950,14 +1546,13 @@ float OH_NativeXComponent_TouchEvent::screenY = 0.0 ### screenY [3/3] - ``` float OH_NativeXComponent_MouseEvent::screenY ``` -**描述:** +**描述:** -点击触点相对于XComponent所在应用窗口左上角的y轴坐标。 +点击触点相对于屏幕左上角的y轴坐标。 **起始版本:** @@ -966,12 +1561,11 @@ float OH_NativeXComponent_MouseEvent::screenY ### size [1/2] - ``` double OH_NativeXComponent_TouchPoint::size = 0.0 ``` -**描述:** +**描述:** 指垫和屏幕之间的接触面积。 @@ -982,12 +1576,11 @@ double OH_NativeXComponent_TouchPoint::size = 0.0 ### size [2/2] - ``` double OH_NativeXComponent_TouchEvent::size = 0.0 ``` -**描述:** +**描述:** 指垫和屏幕之间的接触面积。 @@ -998,12 +1591,11 @@ double OH_NativeXComponent_TouchEvent::size = 0.0 ### timeStamp [1/2] - ``` long long OH_NativeXComponent_TouchPoint::timeStamp = 0 ``` -**描述:** +**描述:** 当前触摸事件的时间戳。 @@ -1014,12 +1606,11 @@ long long OH_NativeXComponent_TouchPoint::timeStamp = 0 ### timeStamp [2/2] - ``` long long OH_NativeXComponent_TouchEvent::timeStamp = 0 ``` -**描述:** +**描述:** 当前触摸事件的时间戳。 @@ -1030,14 +1621,13 @@ long long OH_NativeXComponent_TouchEvent::timeStamp = 0 ### timestamp - ``` int64_t OH_NativeXComponent_MouseEvent::timestamp ``` -**描述:** +**描述:** -当前鼠标事件的时间戳 +当前鼠标事件的时间戳。 **起始版本:** @@ -1046,12 +1636,11 @@ int64_t OH_NativeXComponent_MouseEvent::timestamp ### touchPoints - ``` OH_NativeXComponent_TouchPoint OH_NativeXComponent_TouchEvent::touchPoints[OH_MAX_TOUCH_POINTS_NUMBER] ``` -**描述:** +**描述:** 当前触摸点的数组。 @@ -1062,12 +1651,11 @@ OH_NativeXComponent_TouchPoint OH_NativeXComponent_TouchEvent::touchPoints[OH_MA ### type [1/2] - ``` OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchPoint::type = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN ``` -**描述:** +**描述:** 触摸事件的触摸类型。 @@ -1078,12 +1666,11 @@ OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchPoint::type = OH_Nat ### type [2/2] - ``` OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchEvent::type = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN ``` -**描述:** +**描述:** 触摸事件的触摸类型。 @@ -1094,12 +1681,11 @@ OH_NativeXComponent_TouchEventType OH_NativeXComponent_TouchEvent::type = OH_Nat ### x [1/3] - ``` float OH_NativeXComponent_TouchPoint::x = 0.0 ``` -**描述:** +**描述:** 触摸点相对于XComponent组件左边缘的x坐标。 @@ -1110,12 +1696,11 @@ float OH_NativeXComponent_TouchPoint::x = 0.0 ### x [2/3] - ``` float OH_NativeXComponent_TouchEvent::x = 0.0 ``` -**描述:** +**描述:** 触摸点相对于XComponent组件左边缘的x坐标。 @@ -1126,12 +1711,11 @@ float OH_NativeXComponent_TouchEvent::x = 0.0 ### x [3/3] - ``` float OH_NativeXComponent_MouseEvent::x ``` -**描述:** +**描述:** 点击触点相对于当前组件左上角的x轴坐标。 @@ -1142,12 +1726,11 @@ float OH_NativeXComponent_MouseEvent::x ### y [1/3] - ``` float OH_NativeXComponent_TouchPoint::y = 0.0 ``` -**描述:** +**描述:** 触摸点相对于XComponent组件上边缘的y坐标。 @@ -1158,12 +1741,11 @@ float OH_NativeXComponent_TouchPoint::y = 0.0 ### y [2/3] - ``` float OH_NativeXComponent_TouchEvent::y = 0.0 ``` -**描述:** +**描述:** 触摸点相对于XComponent组件上边缘的y坐标。 @@ -1174,15 +1756,14 @@ float OH_NativeXComponent_TouchEvent::y = 0.0 ### y [3/3] - ``` float OH_NativeXComponent_MouseEvent::y ``` -**描述:** +**描述:** 点击触点相对于当前组件左上角的y轴坐标。 **起始版本:** -8 \ No newline at end of file +8 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___predicates.md b/zh-cn/application-dev/reference/native-apis/_o_h___predicates.md index e44eeba7c66cdd0e8f0999a78a60cbf332f968b6..bb3c7d99994d2e6d3210b760060e4da93753717b 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___predicates.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___predicates.md @@ -45,4 +45,4 @@ | [in](_r_d_b.md#in) | 函数指针,配置谓词以匹配数据字段为field且值在给定范围内的指定字段。 | | [notIn](_r_d_b.md#notin) | 函数指针,配置谓词以匹配数据字段为field且值超出给定范围内的指定字段。 | | [clear](_r_d_b.md#clear-12) | 函数指针,清空谓词。 | -| [destroyPredicates](_r_d_b.md#destroypredicates) | 销毁OH_Predicates对象,并回收该对象占用的内存。 | +| [destroy](_r_d_b.md#destroy-24) | 销毁OH_Predicates对象,并回收该对象占用的内存。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md b/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md index 6248376e3c64ef9b0d798d298a03c2fff5b4e686..008e7380959716b0c4ff0f2da829917e9c11883e 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___rdb___config.md @@ -21,6 +21,9 @@ | 名称 | 描述 | | -------- | -------- | -| [path](_r_d_b.md#path) | 数据库文件路径。 | +| [selfSize](_r_d_b.md#selfsize) | 该结构体的大小。 | +| [dataBaseDir](_r_d_b.md#databasedir) | 数据库文件路径。 | +| [bundleName](_r_d_b.md#bundlename) | 应用包名。 | +| [moduleName](_r_d_b.md#modulename) | 应用模块名。 | | [isEncrypt](_r_d_b.md#isencrypt) | 指定数据库是否加密。 | -| [securityLevel](_r_d_b.md#securitylevel) | 设置数据库安全级别 [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel)。 | +| [securityLevel](_r_d_b.md#securitylevel) | 数据库安全级别。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___v_bucket.md b/zh-cn/application-dev/reference/native-apis/_o_h___v_bucket.md index e96aa86334ffecc6ecc1eab7e69520cbd5c6ec99..cb230a04f3fa5c1b87abd931f1fe2dc5707a08be 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___v_bucket.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___v_bucket.md @@ -29,4 +29,4 @@ | [putBlob](_r_d_b.md#putblob) | 将const uint8_t \*值放入给定列名的OH_VBucket对象中。 | | [putNull](_r_d_b.md#putnull) | 将NULL值放入给定列名的OH_VBucket对象中。 | | [clear](_r_d_b.md#clear-22) | 清空OH_VBucket对象。 | -| [destroyValuesBucket](_r_d_b.md#destroyvaluesbucket) | 销毁OH_VBucket对象,并回收该对象占用的内存。 | +| [destroy](_r_d_b.md#destroy-34) | 销毁OH_VBucket对象,并回收该对象占用的内存。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___v_object.md b/zh-cn/application-dev/reference/native-apis/_o_h___v_object.md index d0960d7ecb3e3340e7d8a6ad68efe4d5331f67ca..2ffde853814feb9d89e5b0a76d7e83edea5b420e 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___v_object.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___v_object.md @@ -26,4 +26,4 @@ | [putDouble](_r_d_b.md#putdouble) | 将double类型的单个参数或者数组转换为OH_VObject类型的值。 | | [putText](_r_d_b.md#puttext-22) | 将char \*类型的字符数组转换为OH_VObject类型的值。 | | [putTexts](_r_d_b.md#puttexts) | 将char \*类型的字符串数组转换为OH_VObject类型的值。 | -| [destroyValueObject](_r_d_b.md#destroyvalueobject) | 销毁OH_VObject对象,并回收该对象占用的内存。 | +| [destroy](_r_d_b.md#destroy-44) | 销毁OH_VObject对象,并回收该对象占用的内存。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_component.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_component.md new file mode 100644 index 0000000000000000000000000000000000000000..c044cfb1c295ef2f0daf1c50ab1479ed6b208982 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_component.md @@ -0,0 +1,86 @@ +# OHOS::Media::OhosImageComponent + + +## 概述 + +定义图像组成信息。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [byteBuffer](#bytebuffer) | 像素数据地址 | +| [size](#size) | 内存中的像素数据大小 | +| [componentType](#componenttype) | 像素数据类型 | +| [rowStride](#rowstride) | 像素数据行宽 | +| [pixelStride](#pixelstride) | 像素数据的像素大小 | + + +## 结构体成员变量说明 + + +### byteBuffer + +``` +uint8_t* OHOS::Media::OhosImageComponent::byteBuffer +``` + +**描述:** + +像素数据地址 + + +### componentType + +``` +int32_t OHOS::Media::OhosImageComponent::componentType +``` + +**描述:** + +像素数据类型 + + +### pixelStride + +``` +int32_t OHOS::Media::OhosImageComponent::pixelStride +``` + +**描述:** + +像素数据的像素大小 + + +### rowStride + +``` +int32_t OHOS::Media::OhosImageComponent::rowStride +``` + +**描述:** + +像素数据行宽 + + +### size + +``` +size_t OHOS::Media::OhosImageComponent::size +``` + +**描述:** + +内存中的像素数据大小 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_rect.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_rect.md new file mode 100644 index 0000000000000000000000000000000000000000..cca47ccfd9bd0b2be716d96096dc4e5c314e20ac --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_rect.md @@ -0,0 +1,74 @@ +# OHOS::Media::OhosImageRect + + +## 概述 + +定义图像矩形信息。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [x](#x) | 矩形x坐标值 | +| [y](#y) | 矩形y坐标值 | +| [width](#width) | 矩形宽度值,用pixels表示 | +| [height](#height) | 矩形高度值,用pixels表示 | + + +## 结构体成员变量说明 + + +### height + +``` +int32_t OHOS::Media::OhosImageRect::height +``` + +**描述:** + +矩形高度值,用pixels表示 + + +### width + +``` +int32_t OHOS::Media::OhosImageRect::width +``` + +**描述:** + +矩形宽度值,用pixels表示 + + +### x + +``` +int32_t OHOS::Media::OhosImageRect::x +``` + +**描述:** + +矩形x坐标值 + + +### y + +``` +int32_t OHOS::Media::OhosImageRect::y +``` + +**描述:** + +矩形y坐标值 diff --git a/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md new file mode 100644 index 0000000000000000000000000000000000000000..ec47b50addf63a456d448e49fc86824f313c2592 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md @@ -0,0 +1,78 @@ +# OHOS::Media::OhosPixelMapInfo + + +## 概述 + +用于定义 pixel map 的相关信息。 + +**起始版本:** + +8 + +**废弃起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [width](#width) | 图片的宽,用pixels表示 | +| [height](#height) | 图片的高,用pixels表示 | +| [rowSize](#rowsize) | 每行的bytes数 | +| [pixelFormat](#pixelformat) | Pixel 的格式 | + + +## 结构体成员变量说明 + + +### height + +``` +uint32_t OHOS::Media::OhosPixelMapInfo::height +``` + +**描述:** + +图片的高, 用pixels表示 + + +### pixelFormat + +``` +int32_t OHOS::Media::OhosPixelMapInfo::pixelFormat +``` + +**描述:** + +Pixel 的格式 + + +### rowSize + +``` +uint32_t OHOS::Media::OhosPixelMapInfo::rowSize +``` + +**描述:** + +每行的bytes数 + + +### width + +``` +uint32_t OHOS::Media::OhosPixelMapInfo::width +``` + +**描述:** + +图片的宽, 用pixels表示 diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_decoding_ops.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_decoding_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..c3fdf394487fb49bbeaed2046eacd08a0859bcf2 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_decoding_ops.md @@ -0,0 +1,33 @@ +# OhosImageDecodingOps + + +## 概述 + +定义图像源解码选项。 此选项给[OH_ImageSource_CreatePixelMap](image.md#oh_imagesource_createpixelmap)和[OH_ImageSource_CreatePixelMapList](image.md#oh_imagesource_createpixelmaplist)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [editable](image.md#editable) | 定义输出的像素位图是否可编辑 | +| [pixelFormat](image.md#pixelformat-23) | 定义输出的像素格式 | +| [fitDensity](image.md#fitdensity) | 定义解码目标的像素密度 | +| [index](image.md#index) | 定义图像源解码指数 | +| [sampleSize](image.md#samplesize) | 定义解码样本大小选项 | +| [rotate](image.md#rotate) | 定义解码旋转选项 | +| [size](image.md#size-27) | 定义解码目标像素宽高的大小 | +| [region](image.md#region) | 定义图像源解码的像素范围 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_receiver_info.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_receiver_info.md new file mode 100644 index 0000000000000000000000000000000000000000..8151b89421c35af5317878ffc6bd51337a567bb7 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_receiver_info.md @@ -0,0 +1,27 @@ +# OhosImageReceiverInfo + + +## 概述 + +定义**ImageReceiver**的相关信息。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| width | 消费端接收图片时的默认图像宽度,用pixels表示 | +| height | 消费端接收图片时的默认图像高度,用pixels表示 | +| format | 通过接收器创建图像格式OHOS_IMAGE_FORMAT_JPEG | +| capicity | 图片缓存数量的最大值 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_region.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_region.md new file mode 100644 index 0000000000000000000000000000000000000000..4bac58b041cf281dba7270d655b4b96b3822ee02 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_region.md @@ -0,0 +1,29 @@ +# OhosImageRegion + + +## 概述 + +定义图像源解码的范围选项。 [OhosImageDecodingOps](_ohos_image_decoding_ops.md), [OH_ImageSource_CreatePixelMap](image.md#oh_imagesource_createpixelmap) and [OH_ImageSource_CreatePixelMapList](image.md#oh_imagesource_createpixelmaplist). + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [x](image.md#x) | 起始x坐标,用pixels表示 | +| [y](image.md#y) | 起始y坐标,用pixels表示 | +| [width](image.md#width) | 宽度范围,用pixels表示 | +| [height](image.md#height) | 高度范围,用pixels表示 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_size.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_size.md new file mode 100644 index 0000000000000000000000000000000000000000..58b9dcc7f7aa3aa92bd964461f3a0c5c81505b29 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_size.md @@ -0,0 +1,50 @@ +# OhosImageSize + + +## 概述 + +定义图像大小。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [width](#width) | 像素中的图像宽度,用pixels表示 | +| [height](#height) | 像素中的图像高度,用pixels表示 | + + +## 结构体成员变量说明 + + +### height + +``` +int32_t OhosImageSize::height +``` + +**描述:** + +像素中的图像高度,用pixels表示 + + +### width + +``` +int32_t OhosImageSize::width +``` + +**描述:** + +像素中的图像宽度,用pixels表示 diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source.md new file mode 100644 index 0000000000000000000000000000000000000000..6adbffe503920951650a5c1a4d272a390c7cb755 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source.md @@ -0,0 +1,30 @@ +# OhosImageSource + + +## 概述 + +定义图像源输入资源,每次仅接收一种类型。由[OH_ImageSource_Create](image.md#oh_imagesource_create)获取。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [uri](image.md#uri) = nullptr | 图像源资源标识符,接受文件资源或者base64资源 | +| [uriSize](image.md#urisize) = 0 | 图像源资源长度 | +| [fd](image.md#fd) = -1 | 图像源文件资源描述符 | +| [buffer](image.md#buffer-12) = nullptr | 图像源缓冲区资源,解手格式化包缓冲区或者base64缓冲区 | +| [bufferSize](image.md#buffersize-12) = 0 | 图像源缓冲区资源大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_delay_time_list.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_delay_time_list.md new file mode 100644 index 0000000000000000000000000000000000000000..58c19ea3b43e7acf2b308a9cf0a16e2c83655d31 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_delay_time_list.md @@ -0,0 +1,27 @@ +# OhosImageSourceDelayTimeList + + +## 概述 + +定义图像源延迟时间列表。由[OH_ImageSource_GetDelayTime](image.md#oh_imagesource_getdelaytime)获取。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [delayTimeList](image.md#delaytimelist) | 图像源延迟时间列表头地址 | +| [size](image.md#size-47) = 0 | 图像源延迟时间列表大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_info.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_info.md new file mode 100644 index 0000000000000000000000000000000000000000..b9f34bda9499ff1201906101ef82c52b9a5e24bd --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_info.md @@ -0,0 +1,30 @@ +# OhosImageSourceInfo + + +## 概述 + +定义图像源信息,由[OH_ImageSource_GetImageInfo](image.md#oh_imagesource_getimageinfo)获取。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [pixelFormat](image.md#pixelformat-33) | 图像源像素格式, 由[OH_ImageSource_Create()](image.md#oh_imagesource_create)设置 | +| [colorSpace](image.md#colorspace) | 图像源色彩空间 | +| [alphaType](image.md#alphatype) | 图像源透明度类型 | +| [density](image.md#density-22) | 图像源密度, 由 [OH_ImageSource_Create()](image.md#oh_imagesource_create)设置 | +| [size](image.md#size-37) | 图像源像素宽高的大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_ops.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..ed38184716b529f6232e2988febd8c5b97b08d5b --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_ops.md @@ -0,0 +1,28 @@ +# OhosImageSourceOps + + +## 概述 + +定义图像源选项信息。 此选项给[OH_ImageSource_Create](image.md#oh_imagesource_create)和[OH_ImageSource_CreateIncremental](image.md#oh_imagesource_createincremental)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [density](image.md#density-12) | 图像源像素密度 | +| [pixelFormat](image.md#pixelformat-13) | 图像源像素格式,通常用于描述YUV缓冲区 | +| [size](image.md#size-17) | 图像源像素宽高的大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_property.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_property.md new file mode 100644 index 0000000000000000000000000000000000000000..684feb478010e82633d67c9587af1191c7ade38e --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_property.md @@ -0,0 +1,27 @@ +# OhosImageSourceProperty + + +## 概述 + +定义图像源属性键值字符串。 此选项给[OH_ImageSource_GetImageProperty](image.md#oh_imagesource_getimageproperty) and [OH_ImageSource_ModifyImageProperty](image.md#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [value](image.md#value) = nullptr | 定义图像源属性键值字符串头地址 | +| [size](image.md#size-77) = 0 | 定义图像源属性键值字符串大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_supported_format.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_supported_format.md new file mode 100644 index 0000000000000000000000000000000000000000..f77addb6838f9da86c956f03f94fce79895b0105 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_supported_format.md @@ -0,0 +1,27 @@ +# OhosImageSourceSupportedFormat + + +## 概述 + +定义图像源支持的格式字符串。 此选项给[OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md)和[OH_ImageSource_GetSupportedFormats](image.md#oh_imagesource_getsupportedformats)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [format](image.md#format) = nullptr | 图像源支持的格式字符串头地址 | +| [size](image.md#size-57) = 0 | 图像源支持的格式字符串大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_supported_format_list.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_supported_format_list.md new file mode 100644 index 0000000000000000000000000000000000000000..75b166246d0bb33fdb306626c35e8743139d0400 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_supported_format_list.md @@ -0,0 +1,27 @@ +# OhosImageSourceSupportedFormatList + + +## 概述 + +定义图像源支持的格式字符串列表。 由[OH_ImageSource_GetSupportedFormats](image.md#oh_imagesource_getsupportedformats)获取 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [supportedFormatList](image.md#supportedformatlist) = nullptr | 图像源支持的格式字符串列表头地址 | +| [size](image.md#size-67) = 0 | 图像源支持的格式字符串列表大小 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_image_source_update_data.md b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_update_data.md new file mode 100644 index 0000000000000000000000000000000000000000..055761c92b6bac79926823b21ad53f2a81a8e37c --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_image_source_update_data.md @@ -0,0 +1,30 @@ +# OhosImageSourceUpdateData + + +## 概述 + +定义图像源更新数据选项,由[OH_ImageSource_UpdateData](image.md#oh_imagesource_updatedata)获取。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [buffer](image.md#buffer-22) = nullptr | 图像源更新数据缓冲区 | +| [bufferSize](image.md#buffersize-22) = 0 | 图像源更新数据缓冲区大小 | +| [offset](image.md#offset) = 0 | 图像源更新数据缓冲区的开端 | +| [updateLength](image.md#updatelength) = 0 | 图像源更新数据缓冲区的更新数据长度 | +| [isCompleted](image.md#iscompleted) = 0 | 图像源更新数据在此节中完成 | diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_create_ops.md b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_create_ops.md index 438de82b1db4612c61b4696f3c7db1e251a0f93e..1cd2947ade35aaf548febfa65bab0a697e2c6b00 100644 --- a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_create_ops.md +++ b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_create_ops.md @@ -3,12 +3,13 @@ ## 概述 -用于定义创建 pixel map 设置选项的相关信息. +用于定义创建 pixel map 设置选项的相关信息。 **起始版本:** + 10 -**相关模块:** +**相关模块:** [Image](image.md) @@ -20,12 +21,12 @@ | 名称 | 描述 | | -------- | -------- | -| [width](#width) | 图片的宽,用pixels表示。 | -| [height](#height) | 图片的高,用pixels表示。 | -| [pixelFormat](#pixelformat) | 图片的格式。 | -| [editable](#editable) | 图片的编辑类型。 | -| [alphaType](#alphatype) | 图片的alpha类型。 | -| [scaleMode](#scalemode) | 图片的缩放类型。 | +| [width](#width) | 图片的宽, 用pixels表示 | +| [height](#height) | 图片的高, 用pixels表示 | +| [pixelFormat](#pixelformat) | 图片的格式 | +| [editable](#editable) | 图片的编辑类型 | +| [alphaType](#alphatype) | 图片的alpha类型 | +| [scaleMode](#scalemode) | 图片的缩放类型 | ## 结构体成员变量说明 @@ -33,59 +34,65 @@ ### alphaType - ``` uint32_t OhosPixelMapCreateOps::alphaType ``` -**描述:** -图片的alpha类型。 + +**描述:** + +图片的alpha类型 ### editable - ``` uint32_t OhosPixelMapCreateOps::editable ``` -**描述:** -图片的编辑类型。 + +**描述:** + +图片的编辑类型 ### height - ``` uint32_t OhosPixelMapCreateOps::height ``` -**描述:** -图片的高,用pixels表示。 + +**描述:** + +图片的高, 用pixels表示 ### pixelFormat - ``` int32_t OhosPixelMapCreateOps::pixelFormat ``` -**描述:** -图片的格式。 + +**描述:** + +图片的格式 ### scaleMode - ``` uint32_t OhosPixelMapCreateOps::scaleMode ``` -**描述:** -图片的缩放类型。 + +**描述:** + +图片的缩放类型 ### width - ``` uint32_t OhosPixelMapCreateOps::width ``` -**描述:** -图片的宽,用pixels表示。 + +**描述:** + +图片的宽, 用pixels表示 diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md deleted file mode 100644 index 00e40e5e37abeee7c8e2c84c2d88bd9888bc6bf9..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md +++ /dev/null @@ -1,78 +0,0 @@ -# OhosPixelMapInfo - - -## 概述 - -用于定义 pixel map 的相关信息。 - -**起始版本:** - -8 - -**相关模块:** - -[Image](image.md) - - -## 汇总 - - -### 成员变量 - - | 成员变量名称 | 描述 | -| -------- | -------- | -| [width](#width) | 图片的宽,用pixels表示。 | -| [height](#height) | 图片的高,用pixels表示。 | -| [rowSize](#rowsize) | 每行的bytes数。 | -| [pixelFormat](#pixelformat) | Pixel的格式。 | - - -## 结构体成员变量说明 - - -### height - - -``` -uint32_t OhosPixelMapInfo::height -``` - -**描述:** - -图片的高,用pixels表示。 - - -### pixelFormat - - -``` -int32_t OhosPixelMapInfo::pixelFormat -``` - -**描述:** - -Pixel的格式。 - - -### rowSize - - -``` -uint32_t OhosPixelMapInfo::rowSize -``` - -**描述:** - -每行的bytes数。 - - -### width - - -``` -uint32_t OhosPixelMapInfo::width -``` - -**描述:** - -图片的宽,用pixels表示。 diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_infos.md b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_infos.md new file mode 100644 index 0000000000000000000000000000000000000000..313581355beb4c6f3e78a63b171e3bf86e85bbad --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_infos.md @@ -0,0 +1,74 @@ +# OhosPixelMapInfos + + +## 概述 + +用于定义 pixel map 的相关信息。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 成员变量 + +| 名称 | 描述 | +| -------- | -------- | +| [width](#width) | 图片的宽, 用pixels表示 | +| [height](#height) | 图片的高, 用pixels表示 | +| [rowSize](#rowsize) | 每行的bytes数 | +| [pixelFormat](#pixelformat) | Pixel 的格式 | + + +## 结构体成员变量说明 + + +### height + +``` +uint32_t OhosPixelMapInfos::height +``` + +**描述:** + +图片的高, 用pixels表示 + + +### pixelFormat + +``` +int32_t OhosPixelMapInfos::pixelFormat +``` + +**描述:** + +Pixel 的格式 + + +### rowSize + +``` +uint32_t OhosPixelMapInfos::rowSize +``` + +**描述:** + +每行的bytes数 + + +### width + +``` +uint32_t OhosPixelMapInfos::width +``` + +**描述:** + +图片的宽, 用pixels表示 diff --git a/zh-cn/application-dev/reference/native-apis/_r_d_b.md b/zh-cn/application-dev/reference/native-apis/_r_d_b.md index e87a794d4e48b026966caab641f1278ba2b72b43..c1108f5ae184a16910a7ffaa76c17d36713231af 100644 --- a/zh-cn/application-dev/reference/native-apis/_r_d_b.md +++ b/zh-cn/application-dev/reference/native-apis/_r_d_b.md @@ -5,7 +5,7 @@ 关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的 对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。 -\@syscap SystemCapability.DistributedDataManager.RelationalStore.Core +\@SystemCapability.DistributedDataManager.RelationalStore.Core **起始版本:** @@ -43,10 +43,13 @@ | 名称 | 描述 | | -------- | -------- | +| [OH_ColumnType](#oh_columntype) | 数据库字段类型。 | | [OH_Cursor](#oh_cursor) | 表示结果集。 | +| [OH_OrderType](#oh_ordertype) | 排序方式。 | | [OH_Predicates](#oh_predicates) | 表示谓词。 | | [OH_VObject](#oh_vobject) | 表示允许的数据字段类型。 | | [OH_VBucket](#oh_vbucket) | 用于存储键值对的类型。 | +| [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) | 数据库的安全级别枚举。 | | [OH_Rdb_ErrCode](#oh_rdb_errcode) | 表示错误码信息。 | @@ -69,7 +72,7 @@ | [OH_Rdb_CreatePredicates](#oh_rdb_createpredicates) (const char \*table) | 创建[OH_Predicates](_o_h___predicates.md)实例。 | | [OH_Rdb_GetOrOpen](#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | 获得一个相关的[OH_Rdb_Store](_o_h___rdb___store.md)实例,操作关系型数据库。 | | [OH_Rdb_CloseStore](#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | 销毁[OH_Rdb_Store](_o_h___rdb___store.md)对象,并回收该对象占用的内存。 | -| [OH_Rdb_DeleteStore](#oh_rdb_deletestore) (const char \*path) | 使用指定的数据库文件配置删除数据库。 | +| [OH_Rdb_DeleteStore](#oh_rdb_deletestore) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config) | 使用指定的数据库文件配置删除数据库。 | | [OH_Rdb_Insert](#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | 向目标表中插入一行数据。 | | [OH_Rdb_Update](#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件更新数据库中的数据。 | | [OH_Rdb_Delete](#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件删除数据库中的数据。 | @@ -102,7 +105,7 @@ | [OH_Cursor::getReal](#getreal) | 函数指针,以double形式获取当前行中指定列的值。 | | [OH_Cursor::getBlob](#getblob) | 函数指针,以字节数组的形式获取当前行中指定列的值。 | | [OH_Cursor::isNull](#isnull-12) | 函数指针,检查当前行中指定列的值是否为null。 | -| [OH_Cursor::close](#close) | 函数指针,关闭结果集。 | +| [OH_Cursor::destroy](#destroy-14) | 函数指针,关闭结果集。 | | [OH_Predicates::id](#id-14) | OH_Predicates结构体的唯一标识符。 | | [OH_Predicates::equalTo](#equalto) | 函数指针,配置谓词以匹配数据字段等于指定值的字段。 | | [OH_Predicates::notEqualTo](#notequalto) | 函数指针,配置谓词以匹配数据字段不等于指定值的字段。 | @@ -127,13 +130,13 @@ | [OH_Predicates::in](#in) | 函数指针,配置谓词以匹配数据字段为field且值在给定范围内的指定字段。 | | [OH_Predicates::notIn](#notin) | 函数指针,配置谓词以匹配数据字段为field且值超出给定范围内的指定字段。 | | [OH_Predicates::clear](#clear-12) | 函数指针,清空谓词。 | -| [OH_Predicates::destroyPredicates](#destroypredicates) | 销毁[OH_Predicates](_o_h___predicates.md)对象,并回收该对象占用的内存。 | +| [OH_Predicates::destroy](#destroy-24) | 销毁[OH_Predicates](_o_h___predicates.md)对象,并回收该对象占用的内存。 | | [OH_VObject::id](#id-24) | OH_VObject结构体的唯一标识符。 | | [OH_VObject::putInt64](#putint64-22) | 将int64类型的单个参数或者数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putDouble](#putdouble) | 将double类型的单个参数或者数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putText](#puttext-22) | 将char \*类型的字符数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putTexts](#puttexts) | 将char \*类型的字符串数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | -| [OH_VObject::destroyValueObject](#destroyvalueobject) | 销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 | +| [OH_VObject::destroy](#destroy-44) | 销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 | | [OH_VBucket::id](#id-34) | OH_VBucket结构体的唯一标识符。 | | [OH_VBucket::capability](#capability) | 表示结构体的存储键值对的数量 | | [OH_VBucket::putText](#puttext-12) | 将char\*值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 | @@ -142,8 +145,11 @@ | [OH_VBucket::putBlob](#putblob) | 将const uint8_t \*值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 | | [OH_VBucket::putNull](#putnull) | 将NULL值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 | | [OH_VBucket::clear](#clear-22) | 清空[OH_VBucket](_o_h___v_bucket.md)对象。 | -| [OH_VBucket::destroyValuesBucket](#destroyvaluesbucket) | 销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 | -| [OH_Rdb_Config::path](#path) | 数据库文件路径。 | +| [OH_VBucket::destroy](#destroy-34) | 销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 | +| [OH_Rdb_Config::selfSize](#selfsize) | 该结构体的大小。 | +| [OH_Rdb_Config::dataBaseDir](#databasedir) | 数据库文件路径。 | +| [OH_Rdb_Config::bundleName](#bundlename) | 应用包名。 | +| [OH_Rdb_Config::moduleName](#modulename) | 应用模块名。 | | [OH_Rdb_Config::isEncrypt](#isencrypt) | 指定数据库是否加密。 | | [OH_Rdb_Config::securityLevel](#securitylevel) | 设置数据库安全级别[OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)。 | | [OH_Rdb_Store::id](#id-44) | OH_Rdb_Store结构体的唯一标识符。 | @@ -152,8 +158,18 @@ ## 类型定义说明 -### OH_Cursor +### OH_ColumnType + +``` +typedef enum OH_ColumnType OH_ColumnType +``` +**描述:** + +数据库字段类型. + + +### OH_Cursor ``` typedef struct OH_Cursor OH_Cursor @@ -166,9 +182,19 @@ typedef struct OH_Cursor OH_Cursor 提供通过查询数据库生成的数据库结果集的访问方法。 -### OH_Predicates +### OH_OrderType + +``` +typedef enum OH_OrderType OH_OrderType +``` + +**描述:** + +排序方式。 +### OH_Predicates + ``` typedef struct OH_Predicates OH_Predicates ``` @@ -180,7 +206,6 @@ typedef struct OH_Predicates OH_Predicates ### OH_Rdb_ErrCode - ``` typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode ``` @@ -190,8 +215,18 @@ typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode 表示错误码信息。 -### OH_VBucket +### OH_Rdb_SecurityLevel +``` +typedef enum OH_Rdb_SecurityLevel OH_Rdb_SecurityLevel +``` + +**描述:** + +数据库的安全级别枚举。 + + +### OH_VBucket ``` typedef struct OH_VBucket OH_VBucket @@ -204,7 +239,6 @@ typedef struct OH_VBucket OH_VBucket ### OH_VObject - ``` typedef struct OH_VObject OH_VObject ``` @@ -219,7 +253,6 @@ typedef struct OH_VObject OH_VObject ### OH_ColumnType - ``` enum OH_ColumnType ``` @@ -239,7 +272,6 @@ enum OH_ColumnType ### OH_OrderType - ``` enum OH_OrderType ``` @@ -256,7 +288,6 @@ enum OH_OrderType ### OH_Rdb_ErrCode - ``` enum OH_Rdb_ErrCode ``` @@ -323,7 +354,6 @@ enum OH_Rdb_ErrCode ### OH_Rdb_SecurityLevel - ``` enum OH_Rdb_SecurityLevel ``` @@ -345,7 +375,6 @@ enum OH_Rdb_SecurityLevel ### OH_Rdb_Backup() - ``` int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath ) ``` @@ -372,7 +401,6 @@ int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath ) ### OH_Rdb_BeginTransaction() - ``` int OH_Rdb_BeginTransaction (OH_Rdb_Store * store) ``` @@ -398,7 +426,6 @@ int OH_Rdb_BeginTransaction (OH_Rdb_Store * store) ### OH_Rdb_CloseStore() - ``` int OH_Rdb_CloseStore (OH_Rdb_Store * store) ``` @@ -424,7 +451,6 @@ int OH_Rdb_CloseStore (OH_Rdb_Store * store) ### OH_Rdb_Commit() - ``` int OH_Rdb_Commit (OH_Rdb_Store * store) ``` @@ -450,7 +476,6 @@ int OH_Rdb_Commit (OH_Rdb_Store * store) ### OH_Rdb_CreatePredicates() - ``` OH_Predicates* OH_Rdb_CreatePredicates (const char * table) ``` @@ -476,9 +501,8 @@ OH_Predicates* OH_Rdb_CreatePredicates (const char * table) ### OH_Rdb_CreateValueObject() - ``` -OH_VObject* OH_Rdb_CreateValueObject (void ) +OH_VObject* OH_Rdb_CreateValueObject (void) ``` **描述:** @@ -496,9 +520,8 @@ OH_VObject* OH_Rdb_CreateValueObject (void ) ### OH_Rdb_CreateValuesBucket() - ``` -OH_VBucket* OH_Rdb_CreateValuesBucket (void ) +OH_VBucket* OH_Rdb_CreateValuesBucket (void) ``` **描述:** @@ -516,7 +539,6 @@ OH_VBucket* OH_Rdb_CreateValuesBucket (void ) ### OH_Rdb_Delete() - ``` int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates ) ``` @@ -543,9 +565,8 @@ int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates ) ### OH_Rdb_DeleteStore() - ``` -int OH_Rdb_DeleteStore (const char * path) +int OH_Rdb_DeleteStore (const OH_Rdb_Config * config) ``` **描述:** @@ -565,7 +586,6 @@ int OH_Rdb_DeleteStore (const char * path) ### OH_Rdb_Execute() - ``` int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql ) ``` @@ -592,7 +612,6 @@ int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql ) ### OH_Rdb_ExecuteQuery() - ``` OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql ) ``` @@ -619,7 +638,6 @@ OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql ) ### OH_Rdb_GetOrOpen() - ``` OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode ) ``` @@ -646,7 +664,6 @@ OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode ) ### OH_Rdb_GetVersion() - ``` int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version ) ``` @@ -673,7 +690,6 @@ int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version ) ### OH_Rdb_Insert() - ``` int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * valuesBucket ) ``` @@ -701,7 +717,6 @@ int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * values ### OH_Rdb_Query() - ``` OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const char *const * columnNames, int length ) ``` @@ -730,7 +745,6 @@ OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const ### OH_Rdb_Restore() - ``` int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath ) ``` @@ -757,7 +771,6 @@ int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath ) ### OH_Rdb_RollBack() - ``` int OH_Rdb_RollBack (OH_Rdb_Store * store) ``` @@ -783,7 +796,6 @@ int OH_Rdb_RollBack (OH_Rdb_Store * store) ### OH_Rdb_SetVersion() - ``` int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version ) ``` @@ -810,7 +822,6 @@ int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version ) ### OH_Rdb_Update() - ``` int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicates * predicates ) ``` @@ -841,7 +852,6 @@ int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicate ### andOperate - ``` OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates) ``` @@ -869,7 +879,6 @@ OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates) ### beginWrap - ``` OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates) ``` @@ -897,7 +906,6 @@ OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates) ### between - ``` OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -925,8 +933,18 @@ OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char [OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). -### capability +### bundleName +``` +const char* OH_Rdb_Config::bundleName +``` + +**描述:** + +应用包名。 + + +### capability ``` uint16_t OH_VBucket::capability @@ -939,7 +957,6 @@ uint16_t OH_VBucket::capability ### clear [1/2] - ``` OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates) ``` @@ -965,7 +982,6 @@ OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates) ### clear [2/2] - ``` int(* OH_VBucket::clear) (OH_VBucket *bucket) ``` @@ -989,11 +1005,21 @@ int(* OH_VBucket::clear) (OH_VBucket *bucket) [OH_VBucket](_o_h___v_bucket.md). -### close +### dataBaseDir + +``` +const char* OH_Rdb_Config::dataBaseDir +``` + +**描述:** + +数据库文件路径。 + +### destroy [1/4] ``` -int(* OH_Cursor::close) (OH_Cursor *cursor) +int(* OH_Cursor::destroy) (OH_Cursor *cursor) ``` **描述:** @@ -1015,11 +1041,10 @@ int(* OH_Cursor::close) (OH_Cursor *cursor) [OH_Cursor](_o_h___cursor.md). -### destroyPredicates - +### destroy [2/4] ``` -int(* OH_Predicates::destroyPredicates) (OH_Predicates *predicates) +int(* OH_Predicates::destroy) (OH_Predicates *predicates) ``` **描述:** @@ -1041,22 +1066,21 @@ int(* OH_Predicates::destroyPredicates) (OH_Predicates *predicates) [OH_Predicates](_o_h___predicates.md). -### destroyValueObject - +### destroy [3/4] ``` -int(* OH_VObject::destroyValueObject) (OH_VObject *valueObject) +int(* OH_VBucket::destroy) (OH_VBucket *bucket) ``` **描述:** -销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 +销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 **参数:** | 名称 | 描述 | | -------- | -------- | -| valueObject | 表示指向[OH_VObject](_o_h___v_object.md)实例的指针。 | +| bucket | 表示指向[OH_VBucket](_o_h___v_bucket.md)实例的指针。 | **返回:** @@ -1064,25 +1088,24 @@ int(* OH_VObject::destroyValueObject) (OH_VObject *valueObject) **参见:** -[OH_VObject](_o_h___v_object.md). - +[OH_VBucket](_o_h___v_bucket.md). -### destroyValuesBucket +### destroy [4/4] ``` -int(* OH_VBucket::destroyValuesBucket) (OH_VBucket *bucket) +int(* OH_VObject::destroy) (OH_VObject *valueObject) ``` **描述:** -销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 +销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 **参数:** | 名称 | 描述 | | -------- | -------- | -| bucket | 表示指向[OH_VBucket](_o_h___v_bucket.md)实例的指针。 | +| valueObject | 表示指向[OH_VObject](_o_h___v_object.md)实例的指针。 | **返回:** @@ -1090,12 +1113,11 @@ int(* OH_VBucket::destroyValuesBucket) (OH_VBucket *bucket) **参见:** -[OH_VBucket](_o_h___v_bucket.md). +[OH_VObject](_o_h___v_object.md). ### distinct - ``` OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates) ``` @@ -1123,7 +1145,6 @@ OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates) ### endWrap - ``` OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates) ``` @@ -1151,7 +1172,6 @@ OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates) ### equalTo - ``` OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1181,7 +1201,6 @@ OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char ### getBlob - ``` int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char *value, int length) ``` @@ -1210,7 +1229,6 @@ int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char ### getColumnCount - ``` int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count) ``` @@ -1237,7 +1255,6 @@ int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count) ### getColumnIndex - ``` int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *columnIndex) ``` @@ -1265,7 +1282,6 @@ int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *colu ### getColumnName - ``` int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *name, int length) ``` @@ -1294,7 +1310,6 @@ int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *n ### getColumnType - ``` int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_ColumnType *columnType) ``` @@ -1322,7 +1337,6 @@ int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_Colu ### getInt64 - ``` int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *value) ``` @@ -1350,7 +1364,6 @@ int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *val ### getReal - ``` int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value) ``` @@ -1378,7 +1391,6 @@ int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value ### getRowCount - ``` int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count) ``` @@ -1405,7 +1417,6 @@ int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count) ### getSize - ``` int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size) ``` @@ -1433,7 +1444,6 @@ int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size) ### getText - ``` int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value, int length) ``` @@ -1462,7 +1472,6 @@ int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value, ### goToNextRow - ``` int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor) ``` @@ -1488,7 +1497,6 @@ int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor) ### greaterThan - ``` OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1518,7 +1526,6 @@ OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const c ### greaterThanOrEqualTo - ``` OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1548,7 +1555,6 @@ OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates ### groupBy - ``` OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const *const *fields, int length) ``` @@ -1578,7 +1584,6 @@ OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const ### id [1/4] - ``` int64_t OH_Predicates::id ``` @@ -1590,7 +1595,6 @@ OH_Predicates结构体的唯一标识符。 ### id [2/4] - ``` int64_t OH_VObject::id ``` @@ -1602,7 +1606,6 @@ OH_VObject结构体的唯一标识符。 ### id [3/4] - ``` int64_t OH_VBucket::id ``` @@ -1614,7 +1617,6 @@ OH_VBucket结构体的唯一标识符。 ### id [4/4] - ``` int64_t OH_Rdb_Store::id ``` @@ -1626,7 +1628,6 @@ OH_Rdb_Store结构体的唯一标识符。 ### in - ``` OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1656,7 +1657,6 @@ OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *fiel ### isEncrypt - ``` bool OH_Rdb_Config::isEncrypt ``` @@ -1668,7 +1668,6 @@ bool OH_Rdb_Config::isEncrypt ### isNotNull - ``` OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const char *field) ``` @@ -1697,7 +1696,6 @@ OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const cha ### isNull [1/2] - ``` int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull) ``` @@ -1725,7 +1723,6 @@ int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull) ### isNull [2/2] - ``` OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char *field) ``` @@ -1754,7 +1751,6 @@ OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char * ### lessThan - ``` OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1784,7 +1780,6 @@ OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char ### lessThanOrEqualTo - ``` OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1814,7 +1809,6 @@ OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, c ### like - ``` OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1844,7 +1838,6 @@ OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *fi ### limit - ``` OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int value) ``` @@ -1871,9 +1864,19 @@ OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int [OH_Predicates](_o_h___predicates.md). -### notBetween +### moduleName + +``` +const char* OH_Rdb_Config::moduleName +``` + +**描述:** + +应用模块名。 +### notBetween + ``` OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1903,7 +1906,6 @@ OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const ch ### notEqualTo - ``` OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1933,7 +1935,6 @@ OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const ch ### notIn - ``` OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) ``` @@ -1963,7 +1964,6 @@ OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *f ### offset - ``` OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int rowOffset) ``` @@ -1992,7 +1992,6 @@ OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int ### orderBy - ``` OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char *field, OH_OrderType type) ``` @@ -2022,7 +2021,6 @@ OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char ### orOperate - ``` OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates) ``` @@ -2048,21 +2046,8 @@ OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates) [OH_Predicates](_o_h___predicates.md). -### path - - -``` -const char* OH_Rdb_Config::path -``` - -**描述:** - -数据库文件路径。 - - ### putBlob - ``` int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t *value, uint32_t size) ``` @@ -2091,7 +2076,6 @@ int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t ### putDouble - ``` int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t count) ``` @@ -2119,7 +2103,6 @@ int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t c ### putInt64 [1/2] - ``` int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t value) ``` @@ -2147,7 +2130,6 @@ int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t valu ### putInt64 [2/2] - ``` int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t count) ``` @@ -2175,7 +2157,6 @@ int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t c ### putNull - ``` int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field) ``` @@ -2202,14 +2183,13 @@ int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field) ### putReal - ``` int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value) ``` **描述:** -将double值放入给定列名的{**OH_VBucket}对象中。** +将double值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 **参数:** @@ -2230,7 +2210,6 @@ int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value) ### putText [1/2] - ``` int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *value) ``` @@ -2258,7 +2237,6 @@ int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *v ### putText [2/2] - ``` int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value) ``` @@ -2285,7 +2263,6 @@ int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value) ### putTexts - ``` int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32_t count) ``` @@ -2313,11 +2290,21 @@ int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32 ### securityLevel - ``` -enum OH_Rdb_SecurityLevel OH_Rdb_Config::securityLevel +int OH_Rdb_Config::securityLevel ``` **描述:** 设置数据库安全级别[OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)。 + + +### selfSize + +``` +int OH_Rdb_Config::selfSize +``` + +**描述:** + +该结构体的大小。 diff --git a/zh-cn/application-dev/reference/native-apis/_vulkan.md b/zh-cn/application-dev/reference/native-apis/_vulkan.md index f365769c13208df0f2c37d60a156e1f1f94c98cd..0cb4091e1043c0f20f688b571e559f0521b085a3 100644 --- a/zh-cn/application-dev/reference/native-apis/_vulkan.md +++ b/zh-cn/application-dev/reference/native-apis/_vulkan.md @@ -28,8 +28,8 @@ | -------- | -------- | | [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) | 包含创建Vulkan Surface时必要的参数。 | | [VkNativeBufferUsageOHOS](_vk_native_buffer_usage_o_h_o_s.md) | 提供OpenHarmony NativeBuffer用途的说明。 | -| [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) | 包含了NaitveBuffer的属性。 | -| [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) | 包含了NaitveBuffer的一些格式属性。 | +| [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) | 包含了NativeBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) | 包含了NativeBuffer的一些格式属性。 | | [VkImportNativeBufferInfoOHOS](_vk_import_native_buffer_info_o_h_o_s.md) | 包含了OH_NativeBuffer结构体的指针。 | | [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) | 用于从Vulkan内存中获取OH_NativeBuffer。 | | [VkExternalFormatOHOS](_vk_external_format_o_h_o_s.md) | 表示外部定义的格式标识符。 | @@ -56,8 +56,8 @@ | [VkSurfaceCreateInfoOHOS](#vksurfacecreateinfoohos) | 包含创建Vulkan Surface时必要的参数。 | | VkResult ([VKAPI_PTR *PFN_vkCreateSurfaceOHOS](#pfn_vkcreatesurfaceohos)) (VkInstance instance, const [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) \*pCreateInfo, const VkAllocationCallbacks \*pAllocator, VkSurfaceKHR \*pSurface) | 创建Vulkan Surface的函数指针定义。 | | [VkNativeBufferUsageOHOS](#vknativebufferusageohos) | 提供OpenHarmony NativeBuffer用途的说明。 | -| [VkNativeBufferPropertiesOHOS](#vknativebufferpropertiesohos) | 包含了NaitveBuffer的属性。 | -| [VkNativeBufferFormatPropertiesOHOS](#vknativebufferformatpropertiesohos) | 包含了NaitveBuffer的一些格式属性。 | +| [VkNativeBufferPropertiesOHOS](#vknativebufferpropertiesohos) | 包含了NativeBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](#vknativebufferformatpropertiesohos) | 包含了NativeBuffer的一些格式属性。 | | [VkImportNativeBufferInfoOHOS](#vkimportnativebufferinfoohos) | 包含了OH_NativeBuffer结构体的指针。 | | [VkMemoryGetNativeBufferInfoOHOS](#vkmemorygetnativebufferinfoohos) | 用于从Vulkan内存中获取OH_NativeBuffer。 | | [VkExternalFormatOHOS](#vkexternalformatohos) | 表示外部定义的格式标识符。 | @@ -324,7 +324,7 @@ typedef struct VkNativeBufferFormatPropertiesOHOS VkNativeBufferFormatProperties **描述:** -包含了NaitveBuffer的一些格式属性。 +包含了NativeBuffer的一些格式属性。 ### VkNativeBufferPropertiesOHOS @@ -336,7 +336,7 @@ typedef struct VkNativeBufferPropertiesOHOS VkNativeBufferPropertiesOHOS **描述:** -包含了NaitveBuffer的属性。 +包含了NativeBuffer的属性。 ### VkNativeBufferUsageOHOS diff --git a/zh-cn/application-dev/reference/native-apis/context_8h.md b/zh-cn/application-dev/reference/native-apis/context_8h.md index c3ad71e2390393b7bcc1f8785770c3a8416db4ab..dd4277a4eec3273d1a03bc64ddb0d87465d50fc8 100644 --- a/zh-cn/application-dev/reference/native-apis/context_8h.md +++ b/zh-cn/application-dev/reference/native-apis/context_8h.md @@ -52,6 +52,7 @@ | [OH_AI_DeviceInfoSetFrequency](_mind_spore.md#oh_ai_deviceinfosetfrequency) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, int frequency) | 设置NPU的频率,仅NPU设备可用。 | | [OH_AI_DeviceInfoGetFrequency](_mind_spore.md#oh_ai_deviceinfogetfrequency) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | 获取NPU的频率类型,仅NPU设备可用。 | | [OH_AI_GetAllNNRTDeviceDescs](_mind_spore.md#oh_ai_getallnnrtdevicedescs) (size_t \*num) | 获取系统中所有NNRT硬件设备的描述信息。 | +| [OH_AI_GetElementOfNNRTDeviceDescs](_mind_spore.md#oh_ai_getelementofnnrtdevicedescs) (NNRTDeviceDesc \*descs, size_t index) | 获取NNRT设备描述信息数组中的元素指针。 | | [OH_AI_DestroyAllNNRTDeviceDescs](_mind_spore.md#oh_ai_destroyallnnrtdevicedescs) ([NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*\*desc) | 销毁从[OH_AI_GetAllNNRTDeviceDescs](_mind_spore.md#oh_ai_getallnnrtdevicedescs)获取的NNRT描写信息实例数组。 | | [OH_AI_GetDeviceIdFromNNRTDeviceDesc](_mind_spore.md#oh_ai_getdeviceidfromnnrtdevicedesc) (const [NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*desc) | 从特定的NNRT设备描述信息实例获取NNRT设备ID。注意,此ID只对NNRT有效。 | | [OH_AI_GetNameFromNNRTDeviceDesc](_mind_spore.md#oh_ai_getnamefromnnrtdevicedesc) (const [NNRTDeviceDesc](_mind_spore.md#nnrtdevicedesc) \*desc) | 从特定的NNRT设备描述信息实例获取NNRT设备名称。 | @@ -64,3 +65,4 @@ | [OH_AI_DeviceInfoGetPerformanceMode](_mind_spore.md#oh_ai_deviceinfogetperformancemode) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | 获取NNRT性能模式,仅NNRT设备可用。 | | [OH_AI_DeviceInfoSetPriority](_mind_spore.md#oh_ai_deviceinfosetpriority) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, [OH_AI_Priority](_mind_spore.md#oh_ai_priority) priority) | 设置NNRT任务优先级,仅NNRT设备可用。 | | [OH_AI_DeviceInfoGetPriority](_mind_spore.md#oh_ai_deviceinfogetpriority) (const [OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info) | 获取NNRT任务优先级,仅NNRT设备可用。 | +| [OH_AI_DeviceInfoAddExtension](_mind_spore.md#oh_ai_deviceinfoaddextension) ([OH_AI_DeviceInfoHandle](_mind_spore.md#oh_ai_deviceinfohandle) device_info, const char \*name, const char \*value, size_t value_size) | 向设备信息中添加键/值对形式的扩展配置。只对NNRT设备信息有效。 | diff --git a/zh-cn/application-dev/reference/native-apis/image.md b/zh-cn/application-dev/reference/native-apis/image.md index 444a82a797cdcacd21fb9fdbcaa175ade707f56b..acc95bc24a013abd06309388aa3c13e832938ff8 100644 --- a/zh-cn/application-dev/reference/native-apis/image.md +++ b/zh-cn/application-dev/reference/native-apis/image.md @@ -1,14 +1,14 @@ # Image -提供获取pixelmap的数据和信息的接口方法。 +## 概述 -@Syscap SystemCapability.Multimedia.Image +提供访问Image接口的方法,包括如何获取图片数据、获取PixelMap的数据和信息。 +\@Syscap SystemCapability.Multimedia.Image **起始版本:** - 8 @@ -17,686 +17,4092 @@ ### 文件 -| 文件名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | 声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。
**引用文件**:
**库**:libpixelmap_ndk.z.so| +| [image_mdk.h](image__mdk_8h.md) | 声明访问图像剪辑矩形、大小、格式和组件数据的函数。
**引用文件**:<multimedia/image_framework/image_mdk.h>
**库**:libimage_ndk.z.so | +| [image_mdk_common.h](image__mdk__common_8h.md) | 声明图像常用的枚举值和结构体。
**引用文件**:<multimedia/image_framework/image_mdk_common.h>
**库**:libimage_ndk.z.so | +| [image_pixel_map_mdk.h](image__pixel__map__mdk_8h.md) | 声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。
**引用文件**:<multimedia/image_framework/image_pixel_map_mdk.h>
**库**:libpixelmap_ndk.z.so | +| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | 声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。
**引用文件**:<multimedia/image_framework/image_pixel_map_napi.h>
**库**:libpixelmap_ndk.z.so | +| [image_receiver_mdk.h](image__receiver__mdk_8h.md) | 声明从native层获取图片数据的方法。
**引用文件**:<multimedia/image_framework/image_receiver_mdk.h>
**库**:libimage_receiver_ndk.z.so | +| [image_source_mdk.h](image__source__mdk_8h.md) | 声明将图片源解码成像素位图的方法。
**引用文件**:<multimedia/image_framework/image_source_mdk.h>
**库**:libimage_source_ndk.z.so | ### 结构体 -| 结构体名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 | -| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。| +| [OHOS::Media::OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) | 定义图像矩形信息。 | +| [OHOS::Media::OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) | 定义图像组成信息。 | +| [OhosImageSize](_ohos_image_size.md) | 定义图像大小。 | +| [OhosPixelMapInfos](_ohos_pixel_map_infos.md) | 用于定义 pixel map 的相关信息。 | +| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。 | +| [OHOS::Media::OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 | +| [OhosImageReceiverInfo](_ohos_image_receiver_info.md) | 定义**ImageReceiver**的相关信息。 | +| [OhosImageRegion](_ohos_image_region.md) | 定义图像源解码的范围选项。 | +| [OhosImageSourceOps](_ohos_image_source_ops.md) | 定义图像源选项信息。 | +| [OhosImageDecodingOps](_ohos_image_decoding_ops.md) | 定义图像源解码选项。 | +| [OhosImageSourceInfo](_ohos_image_source_info.md) | 定义图像源信息。 | +| [OhosImageSource](_ohos_image_source.md) | 定义图像源输入资源,每次仅接收一种类型。 | +| [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) | 定义图像源延迟时间列表。 | +| [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md) | 定义图像源支持的格式字符串。 | +| [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) | 定义图像源支持的格式字符串列表。 | +| [OhosImageSourceProperty](_ohos_image_source_property.md) | 定义图像源属性键值字符串。 | +| [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) | 定义图像源更新数据选项。 | ### 类型定义 | 名称 | 描述 | | -------- | -------- | -| [NativePixelMap](#nativepixelmap) | 用于定义NativePixelMap数据类型名称。| +| [OHOS::Media::ImageNative](#imagenative) | 为图像接口定义native层图像对象。 | +| [NativePixelMap](#nativepixelmap) | 定义native层pixelmap数据类型名称。 | +| [OhosPixelMapInfos](#ohospixelmapinfos) | 用于定义 pixel map 的相关信息。 | +| [ImageReceiverNative](#imagereceivernative) | 用于定义ImageReceiverNative数据类型名称。 | +| (\*[OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)) () | 定义native层图片的回调方法。 | +| [ImageSourceNative](#imagesourcenative) | 为图像源方法定义native层图像源对象。 | + +### 宏定义 +| 名称 | 描述 | +| -------- | -------- | +| **IMAGE_RESULT_BASE** 62980096 | 接口返回值的基础值 | ### 枚举 | 名称 | 描述 | | -------- | -------- | -| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | 函数方法返回值的错误码的枚举。| -| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | pixel 格式的枚举。| -| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | PixelMap alpha 类型的枚举。| -| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | PixelMap 缩放类型的枚举。| -| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | PixelMap 编辑类型的枚举。| +| { OHOS::Media::OHOS_IMAGE_FORMAT_YCBCR_422_SP = 1000,
OHOS::Media::OHOS_IMAGE_FORMAT_JPEG = 2000, } | 图像格式枚举值。 | +| { OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_Y = 1,
OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_U = 2,
OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_V = 3,
OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_JPEG = 4, } | 图像组成类型枚举值。 | +| [IRNdkErrCode](#irndkerrcode) {
IMAGE_RESULT_SUCCESS = 0,
IMAGE_RESULT_BAD_PARAMETER = -1,
IMAGE_RESULT_IMAGE_RESULT_BASE = IMAGE_RESULT_BASE,
IMAGE_RESULT_ERR_IPC = IMAGE_RESULT_BASE + 1,
IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST = IMAGE_RESULT_BASE + 2,
IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL = IMAGE_RESULT_BASE + 3,
IMAGE_RESULT_DECODE_ABNORMAL = IMAGE_RESULT_BASE + 4,
IMAGE_RESULT_DATA_ABNORMAL = IMAGE_RESULT_BASE + 5,
IMAGE_RESULT_MALLOC_ABNORMAL = IMAGE_RESULT_BASE + 6,
IMAGE_RESULT_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 7,
IMAGE_RESULT_INIT_ABNORMAL = IMAGE_RESULT_BASE + 8,
IMAGE_RESULT_GET_DATA_ABNORMAL = IMAGE_RESULT_BASE + 9,
IMAGE_RESULT_TOO_LARGE = IMAGE_RESULT_BASE + 10,
IMAGE_RESULT_TRANSFORM = IMAGE_RESULT_BASE + 11,
IMAGE_RESULT_COLOR_CONVERT = IMAGE_RESULT_BASE + 12,
IMAGE_RESULT_CROP = IMAGE_RESULT_BASE + 13,
IMAGE_RESULT_SOURCE_DATA = IMAGE_RESULT_BASE + 14,
IMAGE_RESULT_SOURCE_DATA_INCOMPLETE = IMAGE_RESULT_BASE + 15,
IMAGE_RESULT_MISMATCHED_FORMAT = IMAGE_RESULT_BASE + 16,
IMAGE_RESULT_UNKNOWN_FORMAT = IMAGE_RESULT_BASE + 17,
IMAGE_RESULT_SOURCE_UNRESOLVED = IMAGE_RESULT_BASE + 18,
IMAGE_RESULT_INVALID_PARAMETER = IMAGE_RESULT_BASE + 19,
IMAGE_RESULT_DECODE_FAILED = IMAGE_RESULT_BASE + 20,
IMAGE_RESULT_PLUGIN_REGISTER_FAILED = IMAGE_RESULT_BASE + 21,
IMAGE_RESULT_PLUGIN_CREATE_FAILED = IMAGE_RESULT_BASE + 22,
IMAGE_RESULT_ENCODE_FAILED = IMAGE_RESULT_BASE + 23,
IMAGE_RESULT_ADD_PIXEL_MAP_FAILED = IMAGE_RESULT_BASE + 24,
IMAGE_RESULT_HW_DECODE_UNSUPPORT = IMAGE_RESULT_BASE + 25,
IMAGE_RESULT_DECODE_HEAD_ABNORMAL = IMAGE_RESULT_BASE + 26,
IMAGE_RESULT_DECODE_EXIF_UNSUPPORT = IMAGE_RESULT_BASE + 27,
IMAGE_RESULT_PROPERTY_NOT_EXIST = IMAGE_RESULT_BASE + 28,
IMAGE_RESULT_MEDIA_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 30,
IMAGE_RESULT_MEDIA_TOO_LARGE = IMAGE_RESULT_BASE + 31,
IMAGE_RESULT_MEDIA_MALLOC_FAILED = IMAGE_RESULT_BASE + 32,
IMAGE_RESULT_MEDIA_END_OF_STREAM = IMAGE_RESULT_BASE + 33,
IMAGE_RESULT_MEDIA_IO_ABNORMAL = IMAGE_RESULT_BASE + 34,
IMAGE_RESULT_MEDIA_MALFORMED = IMAGE_RESULT_BASE + 35,
IMAGE_RESULT_MEDIA_BUFFER_TOO_SMALL = IMAGE_RESULT_BASE + 36,
IMAGE_RESULT_MEDIA_OUT_OF_RANGE = IMAGE_RESULT_BASE + 37,
IMAGE_RESULT_MEDIA_STATUS_ABNORMAL = IMAGE_RESULT_BASE + 38,
IMAGE_RESULT_MEDIA_VALUE_INVALID = IMAGE_RESULT_BASE + 39,
IMAGE_RESULT_MEDIA_NULL_POINTER = IMAGE_RESULT_BASE + 40,
IMAGE_RESULT_MEDIA_INVALID_OPERATION = IMAGE_RESULT_BASE + 41,
IMAGE_RESULT_MEDIA_ERR_PLAYER_NOT_INIT = IMAGE_RESULT_BASE + 42,
IMAGE_RESULT_MEDIA_EARLY_PREPARE = IMAGE_RESULT_BASE + 43,
IMAGE_RESULT_MEDIA_SEEK_ERR = IMAGE_RESULT_BASE + 44,
IMAGE_RESULT_MEDIA_PERMISSION_DENIED = IMAGE_RESULT_BASE + 45,
IMAGE_RESULT_MEDIA_DEAD_OBJECT = IMAGE_RESULT_BASE + 46,
IMAGE_RESULT_MEDIA_TIMED_OUT = IMAGE_RESULT_BASE + 47,
IMAGE_RESULT_MEDIA_TRACK_NOT_ALL_SUPPORTED = IMAGE_RESULT_BASE + 48,
IMAGE_RESULT_MEDIA_ADAPTER_INIT_FAILED = IMAGE_RESULT_BASE + 49,
IMAGE_RESULT_MEDIA_WRITE_PARCEL_FAIL = IMAGE_RESULT_BASE + 50,
IMAGE_RESULT_MEDIA_READ_PARCEL_FAIL = IMAGE_RESULT_BASE + 51,
IMAGE_RESULT_MEDIA_NO_AVAIL_BUFFER = IMAGE_RESULT_BASE + 52,
IMAGE_RESULT_MEDIA_INVALID_PARAM = IMAGE_RESULT_BASE + 53, IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 54,
IMAGE_RESULT_MEDIA_CREATE_CODEC_ADAPTER_FAILED = IMAGE_RESULT_BASE + 55,
IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 56,
IMAGE_RESULT_MEDIA_ZCODEC_CREATE_FAILED = IMAGE_RESULT_BASE + 57,
IMAGE_RESULT_MEDIA_ZCODEC_NOT_EXIST = IMAGE_RESULT_BASE + 58,
IMAGE_RESULT_MEDIA_JNI_CLASS_NOT_EXIST = IMAGE_RESULT_BASE + 59,
IMAGE_RESULT_MEDIA_JNI_METHOD_NOT_EXIST = IMAGE_RESULT_BASE + 60,
IMAGE_RESULT_MEDIA_JNI_NEW_OBJ_FAILED = IMAGE_RESULT_BASE + 61,
IMAGE_RESULT_MEDIA_JNI_COMMON_ERROR = IMAGE_RESULT_BASE + 62,
IMAGE_RESULT_MEDIA_DISTRIBUTE_NOT_SUPPORT = IMAGE_RESULT_BASE + 63,
IMAGE_RESULT_MEDIA_SOURCE_NOT_SET = IMAGE_RESULT_BASE + 64,
IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 65,
IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 66,
IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT = IMAGE_RESULT_BASE + 67,
IMAGE_RESULT_MEDIA_RTSP_CAPTURE_NOT_INIT = IMAGE_RESULT_BASE + 68,
IMAGE_RESULT_MEDIA_RTSP_SOURCE_URL_INVALID = IMAGE_RESULT_BASE + 69,
IMAGE_RESULT_MEDIA_RTSP_VIDEO_TRACK_NOT_FOUND = IMAGE_RESULT_BASE + 70,
IMAGE_RESULT_MEDIA_RTSP_CAMERA_NUM_REACH_MAX = IMAGE_RESULT_BASE + 71,
IMAGE_RESULT_MEDIA_SET_VOLUME = IMAGE_RESULT_BASE + 72,
IMAGE_RESULT_MEDIA_NUMBER_OVERFLOW = IMAGE_RESULT_BASE + 73,
IMAGE_RESULT_MEDIA_DIS_PLAYER_UNSUPPORTED = IMAGE_RESULT_BASE + 74,
IMAGE_RESULT_MEDIA_DENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 75,
IMAGE_RESULT_MEDIA_ENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 76,
IMAGE_RESULT_MEDIA_READ_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 150,
IMAGE_RESULT_MEDIA_WRITE_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 151,
IMAGE_RESULT_MEDIA_PIXELMAP_NOT_ALLOW_MODIFY = IMAGE_RESULT_BASE + 152,
IMAGE_RESULT_MEDIA_CONFIG_FAILED = IMAGE_RESULT_BASE + 153,
IMAGE_RESULT_JNI_ENV_ABNORMAL = IMAGE_RESULT_BASE + 154,
IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED = IMAGE_RESULT_BASE + 155,
IMAGE_RESULT_CREATE_SURFACE_FAILED = IMAGE_RESULT_BASE + 156,
IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED = IMAGE_RESULT_BASE + 157,
IMAGE_RESULT_GET_SURFACE_FAILED = IMAGE_RESULT_BASE + 158,
IMAGE_RESULT_SURFACE_ACQUIRE_BUFFER_FAILED = IMAGE_RESULT_BASE + 159,
IMAGE_RESULT_SURFACE_REQUEST_BUFFER_FAILED = IMAGE_RESULT_BASE + 160,
IMAGE_RESULT_REGISTER_LISTENER_FAILED = IMAGE_RESULT_BASE + 161,
IMAGE_RESULT_REGISTER_BUFFER_FAILED = IMAGE_RESULT_BASE + 162,
IMAGE_RESULT_FREAD_FAILED = IMAGE_RESULT_BASE + 163,
IMAGE_RESULT_PEEK_FAILED = IMAGE_RESULT_BASE + 164,
IMAGE_RESULT_SEEK_FAILED = IMAGE_RESULT_BASE + 165,
IMAGE_RESULT_STREAM_SIZE_ERROR = IMAGE_RESULT_BASE + 166,
IMAGE_RESULT_FILE_FD_ERROR = IMAGE_RESULT_BASE + 167,
IMAGE_RESULT_FILE_DAMAGED = IMAGE_RESULT_BASE + 168,
IMAGE_RESULT_CREATE_DECODER_FAILED = IMAGE_RESULT_BASE + 169,
IMAGE_RESULT_CREATE_ENCODER_FAILED = IMAGE_RESULT_BASE + 170,
IMAGE_RESULT_CHECK_FORMAT_ERROR = IMAGE_RESULT_BASE + 171,
IMAGE_RESULT_THIRDPART_SKIA_ERROR = IMAGE_RESULT_BASE + 172,
IMAGE_RESULT_HW_DECODE_FAILED = IMAGE_RESULT_BASE + 173,
IMAGE_RESULT_ALLOCATER_TYPE_ERROR = IMAGE_RESULT_BASE + 174,
IMAGE_RESULT_ALPHA_TYPE_ERROR = IMAGE_RESULT_BASE + 175,
IMAGE_RESULT_INDEX_INVALID = IMAGE_RESULT_BASE + 176,
IMAGE_RESULT_MEDIA_UNKNOWN = IMAGE_RESULT_BASE + 200
} | 可能出现的返回值的枚举。 | +| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0,
OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1,
OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2,
OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | PixelMap 透明度类型的枚举。 | +| { OHOS_PIXEL_MAP_READ_ONLY = 0,
OHOS_PIXEL_MAP_EDITABLE = 1 } | PixelMap 编辑类型的枚举。 | +| { OHOS::Media::OHOS_IMAGE_RESULT_SUCCESS = 0,
OHOS::Media::OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | 函数方法返回值的错误码的枚举。 | +| { OHOS::Media::OHOS_PIXEL_MAP_FORMAT_NONE = 0,
OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3,
OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | pixel 格式的枚举。 | +| { OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0,
OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | PixelMap 缩放类型的枚举。 | ### 函数 | 名称 | 描述 | | -------- | -------- | -| [OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_ohos_pixel_map_info.md)结构中。| -| [OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。| -| [OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法[OH_AccessPixels](#oh_accesspixels)。| -| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。| -| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。| -| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。| -| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。| -| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*[editable](image__pixel__map__napi_8h.md#editable)) | 获取**PixelMap**对象是否可编辑的状态。| -| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。| -| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。| -| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。| -| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。| -| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。| -| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。| -| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。| -| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。| -| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。| -| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](image__pixel__map__napi_8h.md#width), int32_t [height](image__pixel__map__napi_8h.md#height)) | 设置**PixelMap**对象的裁剪。| +| [OHOS::Media::OH_Image_InitImageNative](#oh_image_initimagenative) (napi_env env, napi_value source) | 从输入的JavaScript Native API **图像** 对象中解析 native **ImageNative** 对象。 | +| [OHOS::Media::OH_Image_ClipRect](#oh_image_cliprect) (const [ImageNative](#imagenative) \*native, struct [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) \*rect) | 获取native **ImageNative** 对象 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 信息。 | +| [OHOS::Media::OH_Image_Size](#oh_image_size) (const [ImageNative](#imagenative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 获取native **ImageNative** 对象的 [OhosImageSize](_ohos_image_size.md) 信息。 | +| [OHOS::Media::OH_Image_Format](#oh_image_format) (const [ImageNative](#imagenative) \*native, int32_t \*format) | 获取native **ImageNative** 对象的图像格式。 | +| [OHOS::Media::OH_Image_GetComponent](#oh_image_getcomponent) (const [ImageNative](#imagenative) \*native, int32_t componentType, struct [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) \*componentNative) | 从 native **ImageNative** 对象中获取 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)。 | +| [OHOS::Media::OH_Image_Release](#oh_image_release) ([ImageNative](#imagenative) \*native) | 释放 **ImageNative** native对象。 | +| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。 | +| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 | +| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。 | +| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。 | +| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*editable) | 获取**PixelMap**对象是否可编辑的状态。 | +| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。 | +| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。 | +| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。 | +| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。 | +| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。 | +| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。 | +| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。 | +| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。 | +| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。 | +| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t width, int32_t height) | 设置**PixelMap**对象的裁剪。 | +| [OH_PixelMap_GetImageInfo](#oh_pixelmap_getimageinfo) (const [NativePixelMap](#nativepixelmap) \*native, [OhosPixelMapInfos](_ohos_pixel_map_infos.md) \*info) | 获取**PixelMap**对象图像信息。 | +| [OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels) (const [NativePixelMap](#nativepixelmap) \*native, void \*\*addr) | 获取native **PixelMap** 对象数据的内存地址,并锁定该内存。 | +| [OH_PixelMap_UnAccessPixels](#oh_pixelmap_unaccesspixels) (const [NativePixelMap](#nativepixelmap) \*native) | 释放native **PixelMap**对象数据的内存锁,用于匹配方法 [OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels)。 | +| [OHOS::Media::OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)结构中。 | +| [OHOS::Media::OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。 | +| [OHOS::Media::OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法**OH_AccessPixels**。 | +| [OH_Image_Receiver_CreateImageReceiver](#oh_image_receiver_createimagereceiver) (napi_env env, struct [OhosImageReceiverInfo](_ohos_image_receiver_info.md) info, napi_value \*res) | 创建应用层 **ImageReceiver** 对象。 | +| [OH_Image_Receiver_InitImageReceiverNative](#oh_image_receiver_initimagereceivernative) (napi_env env, napi_value source) | 通过应用层**ImageReceiver**对象初始化native层[ImageReceiverNative](#imagereceivernative)对象。 | +| [OH_Image_Receiver_GetReceivingSurfaceId](#oh_image_receiver_getreceivingsurfaceid) (const [ImageReceiverNative](#imagereceivernative) \*native, char \*id, size_t len) | 通过[ImageReceiverNative](#imagereceivernative)获取receiver的id。 | +| [OH_Image_Receiver_ReadLatestImage](#oh_image_receiver_readlatestimage) (const [ImageReceiverNative](#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](#imagereceivernative)获取最新的一张图片。 | +| [OH_Image_Receiver_ReadNextImage](#oh_image_receiver_readnextimage) (const [ImageReceiverNative](#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](#imagereceivernative)获取下一张图片。 | +| [OH_Image_Receiver_On](#oh_image_receiver_on) (const [ImageReceiverNative](#imagereceivernative) \*native, [OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback) callback) | 注册一个[OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)回调事件。每当接收新图片,该回调事件就会响应。 | +| [OH_Image_Receiver_GetSize](#oh_image_receiver_getsize) (const [ImageReceiverNative](#imagereceivernative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的大小。 | +| [OH_Image_Receiver_GetCapacity](#oh_image_receiver_getcapacity) (const [ImageReceiverNative](#imagereceivernative) \*native, int32_t \*capacity) | 通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的容量。 | +| [OH_Image_Receiver_GetFormat](#oh_image_receiver_getformat) (const [ImageReceiverNative](#imagereceivernative) \*native, int32_t \*format) | 通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的格式。 | +| [OH_Image_Receiver_Release](#oh_image_receiver_release) ([ImageReceiverNative](#imagereceivernative) \*native) | 释放native层 [ImageReceiverNative](#imagereceivernative) 对象。注意: 此方法不能释放应用层**ImageReceiver**对象。 | +| [OH_ImageSource_Create](#oh_imagesource_create) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*src, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的信息[OhosImageSource](_ohos_image_source.md) 和[OhosImageSourceOps](_ohos_image_source_ops.md)结构体,获取JavaScript native层API**ImageSource**对象。 | +| [OH_ImageSource_CreateIncremental](#oh_imagesource_createincremental) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*source, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的infomations[OhosImageSource](_ohos_image_source.md)和[OhosImageSourceOps](_ohos_image_source_ops.md)结构, 获取增量类型的JavaScript Native API ImageSource对象,图像数据应通过OH_ImageSource_UpdateData更新。 | +| [OH_ImageSource_GetSupportedFormats](#oh_imagesource_getsupportedformats) (struct [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) \*res) | 获取所有支持的解码格式元标记。 | +| [OH_ImageSource_InitNative](#oh_imagesource_initnative) (napi_env env, napi_value source) | 从输入JavaScript native层API **ImageSource** 对象中,转换成[ImageSourceNative](#imagesourcenative)值。 | +| [OH_ImageSource_CreatePixelMap](#oh_imagesource_createpixelmap) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码JavaScript native层API**PixelMap**对象 | +| [OH_ImageSource_CreatePixelMapList](#oh_imagesource_createpixelmaplist) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码所有的JavaScript native层API**PixelMap**对象列表 | +| [OH_ImageSource_GetDelayTime](#oh_imagesource_getdelaytime) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) \*res) | 从一些**ImageSource**(如GIF图像源)获取延迟时间列表。 | +| [OH_ImageSource_GetFrameCount](#oh_imagesource_getframecount) (const [ImageSourceNative](#imagesourcenative) \*native, uint32_t \*res) | 从**ImageSource**中获取帧计数。 | +| [OH_ImageSource_GetImageInfo](#oh_imagesource_getimageinfo) (const [ImageSourceNative](#imagesourcenative) \*native, int32_t index, struct [OhosImageSourceInfo](_ohos_image_source_info.md) \*info) | 通过索引从**ImageSource**获取图像源信息。 | +| [OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字从**ImageSource**中获取图像源属性。 | +| [OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字为**ImageSource**修改图像源属性。 | +| [OH_ImageSource_UpdateData](#oh_imagesource_updatedata) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) \*data) | 为了增量类型的**ImageSource**更新源数据。 | +| [OH_ImageSource_Release](#oh_imagesource_release) ([ImageSourceNative](#imagesourcenative) \*native) | 释放native层图像源 **ImageSourceNative**。 | + + +### 变量 + +| 名称 | 描述 | +| -------- | -------- | +| [OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE](#ohos_image_property_bits_per_sample) = "BitsPerSample" | 定义每个样本比特的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_ORIENTATION](#ohos_image_property_orientation) = "Orientation" | 定义方向的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_IMAGE_LENGTH](#ohos_image_property_image_length) = "ImageLength" | 定义图像长度的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_IMAGE_WIDTH](#ohos_image_property_image_width) = "ImageWidth" | 定义图像宽度的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_GPS_LATITUDE](#ohos_image_property_gps_latitude) = "GPSLatitude" | 定义GPS纬度的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_GPS_LONGITUDE](#ohos_image_property_gps_longitude) = "GPSLongitude" | 定义GPS经度的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF](#ohos_image_property_gps_latitude_ref) = "GPSLatitudeRef" | 定义GPS纬度参考的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF](#ohos_image_property_gps_longitude_ref) = "GPSLongitudeRef" | 定义GPS经度参考的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL](#ohos_image_property_date_time_original) = "DateTimeOriginal" | 定义初始日期时间的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_EXPOSURE_TIME](#ohos_image_property_exposure_time) = "ExposureTime" | 定义曝光时间的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_SCENE_TYPE](#ohos_image_property_scene_type) = "SceneType" | 定义场景类型的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS](#ohos_image_property_iso_speed_ratings) = "ISOSpeedRatings" | 定义ISO速度等级的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_F_NUMBER](#ohos_image_property_f_number) = "FNumber" | 定义FNumber的图像属性关键字。 | +| [OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL](#ohos_image_property_compressed_bits_per_pixel) = "CompressedBitsPerPixel" | 定义每个像素的压缩比特的图像属性关键字。 | +| [OhosImageRegion::x](#x) | 起始x坐标,用pixels表示 | +| [OhosImageRegion::y](#y) | 起始y坐标,用pixels表示 | +| [OhosImageRegion::width](#width) | 宽度范围,用pixels表示 | +| [OhosImageRegion::height](#height) | 高度范围,用pixels表示 | +| [OhosImageSourceOps::density](#density-12) | 图像源像素密度 | +| [OhosImageSourceOps::pixelFormat](#pixelformat-13) | 图像源像素格式,通常用于描述YUV缓冲区 | +| [OhosImageSourceOps::size](#size-17) | 图像源像素宽高的大小 | +| [OhosImageDecodingOps::editable](#editable) | 定义输出的像素位图是否可编辑 | +| [OhosImageDecodingOps::pixelFormat](#pixelformat-23) | 定义输出的像素格式 | +| [OhosImageDecodingOps::fitDensity](#fitdensity) | 定义解码目标的像素密度 | +| [OhosImageDecodingOps::index](#index) | 定义图像源解码指数 | +| [OhosImageDecodingOps::sampleSize](#samplesize) | 定义解码样本大小选项 | +| [OhosImageDecodingOps::rotate](#rotate) | 定义解码旋转选项 | +| [OhosImageDecodingOps::size](#size-27) | 定义解码目标像素宽高的大小 | +| [OhosImageDecodingOps::region](#region) | 定义图像源解码的像素范围 | +| [OhosImageSourceInfo::pixelFormat](#pixelformat-33) | 图像源像素格式, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置 | +| [OhosImageSourceInfo::colorSpace](#colorspace) | 图像源色彩空间 | +| [OhosImageSourceInfo::alphaType](#alphatype) | 图像源透明度类型 | +| [OhosImageSourceInfo::density](#density-22) | 图像源密度, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置 | +| [OhosImageSourceInfo::size](#size-37) | 图像源像素宽高的大小 | +| [OhosImageSource::uri](#uri) = nullptr | 图像源资源标识符,接受文件资源或者base64资源 | +| [OhosImageSource::uriSize](#urisize) = 0 | 图像源资源长度 | +| [OhosImageSource::fd](#fd) = -1 | 图像源文件资源描述符 | +| [OhosImageSource::buffer](#buffer-12) = nullptr | 图像源缓冲区资源,解手格式化包缓冲区或者base64缓冲区 | +| [OhosImageSource::bufferSize](#buffersize-12) = 0 | 图像源缓冲区资源大小 | +| [OhosImageSourceDelayTimeList::delayTimeList](#delaytimelist) | 图像源延迟时间列表头地址 | +| [OhosImageSourceDelayTimeList::size](#size-47) = 0 | 图像源延迟时间列表大小 | +| [OhosImageSourceSupportedFormat::format](#format) = nullptr | 图像源支持的格式字符串头地址 | +| [OhosImageSourceSupportedFormat::size](#size-57) = 0 | 图像源支持的格式字符串大小 | +| [OhosImageSourceSupportedFormatList::supportedFormatList](#supportedformatlist) = nullptr | 图像源支持的格式字符串列表头地址 | +| [OhosImageSourceSupportedFormatList::size](#size-67) = 0 | 图像源支持的格式字符串列表大小 | +| [OhosImageSourceProperty::value](#value) = nullptr | 定义图像源属性键值字符串头地址 | +| [OhosImageSourceProperty::size](#size-77) = 0 | 定义图像源属性键值字符串大小 | +| [OhosImageSourceUpdateData::buffer](#buffer-22) = nullptr | 图像源更新数据缓冲区 | +| [OhosImageSourceUpdateData::bufferSize](#buffersize-22) = 0 | 图像源更新数据缓冲区大小 | +| [OhosImageSourceUpdateData::offset](#offset) = 0 | 图像源更新数据缓冲区的开端 | +| [OhosImageSourceUpdateData::updateLength](#updatelength) = 0 | 图像源更新数据缓冲区的更新数据长度 | +| [OhosImageSourceUpdateData::isCompleted](#iscompleted) = 0 | 图像源更新数据在此节中完成 | ## 类型定义说明 -### NativePixelMap +### ImageNative + - ``` -typedef struct NativePixelMap +typedef struct ImageNative_ OHOS::Media::ImageNative ``` -**描述:** -用于定义NativePixelMap数据类型名称。 -**起始版本:** -10 +**描述:** +为图像接口定义native层图像对象。 -## 枚举类型说明 +**起始版本:** + +10 -### anonymous enum +### ImageReceiverNative - ``` -anonymous enum +typedef struct ImageReceiverNative_ ImageReceiverNative ``` -**描述:** -函数方法返回值的错误码的枚举。 -| 枚举值 | 描述 | -| -------- | -------- | -| OHOS_IMAGE_RESULT_SUCCESS| 成功的结果 | -| OHOS_IMAGE_RESULT_BAD_PARAMETER| 无效值 | +**描述:** + +用于定义ImageReceiverNative数据类型名称。 **起始版本:** -8 -### anonymous enum +10 + + +### ImageSourceNative - ``` -anonymous enum +typedef struct ImageSourceNative_ ImageSourceNative ``` -**描述:** -pixel 格式的枚举。 -| 枚举值 | 描述 | -| -------- | -------- | -| OHOS_PIXEL_MAP_FORMAT_NONE| 未知的格式 | -| OHOS_PIXEL_MAP_FORMAT_RGBA_8888| 32-bit RGBA。 由 R, G, B组成,包括 A 都需要占用 8 bits。存储顺序是从高位到低位。 | -| OHOS_PIXEL_MAP_FORMAT_RGB_565| 16-bit RGB。 仅由 R, G, B 组成. 存储顺序是从高位到低位: 红色占用5 bits,绿色占用6 bits,蓝色占用5 bits。 | +**描述:** + +为图像源方法定义native层图像源对象。 + +\@Syscap SystemCapability.Multimedia.Image **起始版本:** -8 -### anonymous enum +10 + + +### NativePixelMap - ``` -anonymous enum +typedef struct NativePixelMap_ NativePixelMap ``` -**描述:** -PixelMap alpha 类型的枚举。 -| 枚举值 | 描述 | -| -------- | -------- | -| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN| 未知的格式 | -| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE| 不透明的格式 | -| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL| 预乘的格式 | -| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL| 预除的格式 | +**描述:** + +定义native层pixelmap数据类型名称。 + +**起始版本:** -**起始版本:** 10 -### anonymous enum - +### OH_Image_Receiver_On_Callback + ``` -anonymous enum +typedef void(* OH_Image_Receiver_On_Callback) () ``` -**描述:** -PixelMap 缩放类型的枚举。 -| 枚举值 | 描述 | -| -------- | -------- | -| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE| 适应目标图片大小的格式 | -| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP| 以中心进行缩放的格式 | +**描述:** + +定义native层图片的回调方法。 + +**起始版本:** -**起始版本:** 10 -### anonymous enum +### OhosPixelMapInfos - ``` -anonymous enum +typedef struct OhosPixelMapInfosOhosPixelMapInfos ``` -**描述:** -PixelMap 编辑类型的枚举。 -| 枚举值 | 描述 | -| -------- | -------- | -| OHOS_PIXEL_MAP_READ_ONLY| 只读的格式 | -| OHOS_PIXEL_MAP_EDITABLE| 可编辑的格式 | +**描述:** + +用于定义 pixel map 的相关信息。 + +**起始版本:** -**起始版本:** 10 -## 函数说明 +## 枚举类型说明 -### OH_AccessPixels() +### anonymous enum [1/3] - ``` -int32_t OH_AccessPixels (napi_env env, napi_value value, void ** addrPtr ) +anonymous enum ``` -**描述:** -获取**PixelMap**对象数据的内存地址,并锁定该内存。 -函数执行成功后,**\*addrPtr**就是获取的待访问的内存地址. 访问操作完成后,必须要使用[OH_UnAccessPixels](#oh_unaccesspixels)来释放锁, 否则的话资源无法被释放. 待解锁后,内存地址就不可以再被访问和操作。 +**描述:** -**参数:** +图像格式枚举值。 -| 名称 | 描述 | +**起始版本:** + +10 + +| 枚举值 | 描述 | | -------- | -------- | -| env | napi的环境指针。| -| value | 应用层的 **PixelMap** 对象。| -| addrPtr | 用于指向的内存地址的双指针对象。| +| OHOS_IMAGE_FORMAT_YCBCR_422_SP | YCBCR422 semi-planar 格式 | +| OHOS_IMAGE_FORMAT_JPEG | JPEG 编码格式 | -**参见:** -UnAccessPixels +### anonymous enum [2/3] -**返回:** +``` +anonymous enum +``` + +**描述:** -操作成功则返回 OHOS_IMAGE_RESULT_SUCCESS; 如果操作失败,则返回错误码。 +PixelMap 透明度类型的枚举。 **起始版本:** -8 +10 + +| 枚举值 | 描述 | +| -------- | -------- | +| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN | 未知的格式 | +| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE | 不透明的格式 | +| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL | 预乘的格式 | +| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL | 预除的格式 | -### OH_GetImageInfo() - +### anonymous enum [3/3] + ``` -struct OhosPixelMapCreateOps OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) +anonymous enum ``` -**描述:** -获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_ohos_pixel_map_info.md)结构中。 -**参数:** +**描述:** -| 名称 | 描述 | -| -------- | -------- | -| env | napi的环境指针。| -| value | 应用层的 **PixelMap** 对象。| -| info | 用于保存信息的指针对象. 更多细节, 参看 [OhosPixelMapInfo](_ohos_pixel_map_info.md)。| +函数方法返回值的错误码的枚举。 -**返回:** +**起始版本:** -如果获取并保存信息成功,则返回**0**; 如果操作失败,则返回错误码。 +8 -**参见:** +**废弃起始版本:** -[OhosPixelMapInfo](_ohos_pixel_map_info.md) +10 -**起始版本:** -8 +| 枚举值 | 描述 | +| -------- | -------- | +| OHOS_IMAGE_RESULT_SUCCESS | 成功的结果 | +| OHOS_IMAGE_RESULT_BAD_PARAMETER | 无效值 | -### OH_PixelMap_CreateAlphaPixelMap() +### anonymous enum [1/3] - ``` -int32_t OH_PixelMap_CreateAlphaPixelMap (napi_env env, napi_value source, napi_value * alpha ) +anonymous enum ``` -**描述:** -根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 -**参数:** +**描述:** -| 名称 | 描述 | +图像组成类型枚举值。 + +**起始版本:** + +10 + +| 枚举值 | 描述 | | -------- | -------- | -| env | napi的环境指针。| -| source | **PixelMap**数据设置项。| -| alpha | alpha通道的指针。| +| OHOS_IMAGE_COMPONENT_FORMAT_YUV_Y | 亮度信息 | +| OHOS_IMAGE_COMPONENT_FORMAT_YUV_U | 色度信息 | +| OHOS_IMAGE_COMPONENT_FORMAT_YUV_V | 色差值信息 | +| OHOS_IMAGE_COMPONENT_FORMAT_JPEG | Jpeg 格式 | -**返回:** -操作成功则返回 **PixelMap** 对象; 如果操作失败,则返回错误码。 +### anonymous enum [2/3] -**参见:** +``` +anonymous enum +``` -CreateAlphaPixelMap +**描述:** + +PixelMap 编辑类型的枚举。 + +**起始版本:** -**起始版本:** 10 +| 枚举值 | 描述 | +| -------- | -------- | +| OHOS_PIXEL_MAP_READ_ONLY | 只读的格式 | +| OHOS_PIXEL_MAP_EDITABLE | 可编辑的格式 | + -### OH_PixelMap_CreatePixelMap() +### anonymous enum [3/3] - ``` -int32_t OH_PixelMap_CreatePixelMap (napi_env env, OhosPixelMapCreateOps info, void * buf, size_t len, napi_value * res ) +anonymous enum ``` -**描述:** -创建**PixelMap**对象. - -**参数:** -| 名称 | 描述 | -| -------- | -------- | -| env | napi的环境指针。| -| info | pixel map 数据设置项。| -| buf | 图片的buffer数据。| -| len | 图片大小信息。| -| res | 应用层的 **PixelMap** 对象的指针。| +**描述:** -**返回:** +pixel 格式的枚举。 -操作成功则返回 **PixelMap** 对象; 如果操作失败,则返回错误码。 +**起始版本:** -**参见:** +8 -CreatePixelMap +**废弃起始版本:** -**起始版本:** 10 +| 枚举值 | 描述 | +| -------- | -------- | +| OHOS_PIXEL_MAP_FORMAT_NONE | 未知的格式 | +| OHOS_PIXEL_MAP_FORMAT_RGBA_8888 | 32-bit RGBA. 由 R, G, B组成,包括 A 都需要占用 8 bits。存储顺序是从高位到低位。 | +| OHOS_PIXEL_MAP_FORMAT_RGB_565 | 16-bit RGB. 仅由 R, G, B 组成。 存储顺序是从高位到低位: 红色占用5 bits,绿色占用6 bits,蓝色占用5 bits。 | + -### OH_PixelMap_Crop() +### anonymous enum - ``` -int32_t OH_PixelMap_Crop (const NativePixelMap * native, int32_t x, int32_t y, int32_t width, int32_t height ) +anonymous enum ``` -**描述:** -设置**PixelMap**对象的裁剪. - -**参数:** - -| 名称 | 描述 | -| -------- | -------- | -| native | NativePixelMap的指针。| -| x | 目标图片左上角的x坐标。| -| y | 目标图片左上角的y坐标。| -| width | 裁剪区域的宽度。| -| height | 裁剪区域的高度。| -**返回:** - -操作成功则返回**0**; 如果操作失败,则返回错误码。 +**描述:** -**参见:** +PixelMap 缩放类型的枚举。 -Crop +**起始版本:** -**起始版本:** 10 +| 枚举值 | 描述 | +| -------- | -------- | +| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE | 适应目标图片大小的格式 | +| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP | 以中心进行缩放的格式 | + -### OH_PixelMap_Flip() +### IRNdkErrCode - ``` -int32_t OH_PixelMap_Flip (const NativePixelMap * native, int32_t x, int32_t y ) +enum IRNdkErrCode ``` -**描述:** -设置**PixelMap**对象的翻转. -**参数:** +**描述:** -| 名称 | 描述 | -| -------- | -------- | -| native | NativePixelMap的指针。| -| x | 根据水平方向x轴进行图片翻转。| -| y | 根据垂直方向y轴进行图片翻转。| +可能被使用的接口返回值的枚举。 -**返回:** +**起始版本:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +10 -**参见:** +| 枚举值 | 描述 | +| -------- | -------- | +| IMAGE_RESULT_SUCCESS | 操作成功 | +| IMAGE_RESULT_BAD_PARAMETER | 无效参数 | +| IMAGE_RESULT_IMAGE_RESULT_BASE | 操作失败 | +| IMAGE_RESULT_ERR_IPC | ipc 错误 | +| IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST | 共享内存失败 | +| IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL | 共享内存数据异常 | +| IMAGE_RESULT_DECODE_ABNORMAL | 图像解码失败 | +| IMAGE_RESULT_DATA_ABNORMAL | 图像输入数据异常 | +| IMAGE_RESULT_MALLOC_ABNORMAL | 图像内存分配异常 | +| IMAGE_RESULT_DATA_UNSUPPORT | 图像类型不支持 | +| IMAGE_RESULT_INIT_ABNORMAL | 图像初始化失败 | +| IMAGE_RESULT_GET_DATA_ABNORMAL | 图像获取数据错误 | +| IMAGE_RESULT_TOO_LARGE | 图像数据过大 | +| IMAGE_RESULT_TRANSFORM | 图像转换错误 | +| IMAGE_RESULT_COLOR_CONVERT | 图像颜色转换错误 | +| IMAGE_RESULT_CROP | 裁剪错误 | +| IMAGE_RESULT_SOURCE_DATA | 图像源数据错误 | +| IMAGE_RESULT_SOURCE_DATA_INCOMPLETE | 图像源数据不完整 | +| IMAGE_RESULT_MISMATCHED_FORMAT | 图像格式不匹配 | +| IMAGE_RESULT_UNKNOWN_FORMAT | 图像未知格式 | +| IMAGE_RESULT_SOURCE_UNRESOLVED | 图像源未解析 | +| IMAGE_RESULT_INVALID_PARAMETER | 图像无效参数 | +| IMAGE_RESULT_DECODE_FAILED | 解码失败 | +| IMAGE_RESULT_PLUGIN_REGISTER_FAILED | 注册插件失败 | +| IMAGE_RESULT_PLUGIN_CREATE_FAILED | 创建插件失败 | +| IMAGE_RESULT_ENCODE_FAILED | 图像编码失败 | +| IMAGE_RESULT_ADD_PIXEL_MAP_FAILED | 图像添加像素位图失败 | +| IMAGE_RESULT_HW_DECODE_UNSUPPORT | 图像硬解码不支持 | +| IMAGE_RESULT_DECODE_HEAD_ABNORMAL | 图像头解码失败 | +| IMAGE_RESULT_DECODE_EXIF_UNSUPPORT | 图像解码EXIF不支持 | +| IMAGE_RESULT_PROPERTY_NOT_EXIST | 图像属性不存在 | +| IMAGE_RESULT_MEDIA_DATA_UNSUPPORT | 媒体类型不支持 | +| IMAGE_RESULT_MEDIA_TOO_LARGE | 媒体数据过大 | +| IMAGE_RESULT_MEDIA_MALLOC_FAILED | 媒体分配内存失败 | +| IMAGE_RESULT_MEDIA_END_OF_STREAM | 媒体数据流结束失败 | +| IMAGE_RESULT_MEDIA_IO_ABNORMAL | 媒体输入输出流异常 | +| IMAGE_RESULT_MEDIA_MALFORMED | 媒体功能异常 | +| IMAGE_RESULT_MEDIA_BUFFER_TOO_SMALL | 媒体数据过小错误 | +| IMAGE_RESULT_MEDIA_OUT_OF_RANGE | 媒体超出范围错误 | +| IMAGE_RESULT_MEDIA_STATUS_ABNORMAL | 媒体状态异常错误 | +| IMAGE_RESULT_MEDIA_VALUE_INVALID | 媒体值无效 | +| IMAGE_RESULT_MEDIA_NULL_POINTER | 媒体操作失败 | +| IMAGE_RESULT_MEDIA_INVALID_OPERATION | 媒体操作无效 | +| IMAGE_RESULT_MEDIA_ERR_PLAYER_NOT_INIT | 媒体初始化异常 | +| IMAGE_RESULT_MEDIA_EARLY_PREPARE | 媒体过早预处理 | +| IMAGE_RESULT_MEDIA_SEEK_ERR | 媒体查找失败 | +| IMAGE_RESULT_MEDIA_PERMISSION_DENIED | 媒体权限拒绝 | +| IMAGE_RESULT_MEDIA_DEAD_OBJECT | 媒体对象注销 | +| IMAGE_RESULT_MEDIA_TIMED_OUT | 媒体超时 | +| IMAGE_RESULT_MEDIA_TRACK_NOT_ALL_SUPPORTED | 媒体能力不支持 | +| IMAGE_RESULT_MEDIA_ADAPTER_INIT_FAILED | 媒体适配器初始化失败 | +| IMAGE_RESULT_MEDIA_WRITE_PARCEL_FAIL | 写入parcel失败 | +| IMAGE_RESULT_MEDIA_READ_PARCEL_FAIL | 读取parcel失败 | +| IMAGE_RESULT_MEDIA_NO_AVAIL_BUFFER | 无效数据 | +| IMAGE_RESULT_MEDIA_INVALID_PARAM | 媒体接口发现无效参数 | +| IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_EXIST | 媒体代码适配器不存在 | +| IMAGE_RESULT_MEDIA_CREATE_CODEC_ADAPTER_FAILED | 媒体创建代码适配器失败 | +| IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_INIT | 媒体代码适配器未初始化 | +| IMAGE_RESULT_MEDIA_ZCODEC_CREATE_FAILED | 媒体代码创建失败 | +| IMAGE_RESULT_MEDIA_ZCODEC_NOT_EXIST | 媒体代码不存在 | +| IMAGE_RESULT_MEDIA_JNI_CLASS_NOT_EXIST | 媒体JNI层类不存在 | +| IMAGE_RESULT_MEDIA_JNI_METHOD_NOT_EXIST | 媒体JNI层方法不存在 | +| IMAGE_RESULT_MEDIA_JNI_NEW_OBJ_FAILED | 媒体JNI层创建对象失败 | +| IMAGE_RESULT_MEDIA_JNI_COMMON_ERROR | 媒体JNI层异常 | +| IMAGE_RESULT_MEDIA_DISTRIBUTE_NOT_SUPPORT | 媒体不支持分布 | +| IMAGE_RESULT_MEDIA_SOURCE_NOT_SET | 媒体源未设置 | +| IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_INIT | 媒体rtsp适配器未初始化 | +| IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_EXIST | 媒体rtsp适配器不存在 | +| IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT | 媒体不支持rtsp surface | +| IMAGE_RESULT_MEDIA_RTSP_CAPTURE_NOT_INIT | 媒体rtsp capture初始化失败 | +| IMAGE_RESULT_MEDIA_RTSP_SOURCE_URL_INVALID | 媒体rtsp源路径无效 | +| IMAGE_RESULT_MEDIA_RTSP_VIDEO_TRACK_NOT_FOUND | 媒体rtsp未发现视频能力 | +| IMAGE_RESULT_MEDIA_RTSP_CAMERA_NUM_REACH_MAX | rtsp相机数量达到最大数量 | +| IMAGE_RESULT_MEDIA_SET_VOLUME | 媒体设置卷失败 | +| IMAGE_RESULT_MEDIA_NUMBER_OVERFLOW | 媒体操作次数溢出 | +| IMAGE_RESULT_MEDIA_DIS_PLAYER_UNSUPPORTED | 媒体分布式播放器不支持 | +| IMAGE_RESULT_MEDIA_DENCODE_ICC_FAILED | 图像解码ICC失败 | +| IMAGE_RESULT_MEDIA_ENCODE_ICC_FAILED | 图像编码CC失败 | +| IMAGE_RESULT_MEDIA_READ_PIXELMAP_FAILED | 读取像素位图失败 | +| IMAGE_RESULT_MEDIA_WRITE_PIXELMAP_FAILED | 写入像素位图失败 | +| IMAGE_RESULT_MEDIA_PIXELMAP_NOT_ALLOW_MODIFY | 像素位图不允许修改 | +| IMAGE_RESULT_MEDIA_CONFIG_FAILED | 配置失败 | +| IMAGE_RESULT_JNI_ENV_ABNORMAL | JNI环境异常 | +| IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED | surface申请内存失败 | +| IMAGE_RESULT_CREATE_SURFACE_FAILED | 创建surface失败 | +| IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED | 从surface获取参数失败 | +| IMAGE_RESULT_GET_SURFACE_FAILED | 获取sufrace失败 | +| IMAGE_RESULT_SURFACE_ACQUIRE_BUFFER_FAILED | 申请内存失败 | +| IMAGE_RESULT_SURFACE_REQUEST_BUFFER_FAILED | 申请内存失败 | +| IMAGE_RESULT_REGISTER_LISTENER_FAILED | 注册监听失败 | +| IMAGE_RESULT_REGISTER_BUFFER_FAILED | 注册内存失败 | +| IMAGE_RESULT_FREAD_FAILED | 读取文件失败 | +| IMAGE_RESULT_PEEK_FAILED | 检测文件失败 | +| IMAGE_RESULT_SEEK_FAILED | 查找文件失败 | +| IMAGE_RESULT_STREAM_SIZE_ERROR | 数据流损坏 | +| IMAGE_RESULT_FILE_FD_ERROR | 文件描述符损坏 | +| IMAGE_RESULT_FILE_DAMAGED | 文件损坏 | +| IMAGE_RESULT_CREATE_DECODER_FAILED | 创建解码失败 | +| IMAGE_RESULT_CREATE_ENCODER_FAILED | 创建编码失败 | +| IMAGE_RESULT_CHECK_FORMAT_ERROR | 检查格式失败 | +| IMAGE_RESULT_THIRDPART_SKIA_ERROR | skia解码失败 | +| IMAGE_RESULT_HW_DECODE_FAILED | 硬解码失败 | +| IMAGE_RESULT_ALLOCATER_TYPE_ERROR | 内存类型校验失败 | +| IMAGE_RESULT_ALPHA_TYPE_ERROR | 透明度类型失败 | +| IMAGE_RESULT_INDEX_INVALID | 参数无效 | +| IMAGE_RESULT_MEDIA_UNKNOWN | 媒体未知错误 | -Flip -**起始版本:** -10 +## 函数说明 -### OH_PixelMap_GetBytesNumberPerRow() +### OH_AccessPixels() - ``` -int32_t OH_PixelMap_GetBytesNumberPerRow (const NativePixelMap * native, int32_t * num ) +int32_t OHOS::Media::OH_AccessPixels (napi_env env, napi_value value, void ** addrPtr ) ``` -**描述:** -获取**PixelMap**对象每行字节数. -**参数:** +**描述:** + +获取**PixelMap**对象数据的内存地址,并锁定该内存。 + +函数执行成功后,**\*addrPtr**就是获取的待访问的内存地址。访问操作完成后,必须要使用**OH_UnAccessPixels**来释放锁,否则的话资源无法被释放。 待解锁后,内存地址就不可以再被访问和操作。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| num | **PixelMap**对象的每行字节数指针。| +| env | napi的环境指针。 | +| value | 应用层的 **PixelMap** 对象。 | +| addrPtr | 用于指向的内存地址的双指针对象。 | -**返回:** +**返回:** -操作成功则返回 **PixelMap** 对象每行字节数; 如果操作失败,则返回错误码。 +操作成功则返回 **OHOS_IMAGE_RESULT_SUCCESS**;如果操作失败,则返回错误码。 -**参见:** +**起始版本:** -GetBytesNumberPerRow +8 + +**废弃起始版本:** -**起始版本:** 10 -### OH_PixelMap_GetDensity() +**参见:** + +UnAccessPixels + + +### OH_GetImageInfo() - ``` -int32_t OH_PixelMap_GetDensity (const NativePixelMap * native, int32_t * density ) +int32_t OHOS::Media::OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) ``` -**描述:** -获取**PixelMap**对象像素密度. -**参数:** +**描述:** + +获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)结构中。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| density | 像素密度指针。| +| env | napi的环境指针。 | +| value | 应用层的 **PixelMap** 对象。 | +| info | 用于保存信息的指针对象。 更多细节, 参看 [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)。 | -**返回:** +**返回:** + +如果获取并保存信息成功,则返回**0**; 如果操作失败,则返回错误码。 -操作成功则返回像素密度; 如果操作失败,则返回错误码。 +**起始版本:** -**参见:** +8 -GetDensity +**废弃起始版本:** -**起始版本:** 10 +**参见:** -### OH_PixelMap_GetIsEditable() +[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) + + +### OH_Image_ClipRect() - ``` -int32_t OH_PixelMap_GetIsEditable (const NativePixelMap * native, int32_t * editable ) +int32_t OHOS::Media::OH_Image_ClipRect (const ImageNative * native, struct OhosImageRect * rect ) ``` -**描述:** -获取**PixelMap**对象是否可编辑的状态. -**参数:** +**描述:** + +获取native **ImageNative** 对象 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 信息。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| editable | **PixelMap** 对象是否可编辑的指针。| +| native | 表示指向 **ImageNative** native层对象的指针。 | +| rect | 表示作为转换结果的 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 对象指针。 | -**返回:** +**返回:** -操作成功则返回编辑类型的枚举值; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功返回 IMAGE_RESULT_SUCCESS ; -GetIsEditable +如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED; + +如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。 + +**起始版本:** -**起始版本:** 10 +**参见:** -### OH_PixelMap_InitNativePixelMap() +ImageNative, [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) + + +### OH_Image_Format() - ``` -NativePixelMap* OH_PixelMap_InitNativePixelMap (napi_env env, napi_value source ) +int32_t OHOS::Media::OH_Image_Format (const ImageNative * native, int32_t * format ) ``` -**描述:** -初始化**PixelMap**对象数据. -**参数:** +**描述:** + +获取native **ImageNative** 对象的图像格式。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| env | napi的环境指针。| -| source | **PixelMap** 数据设置项。| +| native | 表示 **ImageNative** native对象的指针。 | +| format | 表示作为转换结果的图像格式对象的指针。 | -**返回:** +**返回:** -操作成功则返回NativePixelMap的指针; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功返回 IMAGE_RESULT_SUCCESS ; -InitNativePixelMap +如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED; + +如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。 + +**起始版本:** -**起始版本:** 10 +**参见:** -### OH_PixelMap_IsSupportAlpha() +ImageNative + + +### OH_Image_GetComponent() - ``` -int32_t OH_PixelMap_IsSupportAlpha (const NativePixelMap * native, int32_t * alpha ) +int32_t OHOS::Media::OH_Image_GetComponent (const ImageNative * native, int32_t componentType, struct OhosImageComponent * componentNative ) ``` -**描述:** -获取**PixelMap**对象是否支持Alpha通道. -**参数:** +**描述:** + +从 native **ImageNative** 对象中获取 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| alpha | 是否支持Alpha的指针。| +| native | 表示 **ImageNative** native对象的指针。 | +| componentType | 表示所需组件的组件类型。 | +| componentNative | 表示转换结果的 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) 对象的指针。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功返回 IMAGE_RESULT_SUCCESS ; -IsSupportAlpha +如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED; + +如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。 + +**起始版本:** -**起始版本:** 10 +**参见:** +ImageNative, [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) -### OH_PixelMap_Rotate() - +### OH_Image_InitImageNative() + ``` -int32_t OH_PixelMap_Rotate (const NativePixelMap * native, float angle ) +ImageNative* OHOS::Media::OH_Image_InitImageNative (napi_env env, napi_value source ) ``` -**描述:** -设置**PixelMap**对象的旋转. -**参数:** +**描述:** + +从输入的JavaScript Native API **图像** 对象中解析 native **ImageNative** 对象。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| angle | 旋转角度。| +| env | 表示指向 JNI 环境的指针。 | +| source | 表示 JavaScript Native API **图像** 对象。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +如果操作成果返回 **ImageNative** 指针对象,如果操作失败返回空指针。 -**参见:** +**起始版本:** -Rotate +10 + +**参见:** + +ImageNative, OH_Image_Release + + +### OH_Image_Receiver_CreateImageReceiver() + +``` +int32_t OH_Image_Receiver_CreateImageReceiver (napi_env env, struct OhosImageReceiverInfo info, napi_value * res ) +``` + +**描述:** + +创建应用层 **ImageReceiver** 对象。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | napi的环境指针。 | +| info | **ImageReceiver** 数据设置项。 | +| res | 应用层的 **ImageReceiver** 对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果创建surface失败则返回 IMAGE_RESULT_CREATE_SURFACE_FAILED ; + +如果surface分配内存失败则返回 IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED ; + +如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ; + +如果媒体rtsp surface不支持则返回 IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。 + +**起始版本:** -**起始版本:** 10 +**参见:** -### OH_PixelMap_Scale() +[OhosImageReceiverInfo](_ohos_image_receiver_info.md) + + +### OH_Image_Receiver_GetCapacity() - ``` -int32_t OH_PixelMap_Scale (const NativePixelMap * native, float x, float y ) +int32_t OH_Image_Receiver_GetCapacity (const ImageReceiverNative * native, int32_t * capacity ) ``` -**描述:** -设置**PixelMap**对象的缩放. -**参数:** +**描述:** + +通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的容量。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| x | 缩放宽度。| -| y | 缩放高度。| +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| capacity | 作为结果的指向容量的指针。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; -Scale +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** -**起始版本:** 10 +**参见:** -### OH_PixelMap_SetAlphaAble() +[ImageReceiverNative](#imagereceivernative), [OhosImageSize](_ohos_image_size.md) + + +### OH_Image_Receiver_GetFormat() - ``` -int32_t OH_PixelMap_SetAlphaAble (const NativePixelMap * native, int32_t alpha ) +int32_t OH_Image_Receiver_GetFormat (const ImageReceiverNative * native, int32_t * format ) ``` -**描述:** -设置**PixelMap**对象的Alpha通道. -**参数:** +**描述:** + +通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的格式。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| alpha | Alpha通道。| +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| format | 作为结果的指向格式的指针。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; -SetAlphaAble +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** -**起始版本:** 10 +**参见:** -### OH_PixelMap_SetDensity() +[ImageReceiverNative](#imagereceivernative) + + +### OH_Image_Receiver_GetReceivingSurfaceId() - ``` -int32_t OH_PixelMap_SetDensity (const NativePixelMap * native, int32_t density ) +int32_t OH_Image_Receiver_GetReceivingSurfaceId (const ImageReceiverNative * native, char * id, size_t len ) ``` -**描述:** -设置**PixelMap**对象像素密度. -**参数:** +**描述:** + +通过[ImageReceiverNative](#imagereceivernative)获取receiver的id。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| density | 像素密度。| +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| id | 指向字符缓冲区的指针,用于获取字符串的id。 | +| len | **id**所对应的字符缓冲区的大小。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; -GetDensity +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。 + +**起始版本:** -**起始版本:** 10 +**参见:** + +[ImageReceiverNative](#imagereceivernative) -### OH_PixelMap_SetOpacity() - +### OH_Image_Receiver_GetSize() + ``` -int32_t OH_PixelMap_SetOpacity (const NativePixelMap * native, float opacity ) +int32_t OH_Image_Receiver_GetSize (const ImageReceiverNative * native, struct OhosImageSize * size ) ``` -**描述:** -设置**PixelMap**对象的透明度. -**参数:** +**描述:** + +通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的大小。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| opacity | 透明度。| +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| size | 作为结果的[OhosImageSize](_ohos_image_size.md)指针。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; -SetOpacity +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** -**起始版本:** 10 +**参见:** + +[ImageReceiverNative](#imagereceivernative), [OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback) -### OH_PixelMap_Translate() - +### OH_Image_Receiver_InitImageReceiverNative() + ``` -int32_t OH_PixelMap_Translate (const NativePixelMap * native, float x, float y ) +ImageReceiverNative* OH_Image_Receiver_InitImageReceiverNative (napi_env env, napi_value source ) ``` -**描述:** -设置**PixelMap**对象的偏移. -**参数:** +**描述:** + +通过应用层**ImageReceiver**对象初始化native层[ImageReceiverNative](#imagereceivernative)对象。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| native | NativePixelMap的指针。| -| x | 水平偏移量。| -| y | 垂直偏移量。| +| env | napi的环境指针。 | +| source | napi的 **ImageReceiver** 对象。 | -**返回:** +**返回:** -操作成功则返回**0**; 如果操作失败,则返回错误码。 +操作成功则返回 [ImageReceiverNative](#imagereceivernative) 指针;如果操作失败,则返回nullptr。 -**参见:** +**起始版本:** -Translate +10 + +**参见:** + +[ImageReceiverNative](#imagereceivernative), [OH_Image_Receiver_Release](#oh_image_receiver_release) + + +### OH_Image_Receiver_On() + +``` +int32_t OH_Image_Receiver_On (const ImageReceiverNative * native, OH_Image_Receiver_On_Callback callback ) +``` + +**描述:** + +注册一个[OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)回调事件。每当接收新图片,该回调事件就会响应。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| callback | [OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)事件的回调函数。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。 + +**起始版本:** -**起始版本:** 10 +**参见:** + +[ImageReceiverNative](#imagereceivernative) -### OH_UnAccessPixels() - +### OH_Image_Receiver_ReadLatestImage() + ``` -int32_t OH_UnAccessPixels (napi_env env, napi_value value ) +int32_t OH_Image_Receiver_ReadLatestImage (const ImageReceiverNative * native, napi_value * image ) ``` -**描述:** -释放**PixelMap**对象数据的内存锁, 用于匹配方法[OH_AccessPixels](#oh_accesspixels). -**参数:** +**描述:** + +通过[ImageReceiverNative](#imagereceivernative)获取最新的一张图片。 + +**参数:** | 名称 | 描述 | | -------- | -------- | -| env | napi的环境指针。| -| value | 应用层的 **PixelMap** 对象。| +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| image | 获取到的应用层的 **Image** 指针对象。 | -**返回:** +**返回:** -操作成功则返回 OHOS_IMAGE_RESULT_SUCCESS; 如果操作失败,则返回错误码。 +参考[IRNdkErrCode](#irndkerrcode)。 -**参见:** +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; -AccessPixels +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果创建surface失败则返回 IMAGE_RESULT_CREATE_SURFACE_FAILED ; + +如果surface分配内存失败则返回 IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED ; + +如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ; + +如果媒体rtsp surface不支持则返回 IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +[ImageReceiverNative](#imagereceivernative) + + +### OH_Image_Receiver_ReadNextImage() + +``` +int32_t OH_Image_Receiver_ReadNextImage (const ImageReceiverNative * native, napi_value * image ) +``` + +**描述:** + +通过[ImageReceiverNative](#imagereceivernative)获取下一张图片。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | +| image | 读取到的应用层的 **Image** 指针对象。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果创建surface失败则返回 IMAGE_RESULT_CREATE_SURFACE_FAILED ; + +如果surface分配内存失败则返回 IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED ; + +如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ; + +如果媒体rtsp surface不支持则返回 IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +[ImageReceiverNative](#imagereceivernative) + + +### OH_Image_Receiver_Release() + +``` +int32_t OH_Image_Receiver_Release (ImageReceiverNative * native) +``` + +**描述:** + +释放native层 [ImageReceiverNative](#imagereceivernative) 对象。注意: 此方法不能释放应用层**ImageReceiver**对象。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +[ImageReceiverNative](#imagereceivernative) + + +### OH_Image_Release() + +``` +int32_t OHOS::Media::OH_Image_Release (ImageNative * native) +``` + +**描述:** + +释放 **ImageNative** native对象。 Note: 这个方法无法释放 JavaScript Native API **Image** 对象, 而是释放被 **OH_Image_InitImageNative** 解析的 **ImageNative** native 对象。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表示 **ImageNative** native对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回 IMAGE_RESULT_SUCCESS ; + +如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。 + +**起始版本:** + +10 + +**参见:** + +ImageNative, OH_Image_InitImageNative + + +### OH_Image_Size() + +``` +int32_t OHOS::Media::OH_Image_Size (const ImageNative * native, struct OhosImageSize * size ) +``` + +**描述:** + +获取native **ImageNative** 对象的 [OhosImageSize](_ohos_image_size.md) 信息。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表示 **ImageNative** native对象的指针。 | +| size | 表示作为转换结果的 [OhosImageSize](_ohos_image_size.md) 对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回 IMAGE_RESULT_SUCCESS ; + +如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED; + +如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。 + +**起始版本:** + +10 + +**参见:** + +ImageNative, [OhosImageSize](_ohos_image_size.md) + + +### OH_ImageSource_Create() + +``` +int32_t OH_ImageSource_Create (napi_env env, struct OhosImageSource * src, struct OhosImageSourceOps * ops, napi_value * res ) +``` + +**描述:** + +通过给定的信息[OhosImageSource](_ohos_image_source.md) 和 [OhosImageSourceOps](_ohos_image_source_ops.md)结构体,获取JavaScript native层API** ImageSource**对象。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | 表明JNI环境的指针。 | +| src | 表明创建一个图像源的信息。查看[OhosImageSource](_ohos_image_source.md)获取更多细节。 | +| ops | 表明创建一个图像源的选项。查看[OhosImageSourceOps](_ohos_image_source_ops.md)。 | +| res | 表明JavaScript native层API**ImageSource**对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果图像源数据不完整,返回IMAGE_RESULT_SOURCE_DATA_INCOMPLETE; + +如果图像源数据错误,返回IMAGE_RESULT_SOURCE_DATA; + +如果图像获取数据错误,返回IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果图像数据太大,返回IMAGE_RESULT_TOO_LARGE; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果图像解码 EXIF 不支持,返回IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图像属性不存在,返回IMAGE_RESULT_PROPERTY_NOT_EXIST; + +如果文件损坏,返回IMAGE_RESULT_FILE_DAMAGED; + +如果文件 FD 错误,返回IMAGE_RESULT_FILE_FD_ERROR; + +如果数据流错误,返回IMAGE_RESULT_STREAM_SIZE_ERROR; + +如果查找文件失败,返回IMAGE_RESULT_SEEK_FAILED; + +如果速览文件失败,返回IMAGE_RESULT_PEEK_FAILED; + +如果读取文件失败,返回IMAGE_RESULT_FREAD_FAILED。 + +**起始版本:** + +10 + +**参见:** + +[OhosImageSource](_ohos_image_source.md), [OhosImageSourceOps](_ohos_image_source_ops.md) + + +### OH_ImageSource_CreateIncremental() + +``` +int32_t OH_ImageSource_CreateIncremental (napi_env env, struct OhosImageSource * source, struct OhosImageSourceOps * ops, napi_value * res ) +``` + +**描述:** + +通过给定的infomations[OhosImageSource](_ohos_image_source.md)和[OhosImageSourceOps](_ohos_image_source_ops.md)结构, 获取增量类型的JavaScript Native API ImageSource对象,图像数据应通过**OH_ImageSource_UpdateData**更新。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | 表明JNI环境的指针。 | +| src | 表明创建一个图像源的信息。这里只接收缓冲区类型。查看[OhosImageSource](_ohos_image_source.md)获取更多细节 | +| ops | 表明创建一个图像源的选项。查看[OhosImageSourceOps](_ohos_image_source_ops.md)。 | +| res | 表明JavaScript native层API**ImageSource**对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果图像源数据不完整,返回IMAGE_RESULT_SOURCE_DATA_INCOMPLETE; + +如果图像源数据错误,返回IMAGE_RESULT_SOURCE_DATA; + +如果图像获取数据错误,返回IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果图像数据太大,返回IMAGE_RESULT_TOO_LARGE; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果图像解码 EXIF 不支持,返回IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图像属性不存在,返回IMAGE_RESULT_PROPERTY_NOT_EXIST; + +如果文件损坏,返回IMAGE_RESULT_FILE_DAMAGED; + +如果文件 FD 错误,返回IMAGE_RESULT_FILE_FD_ERROR; + +如果数据流错误,返回IMAGE_RESULT_STREAM_SIZE_ERROR; + +如果查找文件失败,返回IMAGE_RESULT_SEEK_FAILED; + +如果速览文件失败,返回IMAGE_RESULT_PEEK_FAILED; + +如果读取文件失败,返回IMAGE_RESULT_FREAD_FAILED。 + +**起始版本:** + +10 + +**参见:** + +[OhosImageSource](_ohos_image_source.md), [OhosImageSourceOps](_ohos_image_source_ops.md), [OH_ImageSource_UpdateData](#oh_imagesource_updatedata) + + +### OH_ImageSource_CreatePixelMap() + +``` +int32_t OH_ImageSource_CreatePixelMap (const ImageSourceNative * native, struct OhosImageDecodingOps * ops, napi_value * res ) +``` + +**描述:** + +通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码JavaScript native层API**PixelMap**对象 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层[ImageSourceNative](#imagesourcenative)值的指针。 | +| ops | 表明为了解码图像源的选项,查看[OhosImageDecodingOps](_ohos_image_decoding_ops.md)。 | +| res | 表明JavaScript native层API**PixelMap**对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果创建编码器失败,返回 IMAGE_RESULT_CREATE_ENCODER_FAILED; + +如果检查格式不对,返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL。 + +如果共享内存错误,返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST; + +如果共享内存数据异常,返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL; + +如果图片解码异常,返回 IMAGE_RESULT_DECODE_ABNORMAL; + +如果图像错误,返回 IMAGE_RESULT_MALLOC_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片输入数据错误,返回 IMAGE_RESULT_INIT_ABNORMAL; + +如果裁剪错误,返回 IMAGE_RESULT_CROP; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果增加位图失败,返回 IMAGE_RESULT_ENCODE_FAILED; + +如果不支持图片硬解码,返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT; + +如果硬解码失败,返回 IMAGE_RESULT_HW_DECODE_FAILED; + +如果ipc失败,返回 IMAGE_RESULT_ERR_IPC; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果透明度类型错误,返回 IMAGE_RESULT_ALPHA_TYPE_ERROR; + +如果内存分配类型错误,返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageDecodingOps](_ohos_image_decoding_ops.md) + + +### OH_ImageSource_CreatePixelMapList() + +``` +int32_t OH_ImageSource_CreatePixelMapList (const ImageSourceNative * native, struct OhosImageDecodingOps * ops, napi_value * res ) +``` + +**描述:** + +通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码所有的JavaScript native层API**PixelMap**对象列表 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | +| ops | 表明为了解码图像源的选项,查看[OhosImageDecodingOps](_ohos_image_decoding_ops.md)。 | +| res | 表明JavaScript native层API**PixelMap** 列表对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果创建编码器失败,返回 IMAGE_RESULT_CREATE_ENCODER_FAILED; + +如果检查格式不对,返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果共享内存错误,返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST; + +如果共享内存数据异常,返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL; + +如果图片解码异常,返回 IMAGE_RESULT_DECODE_ABNORMAL; + +如果图像错误,返回 IMAGE_RESULT_MALLOC_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片输入数据错误,返回 IMAGE_RESULT_INIT_ABNORMAL; + +如果裁剪错误,返回 IMAGE_RESULT_CROP; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果增加位图失败,返回 IMAGE_RESULT_ENCODE_FAILED; + +如果不支持图片硬解码,返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT; + +如果硬解码失败,返回 IMAGE_RESULT_HW_DECODE_FAILED; + +如果ipc失败,返回 IMAGE_RESULT_ERR_IPC; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果透明度类型错误,返回 IMAGE_RESULT_ALPHA_TYPE_ERROR; + +如果内存分配类型错误,返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR; + +如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageDecodingOps](_ohos_image_decoding_ops.md) + + +### OH_ImageSource_GetDelayTime() + +``` +int32_t OH_ImageSource_GetDelayTime (const ImageSourceNative * native, struct OhosImageSourceDelayTimeList * res ) +``` + +**描述:** + +从一些**ImageSource**(如GIF图像源)获取延迟时间列表。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | +| res | 表明延迟时间列表 [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) 的指针。 当输入的res中**delayTimeList**是空指针并且**size**是0时,将通过res的**size**中返回延迟时间列表大小 为了获取延迟时间,需要比返回的**delayTimeList**大小值大的足够空间 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) + + +### OH_ImageSource_GetFrameCount() + +``` +int32_t OH_ImageSource_GetFrameCount (const ImageSourceNative * native, uint32_t * res ) +``` + +**描述:** + +从**ImageSource**中获取帧计数。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | +| res | 表明帧计数的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative) + + +### OH_ImageSource_GetImageInfo() + +``` +int32_t OH_ImageSource_GetImageInfo (const ImageSourceNative * native, int32_t index, struct OhosImageSourceInfo * info ) +``` + +**描述:** + +通过索引从**ImageSource**获取图像源信息。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | +| index | 表明帧计数的指针。 | +| info | 表明图像源信息[OhosImageSourceInfo](_ohos_image_source_info.md)的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageSourceInfo](_ohos_image_source_info.md) + + +### OH_ImageSource_GetImageProperty() + +``` +int32_t OH_ImageSource_GetImageProperty (const ImageSourceNative * native, struct OhosImageSourceProperty * key, struct OhosImageSourceProperty * value ) +``` + +**描述:** + +通过关键字从**ImageSource**中获取图像源属性。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | +| key | 表明属性关键字[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 | +| value | 表明作为结果的属性值[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 当输入的value中**value**是空指针并且**size**是0时,将通过value中的**size**返回属性值的大小。 为了获取属性值,需要比**value**中的结果大小大的足够的空间。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageSourceProperty](_ohos_image_source_property.md) + + +### OH_ImageSource_GetSupportedFormats() + +``` +int32_t OH_ImageSource_GetSupportedFormats (struct OhosImageSourceSupportedFormatList * res) +``` + +**描述:** + +获取所有支持的解码格式元标记。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| res | 表明指向**[OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md)**结构的列表指针。 当**supportedFormatList**为nullptr并且**size**以res为0作为输入时,它将以res** size**返回支持的格式大小。
为了获得所有的格式标记,它需要比**supportedFormatList**中的结果大小大的足够空间, 还需要为[OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md)项目中的每个格式提供足够的空间。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果检查格式不对,返回MAGE_RESULT_CHECK_FORMAT_ERROR。 + +**起始版本:** + +10 + +**参见:** + +[OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md), [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md) + + +### OH_ImageSource_InitNative() + +``` +ImageSourceNative* OH_ImageSource_InitNative (napi_env env, napi_value source ) +``` + +**描述:** + +从输入JavaScript native层API **ImageSource** 对象中,转换成[ImageSourceNative](#imagesourcenative)值。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | 表明JNI环境的指针。 | +| source | 表明JavaScript native层API** ImageSource**对象的指针。 | + +**返回:** + +如果操作成功返回[ImageSourceNative](#imagesourcenative)指针;如果操作失败,返回空指针。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OH_ImageSource_Release](#oh_imagesource_release) + + +### OH_ImageSource_ModifyImageProperty() + +``` +int32_t OH_ImageSource_ModifyImageProperty (const ImageSourceNative * native, struct OhosImageSourceProperty * key, struct OhosImageSourceProperty * value ) +``` + +**描述:** + +通过关键字为**ImageSource**修改图像源属性。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针 | +| key | 表明属性关键字[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 | +| value | 为了修改表明属性值[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT; + +如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageSourceProperty](_ohos_image_source_property.md) + + +### OH_ImageSource_Release() + +``` +int32_t OH_ImageSource_Release (ImageSourceNative * native) +``` + +**描述:** + +释放native层图像源 **ImageSourceNative**。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OH_ImageSource_Create](#oh_imagesource_create), [OH_ImageSource_CreateIncremental](#oh_imagesource_createincremental) + + +### OH_ImageSource_UpdateData() + +``` +int32_t OH_ImageSource_UpdateData (const ImageSourceNative * native, struct OhosImageSourceUpdateData * data ) +``` + +**描述:** + +为了增量类型的**ImageSource**更新源数据。 + +\@Syscap SystemCapability.Multimedia.Image + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 | +| data | 表明更新数据信息[OhosImageSourceUpdateData](_ohos_image_source_update_data.md)的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS; + +如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER; + +如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL; + +如果参数无效,IMAGE_RESULT_INVALID_PARAMETER; + +如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL; + +如果解码失败,返回IMAGE_RESULT_DECODE_FAILED; + +如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL; + +如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED; + +如果创建编码器失败,返回 IMAGE_RESULT_CREATE_ENCODER_FAILED; + +如果检查格式不对,返回IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR; + +如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL; + +如果共享内存错误,返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST; + +如果共享内存数据异常,返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL; + +如果图片解码异常,返回IMAGE_RESULT_DECODE_ABNORMAL; + +如果图像错误,返回 IMAGE_RESULT_MALLOC_ABNORMAL; + +如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT; + +如果图片输入数据错误,返回 IMAGE_RESULT_INIT_ABNORMAL; + +如果裁剪错误,返回 IMAGE_RESULT_CROP; + +如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT; + +如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED; + +如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED; + +如果增加位图失败,返回 IMAGE_RESULT_ENCODE_FAILED; + +如果不支持图片硬解码,返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT; + +如果硬解码失败,返回 IMAGE_RESULT_HW_DECODE_FAILED; + +如果ipc失败,返回 IMAGE_RESULT_ERR_IPC; + +如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID; + +如果透明度类型错误,返回 IMAGE_RESULT_ALPHA_TYPE_ERROR; + +如果内存分配类型错误,返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR。 + +**起始版本:** + +10 + +**参见:** + +[ImageSourceNative](#imagesourcenative), [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) + + +### OH_PixelMap_AccessPixels() + +``` +int32_t OH_PixelMap_AccessPixels (const NativePixelMap * native, void ** addr ) +``` + +**描述:** + +获取native **PixelMap** 对象数据的内存地址,并锁定该内存。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| addr | 用于指向的内存地址的双指针对象。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +AccessPixels + + +### OH_PixelMap_CreateAlphaPixelMap() + +``` +int32_t OH_PixelMap_CreateAlphaPixelMap (napi_env env, napi_value source, napi_value * alpha ) +``` + +**描述:** + +根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | napi的环境指针。 | +| source | **PixelMap**数据设置项。 | +| alpha | alpha通道的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果图像头解码失败则返回 IMAGE_RESULT_DECODE_HEAD_ABNORMAL ; + +如果创建解码器失败则返回 IMAGE_RESULT_CREATE_DECODER_FAILED ; + +如果创建编码器失败则返回 IMAGE_RESULT_CREATE_ENCODER_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像解码失败则返回 IMAGE_RESULT_DECODE_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果图像初始化失败则返回 IMAGE_RESULT_INIT_ABNORMAL ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果图像添加像素位图失败则返回 IMAGE_RESULT_ENCODE_FAILED ; + +如果图像不支持硬件解码则返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT ; + +如果硬件解码失败则返回 IMAGE_RESULT_HW_DECODE_FAILED ; + +如果ipc失败则返回 IMAGE_RESULT_INDEX_INVALID ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +CreateAlphaPixelMap + + +### OH_PixelMap_CreatePixelMap() + +``` +int32_t OH_PixelMap_CreatePixelMap (napi_env env, OhosPixelMapCreateOps info, void * buf, size_t len, napi_value * res ) +``` + +**描述:** + +Creates a **PixelMap** object. + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | napi的环境指针。 | +| info | pixel map 数据设置项。 | +| buf | 图片的buffer数据。 | +| len | 图片大小信息。 | +| res | 应用层的 **PixelMap** 对象的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果图像头解码失败则返回 IMAGE_RESULT_DECODE_HEAD_ABNORMAL ; + +如果创建解码器失败则返回 IMAGE_RESULT_CREATE_DECODER_FAILED ; + +如果创建编码器失败则返回 IMAGE_RESULT_CREATE_ENCODER_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像解码失败则返回 IMAGE_RESULT_DECODE_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果图像初始化失败则返回 IMAGE_RESULT_INIT_ABNORMAL ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果图像添加像素位图失败则返回 IMAGE_RESULT_ENCODE_FAILED ; + +如果图像不支持硬件解码则返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT ; + +如果硬件解码失败则返回 IMAGE_RESULT_HW_DECODE_FAILED ; + +如果ipc失败则返回 IMAGE_RESULT_INDEX_INVALID ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +CreatePixelMap + + +### OH_PixelMap_Crop() + +``` +int32_t OH_PixelMap_Crop (const NativePixelMap * native, int32_t x, int32_t y, int32_t width, int32_t height ) +``` + +**描述:** + +设置**PixelMap**对象的裁剪。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| x | 目标图片左上角的x坐标。 | +| y | 目标图片左上角的y坐标。 | +| width | 裁剪区域的宽度。 | +| height | 裁剪区域的高度。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +Crop + + +### OH_PixelMap_Flip() + +``` +int32_t OH_PixelMap_Flip (const NativePixelMap * native, int32_t x, int32_t y ) +``` + +**描述:** + +设置**PixelMap**对象的翻转。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| x | 根据水平方向x轴进行图片翻转。 | +| y | 根据垂直方向y轴进行图片翻转。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +Flip + + +### OH_PixelMap_GetBytesNumberPerRow() + +``` +int32_t OH_PixelMap_GetBytesNumberPerRow (const NativePixelMap * native, int32_t * num ) +``` + +**描述:** + +获取**PixelMap**对象每行字节数。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| num | **PixelMap**对象的每行字节数指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +GetBytesNumberPerRow + + +### OH_PixelMap_GetDensity() + +``` +int32_t OH_PixelMap_GetDensity (const NativePixelMap * native, int32_t * density ) +``` + +**描述:** + +获取**PixelMap**对象像素密度。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| density | 像素密度指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +GetDensity + + +### OH_PixelMap_GetImageInfo() + +``` +int32_t OH_PixelMap_GetImageInfo (const NativePixelMap * native, OhosPixelMapInfos * info ) +``` + +**描述:** + +获取**PixelMap**对象图像信息。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| info | 图像信息指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +[OhosPixelMapInfos](_ohos_pixel_map_infos.md) + + +### OH_PixelMap_GetIsEditable() + +``` +int32_t OH_PixelMap_GetIsEditable (const NativePixelMap * native, int32_t * editable ) +``` + +**描述:** + +获取**PixelMap**对象是否可编辑的状态。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| editable | **PixelMap** 对象是否可编辑的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +GetIsEditable + + +### OH_PixelMap_InitNativePixelMap() + +``` +NativePixelMap* OH_PixelMap_InitNativePixelMap (napi_env env, napi_value source ) +``` + +**描述:** + +初始化**PixelMap**对象数据。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | napi的环境指针。 | +| source | **PixelMap** 数据设置项。 | + +**返回:** + +操作成功则返回NativePixelMap的指针;如果操作失败,则返回错误码。 + +**起始版本:** + +10 + +**参见:** + +InitNativePixelMap + + +### OH_PixelMap_IsSupportAlpha() + +``` +int32_t OH_PixelMap_IsSupportAlpha (const NativePixelMap * native, int32_t * alpha ) +``` + +**描述:** + +获取**PixelMap**对象是否支持Alpha通道。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| alpha | 是否支持Alpha的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +IsSupportAlpha + + +### OH_PixelMap_Rotate() + +``` +int32_t OH_PixelMap_Rotate (const NativePixelMap * native, float angle ) +``` + +**描述:** + +设置**PixelMap**对象的旋转。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| angle | 旋转角度。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +Rotate + + +### OH_PixelMap_Scale() + +``` +int32_t OH_PixelMap_Scale (const NativePixelMap * native, float x, float y ) +``` + +**描述:** + +设置**PixelMap**对象的缩放。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| x | 缩放宽度。 | +| y | 缩放高度。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果图像初始化失败则返回 IMAGE_RESULT_INIT_ABNORMAL ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +Scale + + +### OH_PixelMap_SetAlphaAble() + +``` +int32_t OH_PixelMap_SetAlphaAble (const NativePixelMap * native, int32_t alpha ) +``` + +**描述:** + +设置**PixelMap**对象的Alpha通道。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| alpha | Alpha通道。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +SetAlphaAble + + +### OH_PixelMap_SetDensity() + + +``` +int32_t OH_PixelMap_SetDensity (const NativePixelMap * native, int32_t density ) +``` + +**描述:** + +设置**PixelMap**对象像素密度。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| density | 像素密度。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +GetDensity + + +### OH_PixelMap_SetOpacity() + +``` +int32_t OH_PixelMap_SetOpacity (const NativePixelMap * native, float opacity ) +``` + +**描述:** + +设置**PixelMap**对象的透明度。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| opacity | 透明度。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。 + +**起始版本:** + +10 + +**参见:** + +SetOpacity + + +### OH_PixelMap_Translate() + +``` +int32_t OH_PixelMap_Translate (const NativePixelMap * native, float x, float y ) +``` + +**描述:** + +设置**PixelMap**对象的偏移。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | +| x | 水平偏移量。 | +| y | 垂直偏移量。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +Translate + + +### OH_PixelMap_UnAccessPixels() + +``` +int32_t OH_PixelMap_UnAccessPixels (const NativePixelMap * native) +``` + +**描述:** + +释放native **PixelMap**对象数据的内存锁,用于匹配方法[OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels)。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| native | NativePixelMap的指针。 | + +**返回:** + +参考[IRNdkErrCode](#irndkerrcode)。 + +如果操作成功则返回 IMAGE_RESULT_SUCCESS ; + +如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ; + +如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ; + +如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ; + +如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ; + +如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ; + +如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ; + +如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ; + +如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ; + +如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ; + +如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ; + +如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ; + +如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果裁剪失败失败则返回 IMAGE_RESULT_CROP ; + +如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ; + +如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ; + +如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ; + +如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ; + +如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ; + +如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。 + +**起始版本:** + +10 + +**参见:** + +UnAccessPixels + + +### OH_UnAccessPixels() + +``` +int32_t OHOS::Media::OH_UnAccessPixels (napi_env env, napi_value value ) +``` + +**描述:** + +释放**PixelMap**对象数据的内存锁, 用于匹配方法**OH_AccessPixels**。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| env | napi的环境指针。 | +| value | 应用层的 **PixelMap** 对象。 | + +**返回:** + +操作成功则返回 **OHOS_IMAGE_RESULT_SUCCESS**;如果操作失败,则返回错误码。 + +**起始版本:** + +8 + +**废弃起始版本:** + +10 + +**参见:** + +AccessPixels + + +## 变量说明 + + +### alphaType + +``` +int32_t OhosImageSourceInfo::alphaType +``` + +**描述:** + +图像源透明度类型 + +**起始版本:** + +10 + + +### buffer [1/2] + +``` +uint8_t* OhosImageSource::buffer = nullptr +``` + +**描述:** + +图像源缓冲区资源,解手格式化包缓冲区或者base64缓冲区 + +**起始版本:** + +10 + + +### buffer [2/2] + +``` +uint8_t* OhosImageSourceUpdateData::buffer = nullptr +``` + +**描述:** + +图像源更新数据缓冲区 + +**起始版本:** + +10 + + +### bufferSize [1/2] + +``` +size_t OhosImageSource::bufferSize = 0 +``` + +**描述:** + +图像源缓冲区资源大小 + +**起始版本:** + +10 + + +### bufferSize [2/2] + +``` +size_t OhosImageSourceUpdateData::bufferSize = 0 +``` + +**描述:** + +图像源更新数据缓冲区大小 + +**起始版本:** + +10 + + +### colorSpace + +``` +int32_t OhosImageSourceInfo::colorSpace +``` + +**描述:** + +图像源色彩空间 + +**起始版本:** + +10 + + +### delayTimeList + +``` +int32_t* OhosImageSourceDelayTimeList::delayTimeList +``` + +**描述:** + +图像源延迟时间列表头地址 + +**起始版本:** + +10 + + +### density [1/2] + +``` +int32_t OhosImageSourceOps::density +``` + +**描述:** + +图像源像素密度 + +**起始版本:** + +10 + + +### density [2/2] + +``` +int32_t OhosImageSourceInfo::density +``` + +**描述:** + +图像源密度, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置 + +**起始版本:** + +10 + + +### editable + +``` +int8_t OhosImageDecodingOps::editable +``` + +**描述:** + +定义输出的像素位图是否可编辑 + +**起始版本:** + +10 + + +### fd + +``` +int32_t OhosImageSource::fd = -1 +``` + +**描述:** + +图像源文件资源描述符 + +**起始版本:** + +10 + + +### fitDensity + +``` +int32_t OhosImageDecodingOps::fitDensity +``` + +**描述:** + +定义解码目标的像素密度 + +**起始版本:** + +10 + + +### format + +``` +char* OhosImageSourceSupportedFormat::format = nullptr +``` + +**描述:** + +图像源支持的格式字符串头地址 + +**起始版本:** + +10 + + +### height + +``` +int32_t OhosImageRegion::height +``` + +**描述:** + +高度范围,用pixels表示 + +**起始版本:** + +10 + + +### index + +``` +uint32_t OhosImageDecodingOps::index +``` + +**描述:** + +定义图像源解码指数 + +**起始版本:** + +10 + + +### isCompleted + +``` +int8_t OhosImageSourceUpdateData::isCompleted = 0 +``` + +**描述:** + +图像源更新数据在此节中完成 + +**起始版本:** + +10 + + +### offset + +``` +uint32_t OhosImageSourceUpdateData::offset = 0 +``` + +**描述:** + +图像源更新数据缓冲区的开端 + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE + +``` +const char* OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE = "BitsPerSample" +``` + +**描述:** + +定义每个样本比特的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL + +``` +const char* OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel" +``` + +**描述:** + +定义每个像素的压缩比特的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL + +``` +const char* OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL = "DateTimeOriginal" +``` + +**描述:** + +定义初始日期时间的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_EXPOSURE_TIME + +``` +const char* OHOS_IMAGE_PROPERTY_EXPOSURE_TIME = "ExposureTime" +``` + +**描述:** + +定义曝光时间的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_F_NUMBER + +``` +const char* OHOS_IMAGE_PROPERTY_F_NUMBER = "FNumber" +``` + +**描述:** + +定义FNumber的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_GPS_LATITUDE + +``` +const char* OHOS_IMAGE_PROPERTY_GPS_LATITUDE = "GPSLatitude" +``` + +**描述:** + +定义GPS纬度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF + +``` +const char* OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF = "GPSLatitudeRef" +``` + +**描述:** + +定义GPS纬度参考的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_GPS_LONGITUDE + +``` +const char* OHOS_IMAGE_PROPERTY_GPS_LONGITUDE = "GPSLongitude" +``` + +**描述:** + +定义GPS经度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF + +``` +const char* OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF = "GPSLongitudeRef" +``` + +**描述:** + +定义GPS经度参考的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_IMAGE_LENGTH + +``` +const char* OHOS_IMAGE_PROPERTY_IMAGE_LENGTH = "ImageLength" +``` + +**描述:** + +定义图像长度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_IMAGE_WIDTH + +``` +const char* OHOS_IMAGE_PROPERTY_IMAGE_WIDTH = "ImageWidth" +``` + +**描述:** + +定义图像宽度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS + +``` +const char* OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS = "ISOSpeedRatings" +``` + +**描述:** + +定义ISO速度等级的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_ORIENTATION + +``` +const char* OHOS_IMAGE_PROPERTY_ORIENTATION = "Orientation" +``` + +**描述:** + +定义方向的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### OHOS_IMAGE_PROPERTY_SCENE_TYPE + +``` +const char* OHOS_IMAGE_PROPERTY_SCENE_TYPE = "SceneType" +``` + +**描述:** + +定义场景类型的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)和[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + + +### pixelFormat [1/3] + +``` +int32_t OhosImageSourceOps::pixelFormat +``` + +**描述:** + +图像源像素格式,通常用于描述YUV缓冲区 + +**起始版本:** + +10 + + +### pixelFormat [2/3] + +``` +int32_t OhosImageDecodingOps::pixelFormat +``` + +**描述:** + +定义输出的像素格式 + +**起始版本:** + +10 + + +### pixelFormat [3/3] + +``` +int32_t OhosImageSourceInfo::pixelFormat +``` + +**描述:** + +图像源像素格式, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置 + +**起始版本:** + +10 + + +### region + +``` +struct OhosImageRegion OhosImageDecodingOps::region +``` + +**描述:** + +定义图像源解码的像素范围 + +**起始版本:** + +10 + + +### rotate + +``` +uint32_t OhosImageDecodingOps::rotate +``` + +**描述:** + +定义解码旋转选项 + +**起始版本:** + +10 + + +### sampleSize + +``` +uint32_t OhosImageDecodingOps::sampleSize +``` + +**描述:** + +定义解码样本大小选项 + +**起始版本:** + +10 + + +### size [1/7] + +``` +struct OhosImageSize OhosImageSourceOps::size +``` + +**描述:** + +图像源像素宽高的大小 + +**起始版本:** + +10 + + +### size [2/7] + +``` +struct OhosImageSize OhosImageDecodingOps::size +``` + +**描述:** + +定义解码目标像素宽高的大小 + +**起始版本:** + +10 + + +### size [3/7] + +``` +struct OhosImageSize OhosImageSourceInfo::size +``` + +**描述:** + +图像源像素宽高的大小 + +**起始版本:** + +10 + + +### size [4/7] + +``` +size_t OhosImageSourceDelayTimeList::size = 0 +``` + +**描述:** + +图像源延迟时间列表大小 + +**起始版本:** + +10 + + +### size [5/7] + +``` +size_t OhosImageSourceSupportedFormat::size = 0 +``` + +**描述:** + +图像源支持的格式字符串大小 + +**起始版本:** + +10 + + +### size [6/7] + +``` +size_t OhosImageSourceSupportedFormatList::size = 0 +``` + +**描述:** + +图像源支持的格式字符串列表大小 + +**起始版本:** + +10 + + +### size [7/7] + +``` +size_t OhosImageSourceProperty::size = 0 +``` + +**描述:** + +定义图像源属性键值字符串大小 + +**起始版本:** + +10 + + +### supportedFormatList + +``` +struct OhosImageSourceSupportedFormat** OhosImageSourceSupportedFormatList::supportedFormatList = nullptr +``` + +**描述:** + +图像源支持的格式字符串列表头地址 + +**起始版本:** + +10 + + +### updateLength + +``` +uint32_t OhosImageSourceUpdateData::updateLength = 0 +``` + +**描述:** + +图像源更新数据缓冲区的更新数据长度 + +**起始版本:** + +10 + + +### uri + +``` +char* OhosImageSource::uri = nullptr +``` + +**描述:** + +图像源资源标识符,接受文件资源或者base64资源 + +**起始版本:** + +10 + + +### uriSize + +``` +size_t OhosImageSource::uriSize = 0 +``` + +**描述:** + +图像源资源长度 + +**起始版本:** + +10 + + +### value + +``` +char* OhosImageSourceProperty::value = nullptr +``` + +**描述:** + +定义图像源属性键值字符串头地址 + +**起始版本:** + +10 + + +### width + +``` +int32_t OhosImageRegion::width +``` + +**描述:** + +宽度范围,用pixels表示 + +**起始版本:** + +10 + + +### x + +``` +int32_t OhosImageRegion::x +``` + +**描述:** + +起始x坐标,用pixels表示 + +**起始版本:** + +10 + + +### y + +``` +int32_t OhosImageRegion::y +``` + +**描述:** + +起始y坐标,用pixels表示 + +**起始版本:** + +10 -**起始版本:** -8 diff --git a/zh-cn/application-dev/reference/native-apis/image__mdk_8h.md b/zh-cn/application-dev/reference/native-apis/image__mdk_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..6dd7870d88dc81067c850525e9ce323b9cf0feb0 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/image__mdk_8h.md @@ -0,0 +1,52 @@ +# image_mdk.h + + +## 概述 + +声明访问图像剪辑矩形、大小、格式和组件数据的函数。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [OHOS::Media::OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) | 定义图像矩形信息。 | +| [OHOS::Media::OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) | 定义图像组成信息。 | + + +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [OHOS::Media::ImageNative](image.md#imagenative) | 为图像接口定义native层图像对象。 | + + +### 枚举 + +| 名称 | 描述 | +| -------- | -------- | +| { [OHOS::Media::OHOS_IMAGE_FORMAT_YCBCR_422_SP](image.md) = 1000,
[OHOS::Media::OHOS_IMAGE_FORMAT_JPEG](image.md) = 2000, } | 图像格式枚举值。 | +| { [OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_Y](image.md) = 1,
[OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_U](image.md) = 2,
[OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_V](image.md) = 3,
[OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_JPEG](image.md) = 4, } | 图像组成类型枚举值。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [OHOS::Media::OH_Image_InitImageNative](image.md#oh_image_initimagenative) (napi_env env, napi_value source) | 从输入的JavaScript Native API **图像** 对象中解析 native **ImageNative** 对象。 | +| [OHOS::Media::OH_Image_ClipRect](image.md#oh_image_cliprect) (const [ImageNative](image.md#imagenative) \*native, struct [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) \*rect) | 获取native **ImageNative** 对象 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 信息。 | +| [OHOS::Media::OH_Image_Size](image.md#oh_image_size) (const [ImageNative](image.md#imagenative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 获取native **ImageNative** 对象的 [OhosImageSize](_ohos_image_size.md) 信息。 | +| [OHOS::Media::OH_Image_Format](image.md#oh_image_format) (const [ImageNative](image.md#imagenative) \*native, int32_t \*format) | 获取native **ImageNative** 对象的图像格式。 | +| [OHOS::Media::OH_Image_GetComponent](image.md#oh_image_getcomponent) (const [ImageNative](image.md#imagenative) \*native, int32_t componentType, struct [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) \*componentNative) | 从 native **ImageNative** 对象中获取 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)。 | +| [OHOS::Media::OH_Image_Release](image.md#oh_image_release) ([ImageNative](image.md#imagenative) \*native) | 释放 **ImageNative** native对象。 | diff --git a/zh-cn/application-dev/reference/native-apis/image__mdk__common_8h.md b/zh-cn/application-dev/reference/native-apis/image__mdk__common_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..32c1b789514c7ae6775edf82cd80216398676a07 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/image__mdk__common_8h.md @@ -0,0 +1,36 @@ +# image_mdk_common.h + + +## 概述 + +声明图像常用的枚举值和结构体。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [OhosImageSize](_ohos_image_size.md) | 定义图像大小。 | + +### 宏定义 + +| 名称 | 描述 | +| -------- | -------- | +| **IMAGE_RESULT_BASE** 62980096 | 接口返回值的基础值 | + +### 枚举 + +| 名称 | 描述 | +| -------- | -------- | +| [IRNdkErrCode](image.md#irndkerrcode) {
IMAGE_RESULT_SUCCESS = 0,
IMAGE_RESULT_BAD_PARAMETER = -1,
IMAGE_RESULT_IMAGE_RESULT_BASE = IMAGE_RESULT_BASE,
IMAGE_RESULT_ERR_IPC = IMAGE_RESULT_BASE + 1,
IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST = IMAGE_RESULT_BASE + 2,
IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL = IMAGE_RESULT_BASE + 3,
IMAGE_RESULT_DECODE_ABNORMAL = IMAGE_RESULT_BASE + 4,
IMAGE_RESULT_DATA_ABNORMAL = IMAGE_RESULT_BASE + 5,
IMAGE_RESULT_MALLOC_ABNORMAL = IMAGE_RESULT_BASE + 6,
IMAGE_RESULT_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 7,
IMAGE_RESULT_INIT_ABNORMAL = IMAGE_RESULT_BASE + 8,
IMAGE_RESULT_GET_DATA_ABNORMAL = IMAGE_RESULT_BASE + 9,
IMAGE_RESULT_TOO_LARGE = IMAGE_RESULT_BASE + 10,
IMAGE_RESULT_TRANSFORM = IMAGE_RESULT_BASE + 11,
IMAGE_RESULT_COLOR_CONVERT = IMAGE_RESULT_BASE + 12,
IMAGE_RESULT_CROP = IMAGE_RESULT_BASE + 13,
IMAGE_RESULT_SOURCE_DATA = IMAGE_RESULT_BASE + 14,
IMAGE_RESULT_SOURCE_DATA_INCOMPLETE = IMAGE_RESULT_BASE + 15,
IMAGE_RESULT_MISMATCHED_FORMAT = IMAGE_RESULT_BASE + 16,
IMAGE_RESULT_UNKNOWN_FORMAT = IMAGE_RESULT_BASE + 17,
IMAGE_RESULT_SOURCE_UNRESOLVED = IMAGE_RESULT_BASE + 18,
IMAGE_RESULT_INVALID_PARAMETER = IMAGE_RESULT_BASE + 19,
IMAGE_RESULT_DECODE_FAILED = IMAGE_RESULT_BASE + 20,
IMAGE_RESULT_PLUGIN_REGISTER_FAILED = IMAGE_RESULT_BASE + 21,
IMAGE_RESULT_PLUGIN_CREATE_FAILED = IMAGE_RESULT_BASE + 22,
IMAGE_RESULT_ENCODE_FAILED = IMAGE_RESULT_BASE + 23,
IMAGE_RESULT_ADD_PIXEL_MAP_FAILED = IMAGE_RESULT_BASE + 24,
IMAGE_RESULT_HW_DECODE_UNSUPPORT = IMAGE_RESULT_BASE + 25,
IMAGE_RESULT_DECODE_HEAD_ABNORMAL = IMAGE_RESULT_BASE + 26,
IMAGE_RESULT_DECODE_EXIF_UNSUPPORT = IMAGE_RESULT_BASE + 27,
IMAGE_RESULT_PROPERTY_NOT_EXIST = IMAGE_RESULT_BASE + 28,
IMAGE_RESULT_MEDIA_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 30,
IMAGE_RESULT_MEDIA_TOO_LARGE = IMAGE_RESULT_BASE + 31,
IMAGE_RESULT_MEDIA_MALLOC_FAILED = IMAGE_RESULT_BASE + 32,
IMAGE_RESULT_MEDIA_END_OF_STREAM = IMAGE_RESULT_BASE + 33,
IMAGE_RESULT_MEDIA_IO_ABNORMAL = IMAGE_RESULT_BASE + 34,
IMAGE_RESULT_MEDIA_MALFORMED = IMAGE_RESULT_BASE + 35,
IMAGE_RESULT_MEDIA_BUFFER_TOO_SMALL = IMAGE_RESULT_BASE + 36,
IMAGE_RESULT_MEDIA_OUT_OF_RANGE = IMAGE_RESULT_BASE + 37,
IMAGE_RESULT_MEDIA_STATUS_ABNORMAL = IMAGE_RESULT_BASE + 38,
IMAGE_RESULT_MEDIA_VALUE_INVALID = IMAGE_RESULT_BASE + 39,
IMAGE_RESULT_MEDIA_NULL_POINTER = IMAGE_RESULT_BASE + 40,
IMAGE_RESULT_MEDIA_INVALID_OPERATION = IMAGE_RESULT_BASE + 41,
IMAGE_RESULT_MEDIA_ERR_PLAYER_NOT_INIT = IMAGE_RESULT_BASE + 42,
IMAGE_RESULT_MEDIA_EARLY_PREPARE = IMAGE_RESULT_BASE + 43,
IMAGE_RESULT_MEDIA_SEEK_ERR = IMAGE_RESULT_BASE + 44,
IMAGE_RESULT_MEDIA_PERMISSION_DENIED = IMAGE_RESULT_BASE + 45,
IMAGE_RESULT_MEDIA_DEAD_OBJECT = IMAGE_RESULT_BASE + 46,
IMAGE_RESULT_MEDIA_TIMED_OUT = IMAGE_RESULT_BASE + 47,
IMAGE_RESULT_MEDIA_TRACK_NOT_ALL_SUPPORTED = IMAGE_RESULT_BASE + 48,
IMAGE_RESULT_MEDIA_ADAPTER_INIT_FAILED = IMAGE_RESULT_BASE + 49,
IMAGE_RESULT_MEDIA_WRITE_PARCEL_FAIL = IMAGE_RESULT_BASE + 50,
IMAGE_RESULT_MEDIA_READ_PARCEL_FAIL = IMAGE_RESULT_BASE + 51,
IMAGE_RESULT_MEDIA_NO_AVAIL_BUFFER = IMAGE_RESULT_BASE + 52,
IMAGE_RESULT_MEDIA_INVALID_PARAM = IMAGE_RESULT_BASE + 53, IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 54,
IMAGE_RESULT_MEDIA_CREATE_CODEC_ADAPTER_FAILED = IMAGE_RESULT_BASE + 55,
IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 56,
IMAGE_RESULT_MEDIA_ZCODEC_CREATE_FAILED = IMAGE_RESULT_BASE + 57,
IMAGE_RESULT_MEDIA_ZCODEC_NOT_EXIST = IMAGE_RESULT_BASE + 58,
IMAGE_RESULT_MEDIA_JNI_CLASS_NOT_EXIST = IMAGE_RESULT_BASE + 59,
IMAGE_RESULT_MEDIA_JNI_METHOD_NOT_EXIST = IMAGE_RESULT_BASE + 60,
IMAGE_RESULT_MEDIA_JNI_NEW_OBJ_FAILED = IMAGE_RESULT_BASE + 61,
IMAGE_RESULT_MEDIA_JNI_COMMON_ERROR = IMAGE_RESULT_BASE + 62,
IMAGE_RESULT_MEDIA_DISTRIBUTE_NOT_SUPPORT = IMAGE_RESULT_BASE + 63,
IMAGE_RESULT_MEDIA_SOURCE_NOT_SET = IMAGE_RESULT_BASE + 64,
IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 65,
IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 66,
IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT = IMAGE_RESULT_BASE + 67,
IMAGE_RESULT_MEDIA_RTSP_CAPTURE_NOT_INIT = IMAGE_RESULT_BASE + 68,
IMAGE_RESULT_MEDIA_RTSP_SOURCE_URL_INVALID = IMAGE_RESULT_BASE + 69,
IMAGE_RESULT_MEDIA_RTSP_VIDEO_TRACK_NOT_FOUND = IMAGE_RESULT_BASE + 70,
IMAGE_RESULT_MEDIA_RTSP_CAMERA_NUM_REACH_MAX = IMAGE_RESULT_BASE + 71,
IMAGE_RESULT_MEDIA_SET_VOLUME = IMAGE_RESULT_BASE + 72,
IMAGE_RESULT_MEDIA_NUMBER_OVERFLOW = IMAGE_RESULT_BASE + 73,
IMAGE_RESULT_MEDIA_DIS_PLAYER_UNSUPPORTED = IMAGE_RESULT_BASE + 74,
IMAGE_RESULT_MEDIA_DENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 75,
IMAGE_RESULT_MEDIA_ENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 76,
IMAGE_RESULT_MEDIA_READ_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 150,
IMAGE_RESULT_MEDIA_WRITE_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 151,
IMAGE_RESULT_MEDIA_PIXELMAP_NOT_ALLOW_MODIFY = IMAGE_RESULT_BASE + 152,
IMAGE_RESULT_MEDIA_CONFIG_FAILED = IMAGE_RESULT_BASE + 153,
IMAGE_RESULT_JNI_ENV_ABNORMAL = IMAGE_RESULT_BASE + 154,
IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED = IMAGE_RESULT_BASE + 155,
IMAGE_RESULT_CREATE_SURFACE_FAILED = IMAGE_RESULT_BASE + 156,
IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED = IMAGE_RESULT_BASE + 157,
IMAGE_RESULT_GET_SURFACE_FAILED = IMAGE_RESULT_BASE + 158,
IMAGE_RESULT_SURFACE_ACQUIRE_BUFFER_FAILED = IMAGE_RESULT_BASE + 159,
IMAGE_RESULT_SURFACE_REQUEST_BUFFER_FAILED = IMAGE_RESULT_BASE + 160,
IMAGE_RESULT_REGISTER_LISTENER_FAILED = IMAGE_RESULT_BASE + 161,
IMAGE_RESULT_REGISTER_BUFFER_FAILED = IMAGE_RESULT_BASE + 162,
IMAGE_RESULT_FREAD_FAILED = IMAGE_RESULT_BASE + 163,
IMAGE_RESULT_PEEK_FAILED = IMAGE_RESULT_BASE + 164,
IMAGE_RESULT_SEEK_FAILED = IMAGE_RESULT_BASE + 165,
IMAGE_RESULT_STREAM_SIZE_ERROR = IMAGE_RESULT_BASE + 166,
IMAGE_RESULT_FILE_FD_ERROR = IMAGE_RESULT_BASE + 167,
IMAGE_RESULT_FILE_DAMAGED = IMAGE_RESULT_BASE + 168,
IMAGE_RESULT_CREATE_DECODER_FAILED = IMAGE_RESULT_BASE + 169,
IMAGE_RESULT_CREATE_ENCODER_FAILED = IMAGE_RESULT_BASE + 170,
IMAGE_RESULT_CHECK_FORMAT_ERROR = IMAGE_RESULT_BASE + 171,
IMAGE_RESULT_THIRDPART_SKIA_ERROR = IMAGE_RESULT_BASE + 172,
IMAGE_RESULT_HW_DECODE_FAILED = IMAGE_RESULT_BASE + 173,
IMAGE_RESULT_ALLOCATER_TYPE_ERROR = IMAGE_RESULT_BASE + 174,
IMAGE_RESULT_ALPHA_TYPE_ERROR = IMAGE_RESULT_BASE + 175,
IMAGE_RESULT_INDEX_INVALID = IMAGE_RESULT_BASE + 176,
IMAGE_RESULT_MEDIA_UNKNOWN = IMAGE_RESULT_BASE + 200
} | 可能出现的返回值的枚举。 | diff --git a/zh-cn/application-dev/reference/native-apis/image__pixel__map__mdk_8h.md b/zh-cn/application-dev/reference/native-apis/image__pixel__map__mdk_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..77d3dc9f7dd11ee44f4dca10c704cc3745c1059e --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/image__pixel__map__mdk_8h.md @@ -0,0 +1,65 @@ +# image_pixel_map_mdk.h + + +## 概述 + +声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。 Need link **libpixelmapndk.z.so** + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [OhosPixelMapInfos](_ohos_pixel_map_infos.md) | 用于定义 pixel map 的相关信息。 | +| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。 | + + +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [NativePixelMap](image.md#nativepixelmap) | 定义native层pixelmap数据类型名称。 | +| [OhosPixelMapInfos](image.md#ohospixelmapinfos) | 用于定义 pixel map 的相关信息。 | + + +### 枚举 + +| 名称 | 描述 | +| -------- | -------- | +| { [OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN](image.md) = 0,
[OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE](image.md) = 1,
[OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL](image.md) = 2,
[OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL](image.md) = 3 } | PixelMap 透明度类型的枚举。 | +| { [OHOS_PIXEL_MAP_READ_ONLY](image.md) = 0,
[OHOS_PIXEL_MAP_EDITABLE](image.md) = 1 } | PixelMap 编辑类型的枚举。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [OH_PixelMap_CreatePixelMap](image.md#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。 | +| [OH_PixelMap_CreateAlphaPixelMap](image.md#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 | +| [OH_PixelMap_InitNativePixelMap](image.md#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。 | +| [OH_PixelMap_GetBytesNumberPerRow](image.md#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。 | +| [OH_PixelMap_GetIsEditable](image.md#oh_pixelmap_getiseditable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*editable) | 获取**PixelMap**对象是否可编辑的状态。 | +| [OH_PixelMap_IsSupportAlpha](image.md#oh_pixelmap_issupportalpha) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。 | +| [OH_PixelMap_SetAlphaAble](image.md#oh_pixelmap_setalphaable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。 | +| [OH_PixelMap_GetDensity](image.md#oh_pixelmap_getdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。 | +| [OH_PixelMap_SetDensity](image.md#oh_pixelmap_setdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。 | +| [OH_PixelMap_SetOpacity](image.md#oh_pixelmap_setopacity) (const [NativePixelMap](image.md#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。 | +| [OH_PixelMap_Scale](image.md#oh_pixelmap_scale) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。 | +| [OH_PixelMap_Translate](image.md#oh_pixelmap_translate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。 | +| [OH_PixelMap_Rotate](image.md#oh_pixelmap_rotate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。 | +| [OH_PixelMap_Flip](image.md#oh_pixelmap_flip) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。 | +| [OH_PixelMap_Crop](image.md#oh_pixelmap_crop) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y, int32_t width, int32_t height) | 设置**PixelMap**对象的裁剪。 | +| [OH_PixelMap_GetImageInfo](image.md#oh_pixelmap_getimageinfo) (const [NativePixelMap](image.md#nativepixelmap) \*native, [OhosPixelMapInfos](_ohos_pixel_map_infos.md) \*info) | 获取**PixelMap**对象图像信息。 | +| [OH_PixelMap_AccessPixels](image.md#oh_pixelmap_accesspixels) (const [NativePixelMap](image.md#nativepixelmap) \*native, void \*\*addr) | 获取native **PixelMap** 对象数据的内存地址,并锁定该内存。 | +| [OH_PixelMap_UnAccessPixels](image.md#oh_pixelmap_unaccesspixels) (const [NativePixelMap](image.md#nativepixelmap) \*native) | 释放native **PixelMap**对象数据的内存锁,用于匹配方法 [OH_PixelMap_AccessPixels](image.md#oh_pixelmap_accesspixels)。 | diff --git a/zh-cn/application-dev/reference/native-apis/image__pixel__map__napi_8h.md b/zh-cn/application-dev/reference/native-apis/image__pixel__map__napi_8h.md index 2b375f4330ae4243d5f737345efd9bd78351fab5..26113cb4232ab665181b6bda16f814d3c02ad46b 100644 --- a/zh-cn/application-dev/reference/native-apis/image__pixel__map__napi_8h.md +++ b/zh-cn/application-dev/reference/native-apis/image__pixel__map__napi_8h.md @@ -19,122 +19,24 @@ ### 结构体 -| 名称 | 描述 | -| -------- | -------- | -| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 | -| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。 | - -### 类型定义 - | 名称 | 描述 | | -------- | -------- | -| [NativePixelMap](image.md#nativepixelmap) | 用于定义NativePixelMap数据类型名称。 | +| [OHOS::Media::OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 | ### 枚举 | 名称 | 描述 | | -------- | -------- | -| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | 函数方法返回值的错误码的枚举。 | -| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | pixel 格式的枚举。 | -| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | PixelMap alpha 类型的枚举。 | -| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | PixelMap 缩放类型的枚举。 | -| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | PixelMap 编辑类型的枚举。 | +| { [OHOS::Media::OHOS_IMAGE_RESULT_SUCCESS](image.md) = 0,
[OHOS::Media::OHOS_IMAGE_RESULT_BAD_PARAMETER](image.md) = -1 } | 函数方法返回值的错误码的枚举。 | +| { [OHOS::Media::OHOS_PIXEL_MAP_FORMAT_NONE](image.md) = 0,
[OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGBA_8888](image.md) = 3,
[OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGB_565](image.md) = 2 } | pixel 格式的枚举。 | +| { [OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE](image.md) = 0,
[OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP](image.md) = 1 } | PixelMap 缩放类型的枚举。 | ### 函数 | 名称 | 描述 | | -------- | -------- | -| [OH_GetImageInfo](image.md#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_ohos_pixel_map_info.md)结构中。 | -| [OH_AccessPixels](image.md#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。 | -| [OH_UnAccessPixels](image.md#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法[OH_AccessPixels](image.md#oh_accesspixels)。 | -| [OH_PixelMap_CreatePixelMap](image.md#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。 | -| [OH_PixelMap_CreateAlphaPixelMap](image.md#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 | -| [OH_PixelMap_InitNativePixelMap](image.md#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。 | -| [OH_PixelMap_GetBytesNumberPerRow](image.md#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。 | -| [OH_PixelMap_GetIsEditable](image.md#oh_pixelmap_getiseditable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*[editable](#editable)) | 获取**PixelMap**对象是否可编辑的状态。 | -| [OH_PixelMap_IsSupportAlpha](image.md#oh_pixelmap_issupportalpha) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。 | -| [OH_PixelMap_SetAlphaAble](image.md#oh_pixelmap_setalphaable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。 | -| [OH_PixelMap_GetDensity](image.md#oh_pixelmap_getdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。 | -| [OH_PixelMap_SetDensity](image.md#oh_pixelmap_setdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。 | -| [OH_PixelMap_SetOpacity](image.md#oh_pixelmap_setopacity) (const [NativePixelMap](image.md#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。 | -| [OH_PixelMap_Scale](image.md#oh_pixelmap_scale) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。 | -| [OH_PixelMap_Translate](image.md#oh_pixelmap_translate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。 | -| [OH_PixelMap_Rotate](image.md#oh_pixelmap_rotate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。 | -| [OH_PixelMap_Flip](image.md#oh_pixelmap_flip) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。 | -| [OH_PixelMap_Crop](image.md#oh_pixelmap_crop) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](#width), int32_t [height](#height)) | 设置**PixelMap**对象的裁剪。 | - -### 变量 - -| 名称 | 描述 | -| -------- | -------- | -| [width](#width) | 图片的宽, 用pixels表示。| -| [height](#height) | 图片的高, 用pixels表示。| -| [pixelFormat](#pixelformat) | 图片的格式。| -| [editable](#editable) | 图片的编辑类型。| -| [alphaType](#alphatype) | 图片的alpha类型。| -| [scaleMode](#scalemode) | 图片的缩放类型。| - -## 变量说明 - - -### alphaType - - -``` -uint32_t alphaType -``` -**描述:** -图片的alpha类型。 - - -### editable - - -``` -uint32_t editable -``` -**描述:** -图片的编辑类型。 - - -### height - - -``` -uint32_t height -``` -**描述:** -图片的高, 用pixels表示。 - - -### pixelFormat - - -``` -int32_t pixelFormat -``` -**描述:** -图片的格式。 - - -### scaleMode - - -``` -uint32_t scaleMode -``` -**描述:** -图片的缩放类型。 - - -### width - - -``` -uint32_t width -``` -**描述:** -图片的宽, 用pixels表示。 - +| [OHOS::Media::OH_GetImageInfo](image.md#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)结构中。 | +| [OHOS::Media::OH_AccessPixels](image.md#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。 | +| [OHOS::Media::OH_UnAccessPixels](image.md#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法**OH_AccessPixels**。 | diff --git a/zh-cn/application-dev/reference/native-apis/image__receiver__mdk_8h.md b/zh-cn/application-dev/reference/native-apis/image__receiver__mdk_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..d3d5fccee825bc863a956ddd8c2a07dc11fcf598 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/image__receiver__mdk_8h.md @@ -0,0 +1,48 @@ +# image_receiver_mdk.h + + +## 概述 + +声明从native层获取图片数据的方法。 + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [OhosImageReceiverInfo](_ohos_image_receiver_info.md) | 定义**ImageReceiver**的相关信息。 | + + +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [ImageReceiverNative](image.md#imagereceivernative) | 用于定义ImageReceiverNative数据类型名称。 | +| (\*[OH_Image_Receiver_On_Callback](image.md#oh_image_receiver_on_callback)) () | 定义native层图片的回调方法。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [OH_Image_Receiver_CreateImageReceiver](image.md#oh_image_receiver_createimagereceiver) (napi_env env, struct [OhosImageReceiverInfo](_ohos_image_receiver_info.md) info, napi_value \*res) | 创建应用层 **ImageReceiver** 对象。 | +| [OH_Image_Receiver_InitImageReceiverNative](image.md#oh_image_receiver_initimagereceivernative) (napi_env env, napi_value source) | 通过应用层**ImageReceiver**对象初始化native层[ImageReceiverNative](image.md#imagereceivernative)对象。 | +| [OH_Image_Receiver_GetReceivingSurfaceId](image.md#oh_image_receiver_getreceivingsurfaceid) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, char \*id, size_t len) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取receiver的id。 | +| [OH_Image_Receiver_ReadLatestImage](image.md#oh_image_receiver_readlatestimage) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取最新的一张图片。 | +| [OH_Image_Receiver_ReadNextImage](image.md#oh_image_receiver_readnextimage) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取下一张图片。 | +| [OH_Image_Receiver_On](image.md#oh_image_receiver_on) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, [OH_Image_Receiver_On_Callback](image.md#oh_image_receiver_on_callback) callback) | 注册一个[OH_Image_Receiver_On_Callback](image.md#oh_image_receiver_on_callback)回调事件。每当接收新图片,该回调事件就会响应。 | +| [OH_Image_Receiver_GetSize](image.md#oh_image_receiver_getsize) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取**ImageReceiver**的大小。 | +| [OH_Image_Receiver_GetCapacity](image.md#oh_image_receiver_getcapacity) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, int32_t \*capacity) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取**ImageReceiver**的容量。 | +| [OH_Image_Receiver_GetFormat](image.md#oh_image_receiver_getformat) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, int32_t \*format) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取**ImageReceiver**的格式。 | +| [OH_Image_Receiver_Release](image.md#oh_image_receiver_release) ([ImageReceiverNative](image.md#imagereceivernative) \*native) | 释放native层 [ImageReceiverNative](image.md#imagereceivernative) 对象。 | diff --git a/zh-cn/application-dev/reference/native-apis/image__source__mdk_8h.md b/zh-cn/application-dev/reference/native-apis/image__source__mdk_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..21a0717afb810142a76cb3208fc55efddeac7af0 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/image__source__mdk_8h.md @@ -0,0 +1,81 @@ +# image_source_mdk.h + + +## 概述 + +声明将图片源解码成像素位图的方法。 + +\@Syscap SystemCapability.Multimedia.Image + +**起始版本:** + +10 + +**相关模块:** + +[Image](image.md) + + +## 汇总 + + +### 结构体 + +| 名称 | 描述 | +| -------- | -------- | +| [OhosImageRegion](_ohos_image_region.md) | 定义图像源解码的范围选项。 | +| [OhosImageSourceOps](_ohos_image_source_ops.md) | 定义图像源选项信息。 | +| [OhosImageDecodingOps](_ohos_image_decoding_ops.md) | 定义图像源解码选项。 | +| [OhosImageSourceInfo](_ohos_image_source_info.md) | 定义图像源信息。 | +| [OhosImageSource](_ohos_image_source.md) | 定义图像源输入资源,每次仅接收一种类型。 | +| [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) | 定义图像源延迟时间列表。 | +| [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md) | 定义图像源支持的格式字符串。 | +| [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) | 定义图像源支持的格式字符串列表。 | +| [OhosImageSourceProperty](_ohos_image_source_property.md) | 定义图像源属性键值字符串。 | +| [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) | 定义图像源更新数据选项。 | + + +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [ImageSourceNative](image.md#imagesourcenative) | 为图像源方法定义native层图像源对象。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [OH_ImageSource_Create](image.md#oh_imagesource_create) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*src, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的信息[OhosImageSource](_ohos_image_source.md)和[OhosImageSourceOps](_ohos_image_source_ops.md)结构体,获取JavaScript native层API**ImageSource**对象。 | +| [OH_ImageSource_CreateIncremental](image.md#oh_imagesource_createincremental) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*source, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的infomations[OhosImageSource](_ohos_image_source.md)和[OhosImageSourceOps](_ohos_image_source_ops.md)结构, 获取增量类型的JavaScript Native API ImageSource对象,图像数据应通过OH_ImageSource_UpdateData更新。 | +| [OH_ImageSource_GetSupportedFormats](image.md#oh_imagesource_getsupportedformats) (struct [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) \*res) | 获取所有支持的解码格式元标记。 | +| \*[OH_ImageSource_InitNative](image.md#oh_imagesource_initnative) (napi_env env, napi_value source) | 从输入JavaScript native层API **ImageSource** 对象中,转换成[ImageSourceNative](image.md#imagesourcenative)值。 | +| [OH_ImageSource_CreatePixelMap](image.md#oh_imagesource_createpixelmap) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码JavaScript native层API**PixelMap**对象 | +| [OH_ImageSource_CreatePixelMapList](image.md#oh_imagesource_createpixelmaplist) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码所有的JavaScript native层API**PixelMap**对象列表 | +| [OH_ImageSource_GetDelayTime](image.md#oh_imagesource_getdelaytime) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) \*res) | 从一些**ImageSource**(如GIF图像源)获取延迟时间列表。 | +| [OH_ImageSource_GetFrameCount](image.md#oh_imagesource_getframecount) (const [ImageSourceNative](image.md#imagesourcenative) \*native, uint32_t \*res) | 从**ImageSource**中获取帧计数。 | +| [OH_ImageSource_GetImageInfo](image.md#oh_imagesource_getimageinfo) (const [ImageSourceNative](image.md#imagesourcenative) \*native, int32_t index, struct [OhosImageSourceInfo](_ohos_image_source_info.md) \*info) | 通过索引从**ImageSource**获取图像源信息。 | +| [OH_ImageSource_GetImageProperty](image.md#oh_imagesource_getimageproperty) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字从**ImageSource**中获取图像源属性。 | +| [OH_ImageSource_ModifyImageProperty](image.md#oh_imagesource_modifyimageproperty) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字为**ImageSource**修改图像源属性。 | +| [OH_ImageSource_UpdateData](image.md#oh_imagesource_updatedata) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) \*data) | 为了增量类型的**ImageSource**更新源数据。 | +| [OH_ImageSource_Release](image.md#oh_imagesource_release) ([ImageSourceNative](image.md#imagesourcenative) \*native) | 释放native层图像源 **ImageSourceNative**。 | + + +### 变量 + +| 名称 | 描述 | +| -------- | -------- | +| \*[OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE](image.md#ohos_image_property_bits_per_sample) = "BitsPerSample" | 定义每个样本比特的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_ORIENTATION](image.md#ohos_image_property_orientation) = "Orientation" | 定义方向的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_IMAGE_LENGTH](image.md#ohos_image_property_image_length) = "ImageLength" | 定义图像长度的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_IMAGE_WIDTH](image.md#ohos_image_property_image_width) = "ImageWidth" | 定义图像宽度的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_GPS_LATITUDE](image.md#ohos_image_property_gps_latitude) = "GPSLatitude" | 定义GPS纬度的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_GPS_LONGITUDE](image.md#ohos_image_property_gps_longitude) = "GPSLongitude" | 定义GPS经度的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF](image.md#ohos_image_property_gps_latitude_ref) = "GPSLatitudeRef" | 定义GPS纬度参考的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF](image.md#ohos_image_property_gps_longitude_ref) = "GPSLongitudeRef" | 定义GPS经度参考的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL](image.md#ohos_image_property_date_time_original) = "DateTimeOriginal" | 定义初始日期时间的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_EXPOSURE_TIME](image.md#ohos_image_property_exposure_time) = "ExposureTime" | 定义曝光时间的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_SCENE_TYPE](image.md#ohos_image_property_scene_type) = "SceneType" | 定义场景类型的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS](image.md#ohos_image_property_iso_speed_ratings) = "ISOSpeedRatings" | 定义ISO速度等级的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_F_NUMBER](image.md#ohos_image_property_f_number) = "FNumber" | 定义FNumber的图像属性关键字。 | +| \*[OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL](image.md#ohos_image_property_compressed_bits_per_pixel) = "CompressedBitsPerPixel" | 定义每个像素的压缩比特的图像属性关键字。 | diff --git a/zh-cn/application-dev/reference/native-apis/native__interface__xcomponent_8h.md b/zh-cn/application-dev/reference/native-apis/native__interface__xcomponent_8h.md index afd646012f3276b5a8bbbde55dab5f66b9e1a458..52781dfb75e16b367515c9c4df0bb7b702c0a6ab 100644 --- a/zh-cn/application-dev/reference/native-apis/native__interface__xcomponent_8h.md +++ b/zh-cn/application-dev/reference/native-apis/native__interface__xcomponent_8h.md @@ -5,11 +5,11 @@ 声明用于访问Native XComponent的API。 -**起始版本:** +**起始版本:** 8 -**相关模块:** +**相关模块:** [Native XComponent](_o_h___native_x_component.md) @@ -19,50 +19,65 @@ ### 结构体 -| 结构体名称 | 描述 | -| -------- | -------- | -| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | 触摸事件中触摸点的信息。 | -| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | 触摸事件。 | -| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | 鼠标事件。 | +| 名称 | 描述 | +| ---------------------------------------- | --------------------- | +| [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) | 触摸事件中触摸点的信息。 | +| [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md) | 触摸事件。 | +| [OH_NativeXComponent_MouseEvent](_o_h___native_x_component___mouse_event.md) | 鼠标事件。 | | [OH_NativeXComponent_Callback](_o_h___native_x_component___callback.md) | 注册surface生命周期和触摸事件回调。 | -| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | 注册鼠标事件的回调。 | +| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md) | 注册鼠标事件的回调。 | ### 类型定义 -| 类型定义名称 | 描述 | -| -------- | -------- | -| [OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) | 提供封装的OH_NativeXComponent实例。 | -| [OH_NativeXComponent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_callback) | 注册surface生命周期和触摸事件回调。 | -| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_mouseevent_callback) | 注册鼠标事件的回调。 | +| 名称 | 描述 | +| ---------------------------------------- | ------------------------------------ | +| [OH_NativeXComponent](_o_h___native_x_component.md#oh_nativexcomponent) | 提供封装的OH_NativeXComponent实例。 | +| [OH_NativeXComponent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_callback) | 注册surface生命周期和触摸事件回调。 | +| [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component.md#oh_nativexcomponent_mouseevent_callback) | 注册鼠标事件的回调。 | +| [OH_NativeXComponent_KeyEvent](_o_h___native_x_component.md#oh_nativexcomponent_keyevent) | 提供封装的OH_NativeXComponent_KeyEvent实例。 | ### 枚举 -| 枚举名称 | 描述 | -| -------- | -------- | -| { OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0,
OH_NATIVEXCOMPONENT_RESULT_FAILED = -1,
OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2} | [枚举](_o_h___native_x_component.md#anonymous-enum)API访问状态。 | -| [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 } | 触摸事件类型。 | -| [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 } | 鼠标事件动作。 | -| [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 } | 鼠标事件按键。 | +| 枚举名称 | 描述 | +| ---------------------------------------- | ---------- | +| { OH_NATIVEXCOMPONENT_RESULT_SUCCESS = 0, OH_NATIVEXCOMPONENT_RESULT_FAILED = -1, OH_NATIVEXCOMPONENT_RESULT_BAD_PARAMETER = -2 } | 枚举API访问状态。 | +| [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
} | 触摸事件类型。 | +| [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
} | 触摸点工具类型。 | +| [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
} | 触摸事件源类型。 | +| [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 } | 鼠标事件动作。 | +| [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
} | 鼠标事件按键。 | ### 函数 -| 函数名称 | 描述 | -| -------- | -------- | -| [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) | 获取ArkUI XComponent的id。 | -| [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) | 获取ArkUI XComponent持有的surface的大小。 | -| [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) | 获取ArkUI XComponent组件相对屏幕左上顶点的偏移量。 | -| [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) | 获取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) | 获取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) | 为此OH_NativeXComponent实例注册回调。 | -| [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) | 为此OH_NativeXComponent实例注册鼠标事件回调。 | +| 名称 | 描述 | +| ---------------------------------------- | -------------------------------------- | +| [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) | 获取ArkUI XComponent的id。 | +| [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) | 获取ArkUI XComponent持有的surface的大小。 | +| [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) | 获取ArkUI XComponent组件相对屏幕左上顶点的偏移量。 | +| [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) | 获取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) | 获取ArkUI XComponent触摸点工具类型。 | +| [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) | 获取ArkUI XComponent触摸点倾斜与X轴角度。 | +| [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) | 获取ArkUI XComponent触摸点倾斜与Y轴角度。 | +| [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) | 获取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) | 为此OH_NativeXComponent实例注册回调。 | +| [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) | 为此OH_NativeXComponent实例注册鼠标事件回调。 | +| [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)) | 为此OH_NativeXComponent实例注册获焦事件回调。 | +| [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)) | 为此OH_NativeXComponent实例注册按键事件回调。 | +| [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)) | 为此OH_NativeXComponent实例注册失焦事件回调。 | +| [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) | 获取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) | 获取传入按键事件的动作。 | +| [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) | 获取传入按键事件的按键码。 | +| [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) | 获取传入按键事件的事件源类型。 | +| [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) | 获取传入按键事件的设备id。 | +| [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) | 获取传入按键事件的时间戳。 | ### 变量 -| 变量名称 | 描述 | -| -------- | -------- | -| **OH_XCOMPONENT_ID_LEN_MAX** = 128 | ArkUI XComponent的id的最大长度。 | -| **OH_MAX_TOUCH_POINTS_NUMBER** = 10 | 触摸事件中的可识别的触摸点个数最大值。 | +| 名称 | 描述 | +| ---------------------------------------- | ------------------------- | +| **OH_XCOMPONENT_ID_LEN_MAX** = 128 | ArkUI XComponent的id的最大长度。 | +| **OH_MAX_TOUCH_POINTS_NUMBER** = 10 | 触摸事件中的可识别的触摸点个数最大值。 | diff --git a/zh-cn/application-dev/reference/native-apis/native__xcomponent__key__event_8h.md b/zh-cn/application-dev/reference/native-apis/native__xcomponent__key__event_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..6f7ad998dc526858d0229d5232d7cfab5f5c3e88 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/native__xcomponent__key__event_8h.md @@ -0,0 +1,25 @@ +# native_xcomponent_key_event.h + + +## 概述 + +声明用于访问Native XComponent键盘事件所使用到的枚举类型。 + +**起始版本:** + +10 + +**相关模块:** + +[Native XComponent](_o_h___native_x_component.md) + + +## 汇总 + + +### 枚举 + +| 名称 | 描述 | +| -------- | -------- | +| [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
} | 按键事件的键码。 | +| [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 } | 按键事件动作。 | diff --git a/zh-cn/application-dev/reference/native-apis/oh__cursor_8h.md b/zh-cn/application-dev/reference/native-apis/oh__cursor_8h.md index a26b98ca89b090de9683dec7cd566211193bb60e..0113d44ad78f81d64b299775f2c169a626351f33 100644 --- a/zh-cn/application-dev/reference/native-apis/oh__cursor_8h.md +++ b/zh-cn/application-dev/reference/native-apis/oh__cursor_8h.md @@ -30,6 +30,7 @@ | 名称 | 描述 | | -------- | -------- | +| [OH_ColumnType](_r_d_b.md#oh_columntype) | 数据库字段类型. | | [OH_Cursor](_r_d_b.md#oh_cursor) | 表示结果集。 | @@ -37,4 +38,4 @@ | 名称 | 描述 | | -------- | -------- | -| [OH_ColumnType](_r_d_b.md#oh_columntype) {
TYPE_NULL = 0, TYPE_INT64, TYPE_REAL, TYPE_TEXT,
TYPE_BLOB
} | 数据库字段类型. | +| [OH_ColumnType](_r_d_b.md#oh_columntype) {
TYPE_NULL = 0, TYPE_INT64, TYPE_REAL, TYPE_TEXT,
TYPE_BLOB
} | 数据库字段类型. | diff --git a/zh-cn/application-dev/reference/native-apis/oh__predicates_8h.md b/zh-cn/application-dev/reference/native-apis/oh__predicates_8h.md index c59b86d0fbf3b107ec7a65f13b6b3112030c8668..d1b8698d6f181474424e4ec1aa24076f3a9983a4 100644 --- a/zh-cn/application-dev/reference/native-apis/oh__predicates_8h.md +++ b/zh-cn/application-dev/reference/native-apis/oh__predicates_8h.md @@ -28,6 +28,7 @@ | 名称 | 描述 | | -------- | -------- | +| [OH_OrderType](_r_d_b.md#oh_ordertype) | 排序方式。 | | [OH_Predicates](_r_d_b.md#oh_predicates) | 表示谓词。 | @@ -35,4 +36,4 @@ | 名称 | 描述 | | -------- | -------- | -| [OH_OrderType](_r_d_b.md#oh_ordertype) { ASC = 0, DESC = 1 } | 排序方式。 | +| [OH_OrderType](_r_d_b.md#oh_ordertype) { ASC = 0, DESC = 1 } | 排序方式。 | diff --git a/zh-cn/application-dev/reference/native-apis/relational__store_8h.md b/zh-cn/application-dev/reference/native-apis/relational__store_8h.md index 5a435168e72b1f0c20f7009f5e0b0915771f5108..9d19fe056a4e8021e00c0e75d4690c76d244eb70 100644 --- a/zh-cn/application-dev/reference/native-apis/relational__store_8h.md +++ b/zh-cn/application-dev/reference/native-apis/relational__store_8h.md @@ -9,7 +9,7 @@ 10 -**相关模块:** +**相关模块:** [RDB](_r_d_b.md) @@ -25,6 +25,13 @@ | [OH_Rdb_Store](_o_h___rdb___store.md) | 表示数据库类型。 | +### 类型定义 + +| 名称 | 描述 | +| -------- | -------- | +| [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel) | 数据库的安全级别枚举。 | + + ### 枚举 | 名称 | 描述 | @@ -41,7 +48,7 @@ | [OH_Rdb_CreatePredicates](_r_d_b.md#oh_rdb_createpredicates) (const char \*table) | 创建[OH_Predicates](_o_h___predicates.md)实例。 | | [OH_Rdb_GetOrOpen](_r_d_b.md#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | 获得一个相关的[OH_Rdb_Store](_o_h___rdb___store.md)实例,操作关系型数据库。 | | [OH_Rdb_CloseStore](_r_d_b.md#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | 销毁[OH_Rdb_Store](_o_h___rdb___store.md)对象,并回收该对象占用的内存。 | -| [OH_Rdb_DeleteStore](_r_d_b.md#oh_rdb_deletestore) (const char \*path) | 使用指定的数据库文件配置删除数据库。 | +| [OH_Rdb_DeleteStore](_r_d_b.md#oh_rdb_deletestore) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config) | 使用指定的数据库文件配置删除数据库。 | | [OH_Rdb_Insert](_r_d_b.md#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | 向目标表中插入一行数据。 | | [OH_Rdb_Update](_r_d_b.md#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件更新数据库中的数据。 | | [OH_Rdb_Delete](_r_d_b.md#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件删除数据库中的数据。 | diff --git a/zh-cn/application-dev/reference/native-apis/tensor_8h.md b/zh-cn/application-dev/reference/native-apis/tensor_8h.md index fff4ac894047493d717219a763714a7e3f2dd3bf..86d34f640ace9713f441a268d3a36a8efe7d9dbe 100644 --- a/zh-cn/application-dev/reference/native-apis/tensor_8h.md +++ b/zh-cn/application-dev/reference/native-apis/tensor_8h.md @@ -44,3 +44,4 @@ | [OH_AI_TensorGetMutableData](_mind_spore.md#oh_ai_tensorgetmutabledata) (const OH_AI_TensorHandle tensor) | 获取可变的张量数据指针。如果数据为空则会开辟内存。 | | [OH_AI_TensorGetElementNum](_mind_spore.md#oh_ai_tensorgetelementnum) (const OH_AI_TensorHandle tensor) | 获取张量元素数量。 | | [OH_AI_TensorGetDataSize](_mind_spore.md#oh_ai_tensorgetdatasize) (const OH_AI_TensorHandle tensor) | 获取张量中的数据的字节数大小。 | +| [OH_AI_TensorSetUserData](_mind_spore.md#oh_ai_tensorsetuserdata) ([OH_AI_TensorHandle](_mind_spore.md#oh_ai_tensorhandle) tensor, void \*data, size_t data_size) | 设置张量为用户自行管理的数据。此接口常用于复用用户数据作为模型输入,可减少一次数据拷贝。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md b/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md index 0a5414b122166d3a6d0ae98485d49a24b231c41c..136f63d9fb687249d8824b2a2a20f064626563f6 100644 --- a/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md +++ b/zh-cn/application-dev/reference/native-apis/vulkan__ohos_8h.md @@ -23,8 +23,8 @@ | -------- | -------- | | [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) | 包含创建Vulkan Surface时必要的参数。 | | [VkNativeBufferUsageOHOS](_vk_native_buffer_usage_o_h_o_s.md) | 提供OpenHarmony NativeBuffer用途的说明。 | -| [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) | 包含了NaitveBuffer的属性。 | -| [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) | 包含了NaitveBuffer的一些格式属性。 | +| [VkNativeBufferPropertiesOHOS](_vk_native_buffer_properties_o_h_o_s.md) | 包含了NativeBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](_vk_native_buffer_format_properties_o_h_o_s.md) | 包含了NativeBuffer的一些格式属性。 | | [VkImportNativeBufferInfoOHOS](_vk_import_native_buffer_info_o_h_o_s.md) | 包含了OH_NativeBuffer结构体的指针。 | | [VkMemoryGetNativeBufferInfoOHOS](_vk_memory_get_native_buffer_info_o_h_o_s.md) | 用于从Vulkan内存中获取OH_NativeBuffer。 | | [VkExternalFormatOHOS](_vk_external_format_o_h_o_s.md) | 表示外部定义的格式标识符。 | @@ -51,8 +51,8 @@ | [VkSurfaceCreateInfoOHOS](_vulkan.md#vksurfacecreateinfoohos) | 包含创建Vulkan Surface时必要的参数。 | | VkResult ([VKAPI_PTR *PFN_vkCreateSurfaceOHOS](_vulkan.md#pfn_vkcreatesurfaceohos)) (VkInstance instance, const [VkSurfaceCreateInfoOHOS](_vk_surface_create_info_o_h_o_s.md) \*pCreateInfo, const VkAllocationCallbacks \*pAllocator, VkSurfaceKHR \*pSurface) | 创建Vulkan Surface的函数指针定义。 | | [VkNativeBufferUsageOHOS](_vulkan.md#vknativebufferusageohos) | 提供OpenHarmony NativeBuffer用途的说明。 | -| [VkNativeBufferPropertiesOHOS](_vulkan.md#vknativebufferpropertiesohos) | 包含了NaitveBuffer的属性。 | -| [VkNativeBufferFormatPropertiesOHOS](_vulkan.md#vknativebufferformatpropertiesohos) | 包含了NaitveBuffer的一些格式属性。 | +| [VkNativeBufferPropertiesOHOS](_vulkan.md#vknativebufferpropertiesohos) | 包含了NativeBuffer的属性。 | +| [VkNativeBufferFormatPropertiesOHOS](_vulkan.md#vknativebufferformatpropertiesohos) | 包含了NativeBuffer的一些格式属性。 | | [VkImportNativeBufferInfoOHOS](_vulkan.md#vkimportnativebufferinfoohos) | 包含了OH_NativeBuffer结构体的指针。 | | [VkMemoryGetNativeBufferInfoOHOS](_vulkan.md#vkmemorygetnativebufferinfoohos) | 用于从Vulkan内存中获取OH_NativeBuffer。 | | [VkExternalFormatOHOS](_vulkan.md#vkexternalformatohos) | 表示外部定义的格式标识符。 | diff --git a/zh-cn/application-dev/reference/syscap-list.md b/zh-cn/application-dev/reference/syscap-list.md index 1cf23e3cb377d6020603fd7bcbc6fed02d22d33e..d897ef20a5fdd53b04075cd323e86d9f4e87c94a 100644 --- a/zh-cn/application-dev/reference/syscap-list.md +++ b/zh-cn/application-dev/reference/syscap-list.md @@ -951,10 +951,15 @@ TS/JS语言基础库 | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | 是 | 否 | 是 | 是 | 否 | 是 | 否 | 否 | -## SystemCapability.Security.Huks -设备密钥管理 +## SystemCapability.Security.Huks.Core +设备密钥管理-核心能力 +| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| 是 | 是 | 是 | 是 | 否 | 是 | 否 | 否 | +## SystemCapability.Security.Huks.Extension +设备密钥管理-扩展能力 | Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | 是 | 否 | 是 | 是 | 否 | 是 | 否 | 否 | diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 50e02d35ef75231bca80b370dbc517317a245577..fa22574a3df5392c5d04844591b1c83dfc5f6def 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -336,16 +336,13 @@ reqPermissions() { ``` ## user_grant权限预授权 -应用在申请`user_grant`类型的权限默认未授权,需要通过拉起弹框由用户确认是否授予该权限。对于一些预制应用,不希望出现弹窗申请`user_grant`类型的权限,例如系统相机应用需要使用麦克风` ohos.permission.MICROPHONE`等权限,需要对麦克风等权限进行预授权,可以通过预授权的方式完成`user_grant`类型权限的授权。[预置配置文件](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json)在设备上的路径为`/system/etc/app/install_list_permission.json`,设备开机启动时会读取该配置文件,在应用安装会对在文件中配置的`user_grant`类型权限授权。预授权配置文件字段内容包括`bundleName`、`app_signature`和`permissions`。 + +user_grant权限可以通过预授权方式请求权限。预授权方式需要预置配置文件,[预置配置文件](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json)在设备上的路径为`/system/etc/app/install_list_permission.json`,设备开机启动时会读取该配置文件,在应用安装会对在文件中配置的`user_grant`类型权限授权。预授权配置文件字段内容包括`bundleName`、`app_signature`和`permissions`。 - `bundleName`字段配置为应用的Bundle名称。 - `app_signature`字段配置为应用的指纹信息。指纹信息的配置参见[应用特权配置指南](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#install_list_capabilityjson中配置)。 - `permissions`字段中`name`配置为需要预授权的`user_grant`类型的权限名;`permissions`字段中`userCancellable`表示为用户是否能够取消该预授权,配置为true,表示支持用户取消授权,为false则表示不支持用户取消授权。 -> **说明**: -> -> 当前仅支持预置应用配置该文件。 - ```json [ // ... diff --git a/zh-cn/application-dev/security/cert-guidelines.md b/zh-cn/application-dev/security/cert-guidelines.md index 12a7b66c636680f1c0e8bd99ba9cc5916bf15bbb..cb77fbca5ef8270c8440f941668c39a8f6c2f055 100755 --- a/zh-cn/application-dev/security/cert-guidelines.md +++ b/zh-cn/application-dev/security/cert-guidelines.md @@ -34,7 +34,7 @@ | X509Cert | getPublicKey() : cryptoFramework.PubKey | 获取证书公钥 | | X509Cert | checkValidityWithDate(date: string) : void | 校验证书有效期 | | X509Cert | getVersion() : number | 获取证书版本 | -| X509Cert | getSerialNumber() : number | 获取证书序列号 | +| X509Cert | getCertSerialNumber() : bigint10+ | 获取证书序列号 | | X509Cert | getIssuerName() : DataBlob | 获取证书颁发者名称 | | X509Cert | getSubjectName() : DataBlob | 获取证书主体名称 | | X509Cert | getNotBeforeTime() : string | 获取证书有效期起始时间 | diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index c13414d4770fd5d74b4c93a860159ff751f5d633..c9514d960e47317d10d6772f8300d270462fae3e 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -390,7 +390,7 @@ ## ohos.permission.SET_WALLPAPER -允许应用设置静态壁纸。 +允许应用设置壁纸。 **权限级别**:normal @@ -414,7 +414,7 @@ ## ohos.permission.CHANGE_ABILITY_ENABLED_STATE -允许改变应用或者组件的使能状态。 +允许改变应用或组件的使能状态。 **权限级别**:system_basic @@ -776,7 +776,7 @@ ## ohos.permission.MANAGE_MISSIONS -允许用户管理元能力任务栈。 +允许应用管理系统中的任务。 **权限级别**:system_core @@ -846,9 +846,21 @@ **起始版本**:10 +## ohos.permission.NETSYS_INTERNAL + +允许SA服务调用网络管理netsys中的网络管理、wifi、网卡监听、iptables设置等功能接口。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:FALSE + +**起始版本**:10 + ## ohos.permission.SET_ABILITY_CONTROLLER -允许设置ability组件启动和停止控制权。 +允许应用拦截Ability组件启动,主要用于测试调试,比如稳定性金刚测试。 **权限级别**:system_basic @@ -872,7 +884,7 @@ ## ohos.permission.MANAGE_USER_IDM -允许应用使用系统身份凭据管理能力进行口令、人脸、指纹等录入、修改、删除等操作。 +允许录入和管理用户身份认证凭据。 **权限级别**:system_basic @@ -896,7 +908,7 @@ ## ohos.permission.ACCESS_USER_AUTH_INTERNAL -允许应用使用系统身份认证能力进行用户身份认证或身份识别。 +允许调用统一身份认证服务的系统内部接口。 **权限级别**:system_basic @@ -908,7 +920,7 @@ ## ohos.permission.ACCESS_PIN_AUTH -允许应用使用口令输入接口,用于系统应用完成口令输入框绘制场景。 +允许注册口令认证过程获取口令数据的回调。 **权限级别**:system_basic @@ -944,7 +956,7 @@ ## ohos.permission.RUNNING_STATE_OBSERVER -允许应用观察应用状态。 +允许应用监听应用状态。 **权限级别**:system_basic @@ -1112,7 +1124,7 @@ ## ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN -允许应用激活设备管理员应用。 +允许应用激活设备管理应用。 **权限级别**:system_core @@ -1124,7 +1136,7 @@ ## ohos.permission.SET_ENTERPRISE_INFO -允许设备管理员应用设置企业信息。 +允许设备管理应用设置企业信息。 **权限级别**:system_basic @@ -1136,7 +1148,7 @@ ## ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT -允许设备管理员应用订阅管理事件。 +允许设备管理应用订阅管理事件。 **权限级别**:system_basic @@ -1148,7 +1160,7 @@ ## ohos.permission.ENTERPRISE_SET_DATETIME -允许设备管理员应用设置系统时间。 +允许设备管理应用设置系统时间。 **权限级别**:system_basic @@ -1160,7 +1172,7 @@ ## ohos.permission.ENTERPRISE_GET_DEVICE_INFO -允许设备管理员读取设备信息。 +允许设备管理应用读取设备信息。 **权限级别**:system_basic @@ -1172,7 +1184,7 @@ ## ohos.permission.ENTERPRISE_RESET_DEVICE -允许设备管理员恢复设备出厂设置。 +允许设备管理应用恢复设备出厂设置。 **权限级别**:system_basic @@ -1184,7 +1196,7 @@ ## ohos.permission.ENTERPRISE_SET_WIFI -允许设备管理员应用设置和查询WiFi信息。 +允许设备管理应用设置和查询WiFi信息。 **权限级别**:system_basic @@ -1196,7 +1208,7 @@ ## ohos.permission.ENTERPRISE_GET_NETWORK_INFO -允许设备管理员应用查询网络信息。 +允许设备管理应用查询网络信息。 **权限级别**:system_basic @@ -1208,7 +1220,7 @@ ## ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY -允许设备管理员设置账户管理策略。 +允许设备管理应用设置账户管理策略。 **权限级别**:system_basic @@ -1220,7 +1232,7 @@ ## ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY -允许设备管理员设置包安装管理策略。 +允许设备管理应用设置包安装管理策略。 **权限级别**:system_basic @@ -1232,7 +1244,7 @@ ## ohos.permission.ENTERPRISE_SET_NETWORK -允许设备管理员设置网络信息。 +允许设备管理应用设置网络信息。 **权限级别**:system_basic @@ -1244,7 +1256,7 @@ ## ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY -允许设备管理员设置应用运行管理策略。 +允许设备管理应用设置应用运行管理策略。 **权限级别**:system_basic @@ -1256,7 +1268,7 @@ ## ohos.permission.ENTERPRISE_SET_SCREENOFF_TIME -允许设备管理员设置系统休眠时间。 +允许设备管理应用设置系统休眠时间。 **权限级别**:system_basic @@ -1268,7 +1280,7 @@ ## ohos.permission.ENTERPRISE_INSTALL_BUNDLE -允许设备管理员安装和卸载包。 +允许设备管理应用安装和卸载包。 **权限级别**:system_core @@ -1280,7 +1292,7 @@ ## ohos.permission.ENTERPRISE_GET_SETTINGS -允许设备管理员查询“设置”应用数据。 +允许设备管理应用查询“设置”应用数据。 **权限级别**:system_basic @@ -1292,7 +1304,7 @@ ## ohos.permission.ENTERPRISE_MANAGE_CERTIFICATE -允许设备管理员管理证书。 +允许设备管理应用管理证书。 **权限级别**:system_basic @@ -1304,7 +1316,7 @@ ## ohos.permission.ENTERPRISE_RESTRICT_POLICY -允许设备管理员下发和获取限制类策略。 +允许设备管理应用下发和获取限制类策略。 **权限级别**:system_basic @@ -1316,7 +1328,7 @@ ## ohos.permission.ENTERPRISE_MANAGE_USB -允许设备管理员管理USB。 +允许设备管理应用管理USB。 **权限级别**:system_basic @@ -1328,7 +1340,7 @@ ## ohos.permission.ENTERPRISE_MANAGE_NETWORK -允许设备管理员管理网络。 +允许设备管理应用管理网络。 **权限级别**:system_basic @@ -1340,7 +1352,7 @@ ## ohos.permission.ENTERPRISE_SET_BROWSER_POLICY -允许设备设置/取消浏览器策略。 +允许设备管理应用设置/取消浏览器策略。 **权限级别**:system_basic @@ -1644,7 +1656,7 @@ ## ohos.permission.CAMERA -允许应用使用相机拍摄照片和录制视频。 +允许应用使用相机。 **权限级别**:normal @@ -2064,7 +2076,7 @@ ## ohos.permission.ENFORCE_USER_IDM -允许SA无token删除IAM子系统用户信息。 +允许SA无token删除IAM用户信息。 **权限级别**:system_core @@ -2076,7 +2088,7 @@ ## ohos.permission.ACCESS_AUTH_RESPOOL -允许SA注册执行器。 +允许SA注册认证执行器。 **权限级别**:system_core @@ -2316,7 +2328,7 @@ ## ohos.permission.INSTALL_ENTERPRISE_BUNDLE -允许应用安装、卸载其他企业InHouse应用。 +允许应用安装企业InHouse应用。 **权限级别**:system_core @@ -2659,3 +2671,27 @@ **ACL使能**:TRUE **起始版本**:10 + +## ohos.permission.OBSERVE_FORM_RUNNING + +允许应用监听卡片运行状态。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + +**起始版本**:10 + +## ohos.permission.MANAGE_DEVICE_AUTH_CRED + +允许应用调用设备认证华为帐号凭据管理应用接口。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:FALSE + +**起始版本**:10 diff --git a/zh-cn/application-dev/task-management/Readme-CN.md b/zh-cn/application-dev/task-management/Readme-CN.md index 3ea02ae686749eb66dec03e5f4b70f975980883d..25aab2780b19dc7c8e32226c54bc02e00714fdcd 100644 --- a/zh-cn/application-dev/task-management/Readme-CN.md +++ b/zh-cn/application-dev/task-management/Readme-CN.md @@ -1,13 +1,8 @@ # 后台任务(Background Task)管理 -- 后台任务 - - [后台任务概述](background-task-overview.md) - - [短时任务开发指导](transient-task-dev-guide.md) - - [长时任务开发指导](continuous-task-dev-guide.md) - - [延迟任务调度开发指导](work-scheduler-dev-guide.md) - - [延迟任务回调能力开发指导(WorkSchedulerExtensionAbility)](workscheduler-extensionability.md) - - [申请能效资源开发指导](efficiency-resources-apply-dev-guide.md) - -- 后台代理提醒 - - [后台代理提醒概述](reminder-agent-overview.md) - - [后台代理提醒开发指导](reminder-agent-development.md) +- [后台任务总体概述](background-task-overview.md) +- [短时任务](transient-task.md) +- [长时任务](continuous-task.md) +- [延迟任务](work-scheduler.md) +- [代理提醒](agent-powered-reminder.md) +- [能效资源申请(仅对系统特权应用开放)](efficiency-resource-request.md) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/reminder-agent-development.md b/zh-cn/application-dev/task-management/agent-powered-reminder.md similarity index 55% rename from zh-cn/application-dev/task-management/reminder-agent-development.md rename to zh-cn/application-dev/task-management/agent-powered-reminder.md index 3b4d643ac42657c7b092c0ce47b9ff23da14d4bd..5763f56f078e99480512617a4b19e09c90b1966d 100644 --- a/zh-cn/application-dev/task-management/reminder-agent-development.md +++ b/zh-cn/application-dev/task-management/agent-powered-reminder.md @@ -1,41 +1,59 @@ -# 后台代理提醒开发指导 +# 代理提醒 +## 概述 -## 接口说明 +### 功能介绍 + +应用退到后台或进程终止后,仍然有一些提醒用户的定时类任务,例如购物类应用抢购提醒等,为满足此类功能场景,系统提供了代理提醒(reminderAgentManager)的能力。当应用退至后台或进程终止后,系统会代理应用做相应的提醒。当前支持的提醒类型包括:倒计时、日历和闹钟。 + +- 倒计时类:基于倒计时的提醒功能。 + +- 日历类:基于日历的提醒功能。 + +- 闹钟类:基于时钟的提醒功能。 + +### 约束与限制 + +- **个数限制**:一个三方应用支持最多30个有效提醒(有效即发布成功),一个系统应用支持最多10000个有效提醒,整个系统最多支持12000个有效提醒。 -后台代理提醒功能主要提供后台提醒通知发布接口,开发者可调用这些接口创建定时提醒,包括倒计时、日历、闹钟三种提醒类型。[reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md)封装了发布、取消提醒通知的方法。 +- **跳转限制**:点击提醒通知后跳转的应用必须是申请代理提醒的本应用。 - **表1** reminderAgentManager主要接口 -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------------------- | -| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | 发布一个定时提醒类通知。
- 单个应用有效的提醒个数最多支持30个(不包括已经超时,即后续不会再提醒的提醒实例)。
- 整个系统有效的提醒个数最多支持2000个(不包括已经超时,即后续不会再提醒的提醒实例)。 | -| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | 取消一个指定的提醒类通知(reminderId从publishReminder的返回值获取)。 | -| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | 获取当前应用设置的所有有效的提醒。 | -| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | 取消当前应用设置的所有提醒。 | -| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | 注册一个提醒类需要使用的NotificationSlot。 | -| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | 删除指定类型的NotificationSlot。 | +## 接口说明 + +**表1** 主要接口 + +以下是代理提醒的相关接口,下表均以Promise形式为例,更多接口及使用方式请见后台代理提醒文档。 +| 接口名 | 描述 | +| -------- | -------- | +| publishReminder(reminderReq: ReminderRequest): Promise<number> | 发布一个定时提醒类通知 | +| cancelReminder(reminderId: number): Promise<void> | 取消一个指定的提醒类通知 | +| getValidReminders(): Promise<Array<ReminderRequest>> | 获取当前应用设置的所有有效的提醒 | +| cancelAllReminders(): Promise<void> | 取消当前应用设置的所有提醒 | +| addNotificationSlot(slot: NotificationSlot): Promise<void> | 注册一个提醒类需要使用的通知通道(NotificationSlot) | +| removeNotificationSlot(slotType: notification.SlotType): Promise<void> | 删除指定的通知通道(NotificationSlot) | ## 开发步骤 -1. 需要申请`ohos.permission.PUBLISH_AGENT_REMINDER`权限,配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 +1. 申请ohos.permission.PUBLISH_AGENT_REMINDER权限,配置方式请参阅[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 -2. [使能通知开关](../notification/notification-enable.md),获得用户授权后,才能使用代理提醒功能。 +2. [使能通知开关](../notification/notification-enable.md)。获得用户授权后,才能使用代理提醒功能。 3. 导入模块。 - + ```js import reminderAgentManager from '@ohos.reminderAgentManager'; import notificationManager from '@ohos.notificationManager'; ``` 4. 定义目标提醒代理。开发者根据实际需要,选择定义如下类型的提醒。 - - 定义倒计时实例。 + - 定义倒计时实例。 + ```js let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // 提醒类型为倒计时类型 + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // 提醒类型为倒计时类型 triggerTimeInSeconds: 10, actionButton: [ // 设置弹出的提醒通知信息上显示的按钮类型和标题 { @@ -43,11 +61,11 @@ type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE } ], - wantAgent: { // 点击提醒通知后跳转的目标UIAbility信息 + wantAgent: { // 点击提醒通知后跳转的目标UIAbility信息 pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' }, - maxScreenWantAgent: { // 全屏显示提醒到达时自动拉起的目标Ability信息 + maxScreenWantAgent: { // 全屏显示提醒到达时自动拉起的目标UIAbility信息 pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' }, @@ -58,15 +76,16 @@ slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // 指明提醒的Slot类型 } ``` - - 定义日历实例。 + - 定义日历实例。 + ```js let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // 提醒类型为日历类型 - dateTime: { // 指明提醒的目标时间 + dateTime: { // 指明提醒的目标时间 year: 2023, - month: 7, - day: 30, + month: 1, + day: 1, hour: 11, minute: 14, second: 30 @@ -87,13 +106,13 @@ pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' }, - maxScreenWantAgent: { // 点击提醒通知后跳转的目标UIAbility信息 + maxScreenWantAgent: { // 全屏显示提醒到达时自动拉起的目标UIAbility信息 pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' }, ringDuration: 5, // 指明响铃时长(单位:秒) snoozeTimes: 2, // 指明延迟提醒次数 - timeInterval: 300, // 执行延迟提醒间隔(单位:秒) + timeInterval: 5, // 执行延迟提醒间隔(单位:秒) title: 'this is title', // 指明提醒标题 content: 'this is content', // 指明提醒内容 expiredContent: 'this reminder has expired', // 指明提醒过期后需要显示的内容 @@ -102,8 +121,9 @@ slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // 指明提醒的Slot类型 } ``` - - 定义闹钟实例。 + - 定义闹钟实例。 + ```js let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // 提醒类型为闹钟类型 @@ -124,13 +144,13 @@ pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' }, - maxScreenWantAgent: { // 点击提醒通知后跳转的目标UIAbility信息 + maxScreenWantAgent: { // 全屏显示提醒到达时自动拉起的目标UIAbility信息 pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' }, ringDuration: 5, // 指明响铃时长(单位:秒) snoozeTimes: 2, // 指明延迟提醒次数 - timeInterval: 300, // 执行延迟提醒间隔(单位:秒) + timeInterval: 5, // 执行延迟提醒间隔(单位:秒) title: 'this is title', // 指明提醒标题 content: 'this is content', // 指明提醒内容 expiredContent: 'this reminder has expired', // 指明提醒过期后需要显示的内容 @@ -141,43 +161,37 @@ ``` 5. 发布相应的提醒代理。代理发布后,应用即可使用后台代理提醒功能。 - + ```js try { reminderAgentManager.publishReminder(targetReminderAgent).then(res => { - console.info('publishReminder promise reminderId: ' + res); - let reminderId: number = res; - // ... + console.info('Succeeded in publishing reminder. '); + let reminderId: number = res; // 发布的提醒ID }).catch(err => { - console.info('publishReminder err code: ' + err.code + ' message:' + err.message); + console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`); }) - } catch (error) { - console.info('publishReminder code: ' + error.code + ' message:' + error.message); + } catch (err) { + console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`); } ``` - 以闹钟为例,运行效果如下图所示。 - - ![zh-cn_image_0000001416585578](figures/zh-cn_image_0000001416585578.png) - -6. 若需要删除提醒任务,可以通过调用[reminderAgentManager.cancelReminder()](../reference/apis/js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder)方法来实现。 - - ```js - let reminderId = 0; // reminderId的值从发布提醒代理成功之后的回调中获得 +6. 根据需要删除提醒任务。 + ```js try { + // reminderId的值从发布提醒代理成功之后的回调中获得 reminderAgentManager.cancelReminder(reminderId).then(() => { - console.log("cancelReminder promise"); + console.log('Succeeded in canceling reminder.'); }).catch(err => { - console.log("promise err code: " + err.code + ", message:" + err.message); + console.error(`Failed to cancel reminder. Code: ${err.code}, message: ${err.message}`); }); - } catch (error) { - console.log("cancelReminder code: " + error.code + ", message: " + error.message); - }; + } catch (err) { + console.error(`Failed to cancel reminder. Code: ${err.code}, message: ${err.message}`); + } ``` ## 相关实例 -基于后台代理提醒的开发,有以下相关实例可供参考: +基于代理提醒,有以下相关实例可供参考: -- [闹钟(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) +- [闹钟(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/background-task-overview.md b/zh-cn/application-dev/task-management/background-task-overview.md index 4eefd27e3e836c51a38fd8a4deb696d9d0f4d889..459c6798460df1881c69c40a3f799c5d20898b76 100644 --- a/zh-cn/application-dev/task-management/background-task-overview.md +++ b/zh-cn/application-dev/task-management/background-task-overview.md @@ -1,138 +1,40 @@ -# 后台任务概述 +# 后台任务总体概述 -后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。 -针对应用或业务模块处于后台(无可见界面)时,有需要继续执行或者后续执行的业务,可基于业务类型,申请[短时任务](#短时任务)延迟挂起或者[长时任务](#长时任务)避免进入挂起状态;使用[延迟调度任务](#延迟任务),执行对实时性要求不高的任务;同时针对特权应用,如果需要更加灵活的配置,可以申请[能效资源](#申请能效资源)。 - **资源使用约束** :对于运行的业务,系统会给予一定的资源配额约束,包括进程在连续一段时间内内存的使用、CPU使用占比,以及24小时磁盘写的IO量,均有对应的配额上限。超过配额上限时,如果进程处于前台,系统会有对应的warning日志,如果进程处于后台,系统会查询并终止该进程。 +## 功能介绍 +设备返回主界面、锁屏、应用切换等操作会使应用退至后台。应用退至后台后,如果继续活动,可能会造成设备耗电快、用户界面卡顿等现象。为了降低设备耗电速度、保障用户使用流畅度,系统会对退至后台的应用进行管控,包括进程挂起(即系统不再为应用进程分配CPU资源,同时对应的[公共事件](../application-models/common-event-overview.md)等不再发给应用进程)和进程终止。 -## 后台任务类型 - -OpenHarmony将后台任务分为四种类型,并提供了一个资源申请的扩展功能: - - **无后台业务** :应用或业务模块退到后台后,无任务需要处理。 - - **短时任务** :应用或业务模块退到后台后,如果有紧急不可推迟且短时间能完成的任务,如应用退后台要进行数据压缩,不可中断,则使用短时任务申请延迟进入挂起(Suspend)状态。 - - **长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 - - **延迟任务** :延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性不高的任务。当满足设定条件的时候,任务会被放入待调度队列,当系统空闲时调度该任务。 - - **能效资源** :能效资源包括CPU资源、WORK_SCHEDULER资源、软件资源(COMMON_EVENT, TIMER)、硬件资源(GPS, BLUETOOTH)。如果应用或者进程申请了能效资源,那么根据能效资源的类型会拥有相应的特权,例如申请了CPU资源的可以不被挂起,申请了WORK_SCHEDULER后延时任务可以拥有更长的执行时间。 - -## 最佳后台任务选择 - -![后台任务选择](figures/bgtask_choice.png) - -## 短时任务 - -退到后台的应用有不可中断且短时间能完成的任务时,可以使用短时任务机制。该机制允许应用在后台短时间内完成任务,保障应用业务运行不受后台生命周期管理的影响。 - -> **说明:** -> -> 短时任务仅针对应用的临时任务提供资源使用生命周期保障,限制单次最大使用时长为3分钟,全天使用配额默认为10分钟(具体时长系统根据应用场景和系统状态智能调整)。 - - -### 短时任务使用约束 - -短时任务的使用需要遵从如下约束和规则: - -- **申请时机**:允许应用在前台时,或退后台在被挂起之前(应用退到后台默认有6~12秒的运行时长,具体时长由系统根据具体场景决定)申请延迟挂起,否则可能被挂起(Suspend),导致申请失败。 - -- **超时**:延迟挂起即将超时(Timeout),系统通过回调知会应用,应用需要取消对应的延迟挂起。如果超时不取消,该应用会被强制终止。 +- 应用退至后台一小段时间(由系统定义),应用进程会被挂起。 -- **取消时机**:任务完成后,应用应主动取消延迟挂起,不要等到系统回调后再取消,否则会影响该应用的后台允许运行时长配额。 +- 应用退至后台,在后台被访问一小段时间(由系统定义)后,应用进程会被挂起。 -- **配额机制**:为了防止应用滥用保活,或者申请后不取消,每个应用每天都会有一定配额(会根据用户的使用习惯动态调整),其中单日配额默认为10分钟,单次配额最大为3分钟。配额消耗完就不再允许申请短时任务,所以应用完成短时任务后应立刻取消延迟挂起,避免消耗配额。(注:该配额指的是申请的时长,系统默认应用在后台运行的时间不计算在内)。 +- 资源不足时,系统会终止部分应用进程(即回收该进程的所有资源)。 -## 长时任务 +同时,为了保障后台音乐播放、日历提醒等功能的正常使用,系统提供了规范内受约束的后台任务,扩展应用在后台运行时间。 -长时任务给用户能够直观感受到的且需要一直在后台运行的业务提供后台运行生命周期的保障。比如:业务需要在后台播放声音、需要在后台持续导航定位等。此类用户可以直观感知到的后台业务行为,可以通过使用长时任务对应的后台模式保障业务在后台的运行,支撑应用完成在后台的业务。 - -### 后台模式分类 - -OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业务使用,具体的后台模式类型如下: - -**表1** 长时任务种类 - -| 后台模式 | 说明 | 通知栏显示提示 | 备注 | -| --------------------- | ------------------------- | ------------ | ------------------------- | -| dataTransfer | 通过网络/对端设备进行数据下载、备份、分享、传输等 | 正在运行数据传输任务 | - | -| audioPlayback | 音频输出 | 正在运行音频播放任务 | - | -| audioRecording | 音频输入 | 正在运行录音任务 | - | -| location | 定位、导航 | 正在运行定位任务 | - | -| bluetoothInteraction | 蓝牙传输 | 正在运行蓝牙相关任务 | - | -| multiDeviceConnection | 应用跨设备多端协同 | 正在运行分布式任务 | - | -| wifiInteraction | WLAN传输 | 正在运行WLAN相关任务 | System API,仅对System权限应用开放 | -| voip | 音视频电话、VOIP | 正在运行通话相关任务 | System API,仅对System权限应用开放 | -| taskKeeping | 计算任务 | 正在运行计算任务 | 仅在特定设备生效 | - -### 长时任务使用约束 - -- 如果用户选择可感知业务(如播音、导航等),触发对应后台模式,在任务启动时,系统会强制弹出通知提醒用户。 -- 如果任务结束,应用应主动退出后台模式。若在后台运行期间,系统检测到应用并未使用对应后台模式的资源,则会被挂起(Suspend)。 -- 避免不合理地申请后台长时任务,长时任务类型要与应用的业务类型匹配。如果执行的任务和申请的类型不匹配,也会被系统检测到并被挂起(Suspend)。 -- 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 -- 一个Ability同一时刻只能申请运行一个长时任务。如果同一时刻需要申请多个长时任务,需要创建多个Ability,每个Ability申请一个长时任务。 - -## 延迟任务 - -延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性要求不高的任务,比如设备空闲时候做一次数据学习等场景。当应用申请延迟任务的时候,任务会被放入待调度队列,系统会根据当前状态,如内存、功耗、温度等统一决策最优的调度时机。同时支持任务的持久化,应用退出或者设备重启,设置的任务同样能够被触发。 - -### 延迟任务调度约束 - -延迟调度任务的使用需要遵从如下约束和规则: - -- **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。默认的超时限制为2分钟,对于系统应用,可以通过[申请能效资源](efficiency-resources-apply-dev-guide.md)获取更长的执行时间(充电状态20分钟,非充电状态10分钟)。 -- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。对于通过能效资源接口申请了WORK_SCHEDULER资源的应用,在资源的有效期内,它的延迟任务执行频率不受限制。 - - | 应用分组 | 延迟任务执行频率约束 | - | ---------------------------------------- | ---------- | - | 活跃 | 最小间隔2小时 | - | 每日使用 | 最小间隔4小时 | - | 经常使用 | 最小间隔24小时 | - | 不经常使用 | 最小间隔48小时 | - | 受限分组 | 禁止 | - | 未使用分组 | 禁止 | - | [能效资源豁免分组](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#resourcetype) | 执行频率不受限制 | - -- **WorkInfo设置参数约束** - - - workId、bundleName、abilityName为必填项,bundleName必须填本应用,否则校验失败。 - - - 至少要设置一个满足的条件。 +## 后台任务类型 - - 重复任务时间间隔至少20分钟,当设置重复任务时间间隔时,必须设置始终重复和重复次数中的一个。 +OpenHarmony标准系统支持规范内受约束的后台任务,包括短时任务、长时任务、延迟任务、代理提醒和能效资源。 - - 携带参数信息支持number、string、bool三种类型。 +开发者可以根据如下的功能介绍,选择合适的后台任务,以满足应用退至后台后继续运行的需求。 -## 申请能效资源 +- **短时任务**:适用于实时性要求高、耗时不长的任务,例如状态保存。 -供系统应用使用的能效资源可以分为两类:软件资源(WORK_SCHEDULER, COMMON_EVENT, TIMER),硬件资源(CPU, GPS, BLUETOOTH, AUDIO)。 +- **长时任务**:适用于长时间运行在后台、用户可感知的任务,例如后台播放音乐、导航、设备连接等,使用长时任务避免应用进程被挂起。 -应用申请不同的能效资源后可以执行相应的操作: - * 申请CPU资源后可以不被挂起,直到任务完成。 - * 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加。 - * 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件。 - * 申请TIMER资源后,应用能够使用定时器执行精确定时任务。 - * 申请资源(GPS, BLUETOOTH, AUDIO)后,应用在后台被挂起后,依然能够被管理相关硬件的服务唤醒,执行相应的任务。 +- **延迟任务**:对于实时性要求不高、可延迟执行的任务,系统提供了延迟任务,即满足条件的应用退至后台后被放入执行队列,系统会根据内存、功耗等统一调度。 +- **代理提醒**:代理提醒是指应用退后台或进程终止后,系统会代理应用做相应的提醒。适用于定时提醒类业务,当前支持的提醒类型包括倒计时、日历和闹钟三类。 -**表2** 能效资源种类 +同时,对于提供基础能力的系统应用,系统单独提供[能效资源申请](efficiency-resource-request.md)接口。应用调用能效资源接口后,系统对应用进行一定的管控豁免。 -| 参数名 | 参数值 | 描述 | -| -------------- | ---- | ------------------- | -| CPU | 1 | CPU资源,申请后不被挂起 | -| COMMON_EVENT | 2 | 公共事件,申请后挂起状态下不被代理掉 | -| TIMER | 4 | 计时器,申请后挂起状态下不被代理掉 | -| WORK_SCHEDULER | 8 | 延迟任务,申请后有更长的执行时间 | -| BLUETOOTH | 16 | 蓝牙相关,申请后挂起状态下不被代理掉 | -| GPS | 32 | GPS相关,申请后挂起状态下不被代理掉 | -| AUDIO | 64 | 音频资源,申请后挂起状态下不被代理掉 | + **图1** 后台任务类型选择   +![bgtask_choice](figures/bgtask_choice.png) -### 能效资源使用约束 -- 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。 -- 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。 -- WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。 -- 需要使用能效资源的应用必须是系统应用,同时需要向应用中心提出申请,配置相应的特权。 +> **说明:** +> +> 1. 系统仅支持规范内受约束的后台任务。应用退至后台后,若未使用规范内的后台任务或选择的后台任务类型不正确,对应的应用进程会被挂起或终止。 +> +> 2. 应用申请了规范内的后台任务,仅会提升应用进程被回收的优先级。当系统资源严重不足时,即使应用进程申请了规范内的后台任务,系统仍会终止部分进程,用以保障系统稳定性。 \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md deleted file mode 100644 index a52def2cb9ee79c8341d274d92d6f466b792735b..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md +++ /dev/null @@ -1,441 +0,0 @@ -# 长时任务开发指导 - -## 场景说明 - -如果应用需要在后台长时间执行用户可感知的任务,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 -长时任务在后台执行没有时间限制。为了避免该机制被滥用,系统只允许申请有限个数的长时任务类型,同时会有相应的通知提示与长时任务相关联,使用户可感知,并且系统会添加相应的校验机制,确保应用是的确在执行相应的长时任务。 - -## 接口说明 - -**表1** 长时任务主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------- | -| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> | 服务启动后,向系统申请长时任务,使服务一直保持后台运行。 | -| stopBackgroundRunning(context: Context): Promise<void> | 停止后台长时任务的运行。 | - - -其中,wantAgent的信息详见([WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)) - -**表2** 后台模式类型 - -| 参数名 | 描述 | 配置项 | -| ----------------------- | -------------- | --------------------- | -| DATA_TRANSFER | 数据传输 | dataTransfer | -| AUDIO_PLAYBACK | 音频播放 | audioPlayback | -| AUDIO_RECORDING | 录音 | audioRecording | -| LOCATION | 定位导航 | location | -| BLUETOOTH_INTERACTION | 蓝牙相关 | bluetoothInteraction | -| MULTI_DEVICE_CONNECTION | 多设备互联 | multiDeviceConnection | -| WIFI_INTERACTION | WLAN相关(系统保留) | wifiInteraction | -| VOIP | 音视频通话(系统保留) | voip | -| TASK_KEEPING | 计算任务(仅供特定设备使用) | taskKeeping | - - -## 开发步骤 - -### 基于Stage模型 - -Stage模型的相关信息参考[Stage模型开发概述](../application-models/stage-model-development-overview.md)。 - -1、在module.json5文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING、同时为需要使用长时任务的ability声明相应的后台模式类型。 - -``` -"module": { - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // 后台模式类型 - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 - } - ] -} -``` - -2、在应用内执行长时任务时,由于元能力启动管控规则限制,不支持同应用通过startAbilityByCall的形式在后台创建并运行Ability。可以直接在page中,执行相应的代码。Stage模型的Ability使用参考[Stage模型开发指导-UIAbility组件](../application-models/uiability-overview.md)。 - -```ts -import wantAgent from '@ohos.app.ability.wantAgent'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -@Entry -@Component -struct Index { - @State message: string = 'test' - // 通过getContext方法,来获取page所在的Ability上下文。 - private context: any = getContext(this) - - startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } - } - - stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - } - - build() { - Row() { - Column() { - Text("Index") - .fontSize(50) - .fontWeight(FontWeight.Bold) - - Button() { Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // 通过按钮申请长时任务 - this.startContinuousTask(); - - // 此处执行具体的长时任务逻辑,如放音等。 - }) - - Button() { Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // 此处结束具体的长时任务的执行 - - // 通过按钮取消长时任务 - this.stopContinuousTask(); - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -3、当需要跨设备或者跨应用在后台执行长时任务时,可以通过Call的方式在后台创建并运行Ability。使用方式参考[Call调用开发指南(同设备)](../application-models/uiability-intra-device-interaction.md#通过call调用实现uiability交互仅对系统应用开放),[Call调用开发指南(跨设备)](../application-models/hop-multi-device-collaboration.md#通过跨设备call调用实现多端协同)。 - -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -const MSG_SEND_METHOD: string = 'CallSendMsg'; - -let mContext = null; - -function startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(mContext, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((error) => { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((error) => { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -class MyParcelable { - num: number = 0; - str: String = ""; - - constructor(num, string) { - this.num = num; - this.str = string; - } - - marshalling(messageSequence) { - messageSequence.writeInt(this.num); - messageSequence.writeString(this.str); - return true; - } - - unmarshalling(messageSequence) { - this.num = messageSequence.readInt(); - this.str = messageSequence.readString(); - return true; - } -} - -function sendMsgCallback(data) { - console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new MyParcelable(0, "") - data.readParcelable(receivedData) - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) - // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 - if (receivedData.str === 'start_bgtask') { - startContinuousTask() - } else if (receivedData.str === 'stop_bgtask') { - stopContinuousTask(); - } - return new MyParcelable(10, "Callee test"); -} - -export default class BgTaskAbility extends UIAbility { - onCreate(want, launchParam) { - console.info("[Demo] BgTaskAbility onCreate") - this.callee.on("test", sendMsgCallback); - - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - mContext = this.context; - } - - onDestroy() { - console.info("[Demo] BgTaskAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - console.info("[Demo] BgTaskAbility onWindowStageCreate") - - windowStage.loadContent("pages/index").then((data)=> { - console.info(`load content succeed with data ${JSON.stringify(data)}`) - }).catch((error)=>{ - console.error(`load content failed with error ${JSON.stringify(error)}`) - }) - } - - onWindowStageDestroy() { - console.info("[Demo] BgTaskAbility onWindowStageDestroy") - } - - onForeground() { - console.info("[Demo] BgTaskAbility onForeground") - } - - onBackground() { - console.info("[Demo] BgTaskAbility onBackground") - } -}; -``` - -### 基于FA模型 - -基于FA的Service Ability使用,参考[ServiceAbility开发指导](../application-models/serviceability-overview.md)。 - -当不需要与后台执行的长时任务交互时,可以采用startAbility()方法启动Service Ability。并在Service Ability的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。当任务执行完,再调用长时任务取消接口,及时释放资源。 - -当需要与后台执行的长时任务交互时(如播放音乐等)。可以采用connectAbility()方法启动并连接Service Ability。在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 - -1、在config.json文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING、同时为需要使用长时任务的Service Ability声明相应的后台模式类型。 - -```json -"module": { - "package": "com.example.myapplication", - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // 后台模式类型 - "type": "service" // ability类型为service - } - ], - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 - } - ] -} -``` - -2、在Service Ability调用长时任务的申请和取消接口。 - -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; -import rpc from "@ohos.rpc"; - -function startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - try { - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); - } catch (error) { - console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); - } -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -async function processAsyncJobs() { - // 此处执行具体的长时任务。 - - // 长时任务执行完,调用取消接口,释放资源。 - stopContinuousTask(); -} - -let mMyStub; - -class MyStub extends rpc.RemoteObject { - constructor(des) { - if (typeof des === 'string') { - super(des); - } else { - return null; - } - } - onRemoteRequest(code, data, reply, option) { - console.log('ServiceAbility onRemoteRequest called'); - // code 的具体含义用户自定义 - if (code === 1) { - // 接收到申请长时任务的请求码 - startContinuousTask(); - // 此处执行具体长时任务 - } else if (code === 2) { - // 接收到取消长时任务的请求码 - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } -} - -export default { - onStart() { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // 在执行后台长时任前,调用申请接口。 - startContinuousTask(); - processAsyncJobs(); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.info('ServiceAbility onConnect'); - return mMyStub; - }, - onReconnect(want) { - console.info('ServiceAbility onReconnect'); - }, - onDisconnect() { - console.info('ServiceAbility onDisconnect'); - }, - onCommand(want, startId) { - console.info('ServiceAbility onCommand'); - } -}; -``` - -## 相关实例 - -基于后台任务管理,有以下相关实例可供参考: - -- [`ContinuousTask`:长时任务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/ContinuousTask) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/continuous-task.md b/zh-cn/application-dev/task-management/continuous-task.md new file mode 100644 index 0000000000000000000000000000000000000000..77eb0c6f3975b9881f134ac758a9cb959b3033ca --- /dev/null +++ b/zh-cn/application-dev/task-management/continuous-task.md @@ -0,0 +1,478 @@ +# 长时任务 + + +## 概述 + + +### 功能介绍 + +应用退至后台后,在后台需要长时间运行用户可感知的任务,如播放音乐、导航等。为防止应用进程被挂起,导致对应功能异常,可以申请长时任务,使应用在后台长时间运行。 +申请长时任务后,系统会做相应的校验,确保应用在执行相应的长时任务。同时,系统有与长时任务相关联的通知栏消息,用户删除通知栏消息时,系统会自动停止长时任务。 + + +### 使用场景 + +下表给出了当前长时任务支持的类型,包含数据传输、音频播放、录音、定位导航、蓝牙相关、多设备互联、WLAN相关、音视频通话和计算任务。可以参考下表中的场景举例,选择合适的长时任务类型。 + +**表1** 长时任务类型 +| 参数名 | 描述 | 场景举例 | +| -------- | -------- | -------- | +| DATA_TRANSFER | 数据传输 | 后台下载大文件,如浏览器后台下载等。 | +| AUDIO_PLAYBACK | 音频播放 | 音乐类应用在后台播放音乐。 | +| AUDIO_RECORDING | 录音 | 录音机在后台录音。 | +| LOCATION | 定位导航 | 导航类应用后台导航。 | +| BLUETOOTH_INTERACTION | 蓝牙相关 | 通过蓝牙传输分享的文件。 | +| MULTI_DEVICE_CONNECTION | 多设备互联 | 分布式业务连接。 | +| WIFI_INTERACTION | WLAN相关(仅对系统应用开放) | 通过WLAN传输分享的文件。 | +| VOIP | 音视频通话(仅对系统应用开放) | 系统聊天类应用后台音频电话。 | +| TASK_KEEPING | 计算任务(仅对特定设备开放) | 杀毒软件 | + + +- 申请了DATA_TRANSFER(数据传输)的长时任务,系统仅会提升应用进程的优先级,降低系统终止应用进程的概率,但仍然会挂起对应的应用进程。对于上传下载对应的功能,需要调用系统[上传下载代理接口](../reference/apis/js-apis-request.md)托管给系统执行。 +- 申请了AUDIO_PLAYBACK(音频播放)的长时任务,要实现后台播放的功能,需要同时申请[媒体会话](../media/avsession-overview.md)。 + + +### 约束与限制 + +- **申请限制**:Stage模型中,长时任务仅支持UIAbility申请;FA模型中,长时任务仅支持ServiceAbility申请。 + +- **数量限制**:一个UIAbility(FA模型则为ServiceAbility)同一时刻仅支持申请一个长时任务,即在一个长时任务结束后才可能继续申请。如果一个应用同时需要申请多个长时任务,需要创建多个UIAbility;一个应用的一个UIAbility申请长时任务后,整个应用下的所有进程均不会被挂起。 + +- **运行限制**:系统会进行长时任务校验。若应用申请了长时任务,但未真正执行申请类型的长时任务或申请类型的任务已结束,系统会对应用进行管控。例如系统检测到应用申请了AUDIO_PLAYBACK(音频播放),但实际未播放音乐,系统则会终止对应的进程。 + +> **说明:** +> +> 应用按需求申请长时任务,当应用无需在后台运行(任务结束)时,要及时主动取消长时任务,否则系统会强行取消。例如用户点击音乐暂停播放时,应用需及时取消对应的长时任务;用户再次点击音乐播放时,需重新申请长时任务。 + +## 接口说明 + +**表2** 主要接口 + +以下是长时任务开发使用的相关接口,下表均以Promise形式为例,更多接口及使用方式请见[后台任务管理](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)。 + +| 接口名 | 描述 | +| -------- | -------- | +| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)): Promise<void> | 申请长时任务 | +| stopBackgroundRunning(context: Context): Promise<void> | 取消长时任务 | + +## 开发步骤 + +### Stage模型 + +1. 需要申请ohos.permission.KEEP_BACKGROUND_RUNNING权限,配置方式请参见[配置文件声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 + +2. 声明后台模式类型。 + 在module.json5配置文件中为需要使用长时任务的UIAbility声明相应的长时任务类型。 + + + ```ts + "module": { + "abilities": [ + { + "backgroundModes": [ + "audioRecording" + ], // 后台模式类型 + } + ], + ... + } + ``` + +3. 导入模块。 + + ```ts + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import wantAgent from '@ohos.app.ability.wantAgent'; + ``` + +4. 申请和取消长时任务。 + + - 在Stage模型中,长时任务支持设备本应用申请,也支持跨设备或跨应用申请。 + + - 跨设备或者跨应用在后台执行长时任务时,可以通过Call的方式在后台创建并运行UIAbility,具体使用请参考[Call调用开发指南(同设备)](../application-models/uiability-intra-device-interaction.md#通过call调用实现uiability交互仅对系统应用开放)和[Call调用开发指南(跨设备)](../application-models/hop-multi-device-collaboration.md#通过跨设备call调用实现多端协同)。 + + **设备本应用**申请长时任务示例代码如下: + + ```ts + @Entry + @Component + struct Index { + @State message: string = 'ContinuousTask'; + // 通过getContext方法,来获取page所在的UIAbility上下文。 + private context = getContext(this); + + startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块下getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } catch (error) { + console.error(`Failed to start background running. Code is ${error.code} message is ${error.message}`); + } + }); + } + + stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } catch (error) { + console.error(`Failed to stop background running. Code is ${error.code} message is ${error.message}`); + } + } + + build() { + Row() { + Column() { + Text("Index") + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button() { + Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .margin({ top: 10 }) + .backgroundColor('#0D9FFB') + .width(250) + .height(40) + .onClick(() => { + // 通过按钮申请长时任务 + this.startContinuousTask(); + + // 此处执行具体的长时任务逻辑,如放音等。 + }) + + Button() { + Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .margin({ top: 10 }) + .backgroundColor('#0D9FFB') + .width(250) + .height(40) + .onClick(() => { + // 此处结束具体的长时任务的执行 + + // 通过按钮取消长时任务 + this.stopContinuousTask(); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + + **跨设备或跨应用**申请长时任务示例代码如下: + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + const MSG_SEND_METHOD: string = 'CallSendMsg' + + let mContext = null; + + function startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + } + }); + } + + function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + } + } + + class MyParcelable { + num: number = 0; + str: String = ''; + + constructor(num, string) { + this.num = num; + this.str = string; + } + + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + + function sendMsgCallback(data) { + console.info('BgTaskAbility funcCallBack is called ' + data) + let receivedData = new MyParcelable(0, '') + data.readParcelable(receivedData) + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 + if (receivedData.str === 'start_bgtask') { + startContinuousTask() + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new MyParcelable(10, 'Callee test'); + } + + export default class BgTaskAbility extends UIAbility { + onCreate(want, launchParam) { + console.info("[Demo] BgTaskAbility onCreate") + this.callee.on('test', sendMsgCallback); + + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + mContext = this.context; + } + + onDestroy() { + console.info('[Demo] BgTaskAbility onDestroy') + } + + onWindowStageCreate(windowStage) { + console.info('[Demo] BgTaskAbility onWindowStageCreate') + + windowStage.loadContent("pages/index").then((data) => { + console.info(`load content succeed with data ${JSON.stringify(data)}`) + }).catch((error) => { + console.error(`load content failed with error ${JSON.stringify(error)}`) + }) + } + + onWindowStageDestroy() { + console.info('[Demo] BgTaskAbility onWindowStageDestroy') + } + + onForeground() { + console.info('[Demo] BgTaskAbility onForeground') + } + + onBackground() { + console.info('[Demo] BgTaskAbility onBackground') + } + }; + ``` + + +### FA模型中 + +1. 启动并连接ServiceAbility。 + + - 不需要与用户进行交互时,采用startAbility()方法启动ServiceAbility(具体使用请参考[ServiceAbility组件](../application-models/serviceability-overview.md),并在ServiceAbility的onStart回调方法中,调用长时任务的申请和取消接口。 + + - 需要与用户进行交互时(如播放音乐),采用connectAbility()方法启动并连接ServiceAbility(具体使用请参考[ServiceAbility组件](../application-models/serviceability-overview.md),在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 + +2. 配置权限和声明后台模式类型。 + + 在config.json文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING,配置方式请参见[配置文件声明](../security/accesstoken-guidelines.md#配置文件权限声明)。同时,为需要使用长时任务的ServiceAbility声明相应的长时任务类型。 + + + ```js + "module": { + "package": "com.example.myapplication", + "abilities": [ + { + "backgroundModes": [ + "audioRecording", + ], // 后台模式类型 + "type": "service" // ability类型为service + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 + } + ] + } + ``` + +3. 导入模块。 + + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent from '@ohos.app.ability.wantAgent'; + import rpc from "@ohos.rpc"; + ``` + +4. 申请和取消长时任务。在 ServiceAbility 中,调用 startBackgroundRunning() 接口和 startBackgroundRunning() 接口实现长时任务的申请和取消。 + + ```js + function startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } catch (error) { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + } + }); + } + + function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } catch (error) { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + } + } + + async function processAsyncJobs() { + // 此处执行具体的长时任务。 + + // 长时任务执行完,调用取消接口,释放资源。 + stopContinuousTask(); + } + + let mMyStub; + + class MyStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + console.log('ServiceAbility onRemoteRequest called'); + // code 的具体含义用户自定义 + if (code === 1) { + // 接收到申请长时任务的请求码 + startContinuousTask(); + // 此处执行具体长时任务 + } else if (code === 2) { + // 接收到取消长时任务的请求码 + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } + } + + export default { + onStart(want) { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // 在执行长时任务前,调用申请接口。 + startContinuousTask(); + processAsyncJobs(); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return mMyStub; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, restart, startId) { + console.info('ServiceAbility onCommand'); + } + }; + ``` + + +## 相关实例 + +针对长时任务开发,有以下相关实例可供参考: + +- [ContinuousTask:长时任务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/ContinuousTask) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/efficiency-resource-request.md b/zh-cn/application-dev/task-management/efficiency-resource-request.md new file mode 100644 index 0000000000000000000000000000000000000000..9792d934187d8f41aef0b8dca0d4f735e2cdbd77 --- /dev/null +++ b/zh-cn/application-dev/task-management/efficiency-resource-request.md @@ -0,0 +1,111 @@ +# 能效资源申请(仅对系统特权应用开放) + +## 概述 + +### 功能介绍 + +部分系统基础应用对外提供或者维持系统基本功能,需要长时间运行,如系统为了维持和服务器的连接,需要有一个默认长连接推送服务的应用每隔一小段时间给服务器发送心跳包,为了避免该应用进程被挂起,可以申请能效资源来保障业务的执行。 + +### 基本概念 + +- **能效资源申请接口** :单独为进程申请CPU等资源的接口,保障系统应用在后台执行的诉求。申请CPU资源后,则应用或进程不被挂起。 + +- **系统特权应用**:配置[runningResourcesApply特权](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-app-privilege-config-guide.md#可由设备厂商配置的特权)应用的系统应用。 + +### 约束与限制 + +- 能效资源仅支持系统特权应用使用。 + +- CPU支持按照进程维度或应用维度申请,其他资源仅支持按照应用维度申请。 + +## 接口说明 + +**表1** 申请能效资源主要接口 + +以下是能效资源开发使用的相关接口,更多接口及使用方式请见[后台任务管理](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)。 + +| 接口名 | 描述 | +| -------- | -------- | +| applyEfficiencyResources(request:EfficiencyResourcesRequest): void | 申请能效资源 | +| resetAllEfficiencyResources():void | 释放全部能效资源 | + +**表2** 能效资源申请参数 +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| resourceTypes | number | 是 | 申请的资源类型 | +| isApply | boolean | 是 | 申请或释放资源
- ture表示申请资源
- false表示释放部分资源 | +| timeOut | number | 是 | 资源使用时间(ms) | +| isPersist | boolean | 否 | 是否为永久持有资源,默认为false
- ture表示永久持有
- false表示有限时间内持有 | +| isProcess | boolean | 否 | 进程或应用申请,默认为false
- ture表示进程申请
- false表示应用申请 | +| reason | string | 是 | 申请资源原因 | + +**表3** 能效资源类型 +| 参数名 | 值 | 描述 | +| -------- | -------- | -------- | +| CPU | 1 | CPU资源,申请后应用进程不被挂起 | +| COMMON_EVENT | 2 | 公共事件资源,申请后应用进程被挂起后,可以收到公共事件 | +| TIMER | 4 | 公共事件资源,申请后应用进程被挂起后,Timer仍然可以唤醒应用 | +| WORK_SCHEDULER | 8 | 延迟任务资源,申请后延迟任务管控变宽松 | +| BLUETOOTH | 16 | 蓝牙资源,申请后应用进程被挂起后,蓝牙相关事件仍然可以唤醒应用 | +| GPS | 32 | GPS资源,申请后应用进程被挂起后,GPS相关事件可以唤醒应用 | +| AUDIO | 64 | 音频资源,有音频播放时对应的应用进程不被挂起 | + + +## 开发步骤 + +1. 导入模块。 + + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + ``` + +2. 申请能效资源。 + + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + + // 应用需要在后台保持活动状态,不被挂起。 + let request = { + resourceTypes: backgroundTaskManager.ResourceType.CPU, // 资源类型是CPU资源,保证应用进程不被挂起 + isApply: true, // 释放资源 + timeOut: 0, // 超时时间,超过超时时间后资源自动释放 + reason: "apply", // 申请原因 + isPersist: true, // 永久持有资源 + isProcess: false, // 在应用级别申请 + }; + try { + backgroundTaskManager.applyEfficiencyResources(request); + console.info("Succeeded in invoking applyEfficiencyResources."); + } catch (error) { + console.error(`Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`); + } + ``` + +3. 释放能效资源。应用在后台完成工作后,及时释放资源,支持释放部分资源或全部资源。 + + ```js + // 应用在后台完成了工作后,全部释放能效资源 + try { + backgroundTaskManager.resetAllEfficiencyResources(); + } catch (error) { + console.error(`Failed to invoke resetAllEfficiencyResources. Code is ${error.code} message is ${error.message}`); + } + //应用在后台完成了工作后,部分释放能效资源 + let request = { + resourceTypes: backgroundTaskManager.ResourceType.CPU, + isApply: false, // 释放资源 + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: false, // 在应用级别释放资源 + }; + try { + backgroundTaskManager.applyEfficiencyResources(request); + console.info("Succeeded in invoking applyEfficiencyResources."); + } catch (error) { + console.error(`Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`); + } + ``` + + > **说明:** + > 能效资源申请接口支持动态申请,在任务完成后,建议主动取消能效资源申请,以降低设备耗电速度、保障用户使用流畅度。 \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md deleted file mode 100644 index aea04c231c2cdef5dccf4e14eb4e4c6ed7495d31..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md +++ /dev/null @@ -1,72 +0,0 @@ -# 申请能效资源开发指导 - -## 场景说明 - -在实际的系统中,存在一些重要性高的系统应用,虽然此类应用相比普通应用具有一定的特权,但为了进一步平衡系统的功耗开销,这些应用同样需要支持在后台可被挂起。但对于系统特权应用,为了避免挂起后重要功能受到影响,提供了独立的能效资源申请接口,使这些特权应用可以在后台执行一些特殊的任务和使用特定的系统资源,例如在被挂起期间如果仍然希望能够收到系统公共事件,可以使用能效资源接口向系统申请使用公共事件资源。 - -对于需要升级为特权应用的,开发者需要合理评估自己的业务诉求,向应用中心提出申请。 - -## 约束与限制 -仅支持系统应用。 - -## 接口说明 - -**表1** 申请能效资源主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------- | -| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#efficiencyresourcesrequest)): boolean | 申请能效资源。 | -| resetAllEfficiencyResources():void | 释放申请的能效资源。 | - - -## 开发步骤 - -1、当特权应用需要在后台使用特殊资源时。向系统申请目标资源。 - -2、当资源使用完毕,需要及时释放。支持释放部分资源或全部资源。 - -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -// 申请能效资源 -let request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | - backgroundTaskManager.ResourceType.TIMER, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; - -let res; -try { - res = backgroundTaskManager.applyEfficiencyResources(request); - console.info("the result of request is: " + res); -} catch (error) { - console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} - -// 释放部分资源 -request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, - isApply: false, - timeOut: 0, - reason: "reset", - isPersist: true, - isProcess: true, -}; -try { - res = backgroundTaskManager.applyEfficiencyResources(request); - console.info("the result of request is: " + res); -} catch (error) { - console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} - -// 释放全部资源 -try { - backgroundTaskManager.resetAllEfficiencyResources(); -} catch (error) { - console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`); -} -``` diff --git a/zh-cn/application-dev/task-management/figures/WorkScheduler.png b/zh-cn/application-dev/task-management/figures/WorkScheduler.png new file mode 100644 index 0000000000000000000000000000000000000000..e52aba0d3c1388b4c1170236101b8b4f09fccab5 Binary files /dev/null and b/zh-cn/application-dev/task-management/figures/WorkScheduler.png differ diff --git a/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png b/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png deleted file mode 100644 index 57520a106c4dc4806866d78516939f29cb33ee9e..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png and /dev/null differ diff --git a/zh-cn/application-dev/task-management/figures/bgtask_choice.png b/zh-cn/application-dev/task-management/figures/bgtask_choice.png index f72473386330f4212a7aa8ff8e0c0f57e30b55de..8927224e1cbba4e4fdc3f4be8aaaa6ae58f1508f 100644 Binary files a/zh-cn/application-dev/task-management/figures/bgtask_choice.png and b/zh-cn/application-dev/task-management/figures/bgtask_choice.png differ diff --git a/zh-cn/application-dev/task-management/figures/transient-task.png b/zh-cn/application-dev/task-management/figures/transient-task.png new file mode 100644 index 0000000000000000000000000000000000000000..13e23bb2d1afa5ea4815d00a9803fec6487c8e27 Binary files /dev/null and b/zh-cn/application-dev/task-management/figures/transient-task.png differ diff --git a/zh-cn/application-dev/task-management/figures/zh-cn_image_0000001416585578.png b/zh-cn/application-dev/task-management/figures/zh-cn_image_0000001416585578.png deleted file mode 100644 index 55a721e05fc632a53c1710450f5de59410e1a587..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/task-management/figures/zh-cn_image_0000001416585578.png and /dev/null differ diff --git a/zh-cn/application-dev/task-management/reminder-agent-overview.md b/zh-cn/application-dev/task-management/reminder-agent-overview.md deleted file mode 100644 index c1e962331d79083cb2e5070c691d753b79ec15bf..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/reminder-agent-overview.md +++ /dev/null @@ -1,14 +0,0 @@ -# 后台代理提醒概述 - - -为保障用户体验,OpenHarmony对后台应用进程进行了有序治理,应用程序不能随意驻留在后台,同时应用后台行为受到严格管理,防止恶意应用行为。但对于某些退居后台或已退出的应用,可能需要在指定的时刻,向用户发送一些业务提醒通知。例如购物类应用,希望在指定时间点提醒用户有优惠活动。为满足此类业务诉求,OpenHarmony提供后台代理提醒功能,在应用退居后台或退出后,计时和提醒通知功能被系统后台代理接管。 - - -后台代理提醒业务类型: - - -- 倒计时类:基于倒计时的提醒功能,适用于短时的计时提醒业务。 - -- 日历类:基于日历的提醒功能,适用于较长时间的提醒业务。 - -- 闹钟类:基于时钟的提醒功能,适用于闹钟相关业务。 diff --git a/zh-cn/application-dev/task-management/transient-task-dev-guide.md b/zh-cn/application-dev/task-management/transient-task-dev-guide.md deleted file mode 100644 index e0de4621dd2dd023548285a13f6b34ee850c8b8c..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/transient-task-dev-guide.md +++ /dev/null @@ -1,99 +0,0 @@ -# 短时任务开发指导 - -## 场景说明 - -当应用退到后台默认有6到12秒的运行时长,超过该时间后,系统会将应用置为挂起状态。对于绝大多数应用,6到12秒的时间,足够执行一些重要的任务,但如果应用需要更多的时间,可以通过短时任务接口,扩展应用的执行时间。 - -建议不要等到应用退后台后,才调用[requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay)方法申请延迟挂起,而是应该在执行任何的耗时操作前,都应该调用该接口,向系统申明扩展应用的执行时间。 - -当应用在前台时,使用[requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay)方法,不会影响应用的短时任务配额。 - -根据需要调用[getRemainingDelayTime()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagergetremainingdelaytime)接口获取应用程序进入挂起状态前的剩余时间。由于每个应用每天的短时任务配额时间有限,当执行完耗时任务后,应当及时调用[cancelSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagercancelsuspenddelay)接口取消延迟挂起的申请。 - -一些典型的耗时任务,例如保存一些状态数据到本地数据库、打开和处理一个大型文件、同步一些数据到应用的云端服务器等。 - - -## 接口说明 - - -**表1** 短时任务主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------------------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为3分钟,低电量时默认值为1分钟。 | -| getRemainingDelayTime(requestId: number): Promise<number> | 获取应用程序进入挂起状态前的剩余时间。
使用Promise形式返回。 | -| cancelSuspendDelay(requestId: number): void | 取消延迟挂起。 | - - -## 开发步骤 - -当应用需要开始执行一个耗时的任务时。调用短时任务申请接口,并且在任务执行完后,调用短时任务取消接口。 - -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - -let id; // 申请延迟挂起任务ID -let delayTime; // 本次申请延迟挂起任务的剩余时间 - -// 申请延迟挂起 -function requestSuspendDelay() { - let myReason = 'test requestSuspendDelay'; // 申请原因 - - try { - let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - // 此回调函数执行,表示应用的延迟挂起申请即将超时,应用需要执行一些清理和标注工作,并取消延时挂起 - console.info("[backgroundTaskManager] Request suspension delay will time out."); - backgroundTaskManager.cancelSuspendDelay(id); - }) - id = delayInfo.requestId; - delayTime = delayInfo.actualDelayTime; - console.info("[backgroundTaskManager] The requestId is: " + id); - console.info("[backgroundTaskManager]The actualDelayTime is: " + delayTime); - } catch (error) { - console.error(`[backgroundTaskManager] requestSuspendDelay failed. code is ${error.code} message is ${error.message}`); - } -} - -// 获取进入挂起前的剩余时间 -async function getRemainingDelayTime() { - try { - await backgroundTaskManager.getRemainingDelayTime(id).then(res => { - console.log('[backgroundTaskManager] promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - }).catch(error => { - console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); - }) - } catch (error) { - console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); - } -} - -// 取消延迟挂起 -function cancelSuspendDelay() { - backgroundTaskManager.cancelSuspendDelay(id); -} - -async function performingLongRunningTask() { - // 在执行具体的耗时任务前,调用短时任务申请接口。向系统申请延迟挂起,延长应用的后台执行时间。 - requestSuspendDelay(); - - // 根据需要,通过剩余时间查询接口,获取可用时间配额。 - await getRemainingDelayTime(); - - if (delayTime < 0) { // 如果时间配置少于一定的大小,考虑取消此次耗时操作。 - // 处理短时任务配额时间不够的场景 - cancelSuspendDelay(); - return; - } - - // 此处执行具体的耗时任务 - - // 耗时任务执行完,调用短时任务取消接口,避免配额浪费 - cancelSuspendDelay(); -} -``` - -## 相关实例 - -针对短时任务开发,有以下相关实例可供参考: - -- [短时任务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/TransientTask) diff --git a/zh-cn/application-dev/task-management/transient-task.md b/zh-cn/application-dev/task-management/transient-task.md new file mode 100644 index 0000000000000000000000000000000000000000..b2e055e9eafcc7b3c32a9348172519935c75e81b --- /dev/null +++ b/zh-cn/application-dev/task-management/transient-task.md @@ -0,0 +1,100 @@ +# 短时任务 + + +## 概述 + +应用退至后台一小段时间后,应用进程会被挂起,无法执行对应的任务。如果应用在后台仍需要执行耗时不长的任务,如状态保存等,可以通过本文申请短时任务,扩展应用在后台的运行时间。 + + +### 约束与限制 + +- **申请时机**:应用需要在前台或退至后台5秒内,申请短时任务,否则会申请失败。 + +- **数量限制**:一个应用同一时刻最多申请3个短时任务。以图1为例,在①②③时间段内的任意时刻,应用申请了2个短时任务;在④时间段内的任意时刻,应用申请了1个短时任务。 + +- **配额机制**:一个应用会有一定的短时任务配额(根据系统状态和用户习惯调整),单日(24小时内)配额默认为10分钟,单次配额最大为3分钟,[低电量](../reference/apis/js-apis-battery-info.md)时单次配额默认为1分钟,配额消耗完后不允许再申请短时任务。同时,系统提供获取对应短时任务剩余时间的查询接口,用以查询本次短时任务剩余时间,以确认是否继续运行其他业务。 + +- **配额计算**:仅当应用在后台时,对应用下的短时任务计时;同一个应用下的同一个时间段的短时任务,不重复计时。以下图为例:应用有两个短时任务A和B,在前台时申请短时任务A,应用退至后台后开始计时为①,应用进入前台②后不计时,再次进入后台③后开始计时,短时任务A结束后,由于阶段④仍然有短时任务B,所以该阶段继续计时。因此,在这个过程中,该应用短时任务总耗时为①+③+④。 + + **图1** 短时任务配额计算原理图 + ![transient-task](figures/transient-task.png) + + > **说明:** + > + > 任务完成后,应用需主动取消短时任务,否则会影响应用当日短时任务的剩余配额。 + +- **超时**:短时任务即将超时时,系统会回调应用,应用需要取消短时任务。如果超时不取消,系统会终止对应的应用进程。 + +## 接口说明 + +**表1** 主要接口 + +以下是短时任务开发使用的主要接口,更多接口及使用方式请见[后台任务管理](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)。 + +| 接口名 | 描述 | +| -------- | -------- | +| requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo | 申请短时任务。 | +| getRemainingDelayTime(requestId: number): Promise<number> | 获取对应短时任务的剩余时间。 | +| cancelSuspendDelay(requestId: number): void | 取消短时任务。 | + + +## 开发步骤 + +1. 导入模块。 + + ```js + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + ``` + +2. 申请短时任务并实现回调。 + + ```js + let id; // 申请短时任务ID + let delayTime; // 本次申请短时任务的剩余时间 + + // 申请短时任务 + function requestSuspendDelay() { + let myReason = 'test requestSuspendDelay'; // 申请原因 + try { + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + // 回调函数。应用申请的短时任务即将超时,通过此函数回调应用,执行一些清理和标注工作,并取消短时任务 + console.info('Succeeded in requesting suspend delay.'); + backgroundTaskManager.cancelSuspendDelay(id); + }) + id = delayInfo.requestId; + delayTime = delayInfo.actualDelayTime; + } catch (err) { + console.error(`Failed to request suspend delay. Code: ${err.code}, message: ${err.message}`); + } + } + ``` + +3. 获取短时任务剩余时间。查询本次短时任务的剩余时间,用以判断是否继续运行其他业务,例如应用有两个小任务,在执行完第一个小任务后,可以判断本次短时任务是否还有剩余时间来决定是否执行第二个小任务。 + + ```js + async function getRemainingDelayTime() { + try { + backgroundTaskManager.getRemainingDelayTime(id).then(res => { + console.info('Succeeded in getting remaining delay time.'); + }).catch(err => { + console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`); + } + } + ``` + +4. 取消短时任务。 + + ```js + function cancelSuspendDelay() { + backgroundTaskManager.cancelSuspendDelay(id); + } + ``` + +## 相关实例 + +针对短时任务开发,有以下相关实例可供参考: + +- [短时任务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/TransientTask) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md deleted file mode 100644 index d8e227f4c5423214146078003b07b9ba4bbb71fe..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md +++ /dev/null @@ -1,203 +0,0 @@ -# 延迟任务调度开发指导 - -## 场景介绍 - -应用要执行对实时性要求不高的任务或持久性任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间,[WorkSchedulerExtensionAbility](./workscheduler-extensionability.md)提供了延迟任务回调拓展能力,注册延迟任务后需要实现延迟任务回调拓展能力。 -延迟任务调度约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束)。 - -## 接口说明 - -**表1** workScheduler主要接口 - -接口名 | 接口描述 ----------------------------------------------------------|----------------------------------------- -startWork(work: WorkInfo): void; | 延迟调度任务申请 -stopWork(work: WorkInfo, needCancel?: boolean): void; | 延迟调度任务取消 -getWorkStatus(workId: number, callback: AsyncCallback\): void;| 获取延迟调度任务状态(Callback形式) -getWorkStatus(workId: number): Promise\; | 获取延迟调度任务状态(Promise形式) -obtainAllWorks(callback: AsyncCallback\): Array\;| 获取所有延迟调度任务(Callback形式) -obtainAllWorks(): Promise>;| 获取所有延迟调度任务(Promise形式) -stopAndClearWorks(): void;| 停止并清除任务 -isLastWorkTimeOut(workId: number, callback: AsyncCallback\): boolean;| 获取上次任务是否超时(针对RepeatWork,Callback形式) -isLastWorkTimeOut(workId: number): Promise\;| 获取上次任务是否超时(针对RepeatWork,Promise形式) - -**表2** WorkInfo包含参数 - -WorkInfo设置参数约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束) - -参数名| 类型 |描述 ----------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- -workId| number | 延迟任务ID(必填) -bundleName| string | 延迟任务Bundle名称(必填) -abilityName| string | 延迟任务回调通知的组件名(必填) -networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | 网络类型 -isCharging| boolean | 是否充电 -chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | 充电类型 -batteryLevel| number | 电量 -batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | 电池状态 -storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |存储状态 -isRepeat| boolean |是否循环任务 -repeatCycleTime| number |循环间隔 -repeatCount | number|循环次数 -parameters | {[key: string]: number | string | boolean} |携带参数信息 - -**表3** 延迟任务回调接口 - -接口名 | 接口描述 ----------------------------------------------------------|----------------------------------------- -onWorkStart(work: WorkInfo): void | 延迟调度任务开始回调 -onWorkStop(work: WorkInfo): void | 延迟调度任务结束回调 - -### 开发步骤 - -1、导入模块。 - -注册相关接口包导入: -```js -import workScheduler from '@ohos.resourceschedule.workScheduler'; -``` - -回调相关接口包导入: -```js -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; -``` - -2、开发对应的ExtensionAbility,用于回调执行具体的延迟任务。关于ExtensionAbility的介绍,参考[ExtensionAbility机制](../application-models/extensionability-overview.md)和[WorkSchedulerExtensionAbility开发指导](./workscheduler-extensionability.md)。 - -```ts -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; - -export default class MyExtension extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); - } - onWorkStop(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); - } -} -``` - - -3、注册延迟任务 - -```ts -import workScheduler from '@ohos.resourceschedule.workScheduler'; - -let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } -} -try{ - workScheduler.startWork(workInfo); - console.info('workschedulerLog startWork success'); -} catch (error) { - console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); -} -``` - - -4、取消延迟任务 - -```ts -import workScheduler from '@ohos.resourceschedule.workScheduler'; - -let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } -} -try{ - workScheduler.stopWork(workInfo, false); - console.info('workschedulerLog stopWork success'); -} catch (error) { - console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); -} -``` - - -5、获取指定延迟任务 - -```ts -try{ - workScheduler.getWorkStatus(50, (error, res) => { - if (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); - } else { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - } - }); -} catch (error) { - console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); -} -``` - - -6、获取所有延迟任务 - -```ts -try{ - workScheduler.obtainAllWorks((error, res) =>{ - if (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - } - }); -} catch (error) { - console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); -} -``` - -7、停止并清除任务 - -```ts -try{ - workScheduler.stopAndClearWorks(); - console.info(`workschedulerLog stopAndClearWorks success`); -} catch (error) { - console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); -} -``` - -8、判断上次执行是否超时 - -```ts -try{ - workScheduler.isLastWorkTimeOut(500, (error, res) =>{ - if (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); - } else { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - } - }); -} catch (error) { - console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); -} -``` - -## 相关实例 - -基于延迟任务调度,有以下相关实例可供参考: - -- [`WorkScheduler`:任务延时调度(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/work-scheduler.md b/zh-cn/application-dev/task-management/work-scheduler.md new file mode 100644 index 0000000000000000000000000000000000000000..e9f83c53723b3849f0542247f689410f47a60ac2 --- /dev/null +++ b/zh-cn/application-dev/task-management/work-scheduler.md @@ -0,0 +1,213 @@ +# 延迟任务 + +## 概述 + +### 功能介绍 + +应用退至后台后,需要执行实时性要求不高的任务,例如有网络时不定期主动获取邮件等,可以使用延迟任务。当应用满足设定条件(包括网络类型、充电类型、存储状态、电池状态、定时状态等)时,将任务添加到执行队列,系统会根据内存、功耗、设备温度、用户使用习惯等统一调度拉起应用。 + +### 运行原理 + +**图1** 延迟任务实现原理 +![WorkScheduler](figures/WorkScheduler.png) + +应用调用延迟任务接口注册、删除、查询延迟任务,延迟任务管理模块会根据任务设置的条件(通过WorkInfo参数设置,包括网络类型、充电类型、存储状态等)和系统状态(包括内存、功耗、设备温度、用户使用习惯等)统一决策调度时机。 + +当满足调度条件或调度结束时,系统会回调应用[WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md)中 onWorkStart() 或 onWorkStop() 的方法,同时会为应用单独创建一个Extension扩展进程用以承载[WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md),并给[WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md)一定的活动周期,开发者可以在对应回调方法中实现自己的任务逻辑。 + + +### 约束与限制 + +- **数量限制**:一个应用同一时刻最多申请10个延迟任务。 + +- **执行频率限制**:系统会根据[应用的活跃分组](../reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md),对延迟任务做分级管控,限制延迟任务调度的执行频率。通过能效资源接口申请了WORK_SCHEDULER资源的应用,会被放在能效资源豁免分组中。 + + **表1** 应用活跃程度分组 + | 应用活跃分组 | 延迟任务执行频率 | + | -------- | -------- | + | 活跃分组 | 最小间隔2小时 | + | 经常使用分组 | 最小间隔4小时 | + | 常用使用 | 最小间隔24小时 | + | 极少使用分组 | 最小间隔48小时 | + | 受限使用分组 | 禁止 | + | 从未使用分组 | 禁止 | + | 能效资源豁免分组 | 不受限制 | + +- **超时**:WorkSchedulerExtensionAbility单次回调最长运行2分钟。如果超时不取消,系统会终止对应的Extension进程。对于系统特权应用,可以通过能效资源接口申请WORK_SCHEDULER资源,扩展单次回调运行时长,扩展后在充电状态下为20分钟,非充电状态下为10分钟。 + +- **调度延迟**:系统会根据内存、功耗、设备温度、用户使用习惯等统一调度,如当系统内存资源不足或温度达到一定挡位时,系统将延迟调度该任务。 + +- **WorkSchedulerExtensionAbility接口调用限制**:为实现对WorkSchedulerExtensionAbility能力的管控,在WorkSchedulerExtensionAbility中限制以下接口的调用: + + [@ohos.resourceschedule.backgroundTaskManager (后台任务管理)](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) + + [@ohos.backgroundTaskManager (后台任务管理)](../reference/apis/js-apis-backgroundTaskManager.md) + + [@ohos.multimedia.camera (相机管理)](../reference/apis/js-apis-camera.md) + + [@ohos.multimedia.audio (音频管理)](../reference/apis/js-apis-audio.md) + + [@ohos.multimedia.media (媒体服务)](../reference/apis/js-apis-media.md) + + +## 接口说明 + +**表2** 延迟任务主要接口 + +以下是延迟任务开发使用的相关接口,更多接口及使用方式请见[延迟任务](../reference/apis/js-apis-resourceschedule-workScheduler.md)文档。 +| 接口名 | 接口描述 | +| -------- | -------- | +| startWork(work: WorkInfo): void; | 申请延迟任务 | +| stopWork(work: WorkInfo, needCancel?: boolean): void; | 取消延迟任务 | +| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | 获取延迟任务状态(Callback形式) | +| getWorkStatus(workId: number): Promise<WorkInfo>; | 获取延迟任务状态(Promise形式) | +| obtainAllWorks(callback: AsyncCallback<void>): Array<WorkInfo>; | 获取所有延迟任务(Callback形式) | +| obtainAllWorks(): Promise<Array<WorkInfo>>; | 获取所有延迟任务(Promise形式) | +| stopAndClearWorks(): void; | 停止并清除任务 | +| isLastWorkTimeOut(workId: number, callback: AsyncCallback<void>): boolean; | 获取上次任务是否超时(针对RepeatWork,Callback形式) | +| isLastWorkTimeOut(workId: number): Promise<boolean>; | 获取上次任务是否超时(针对RepeatWork,Promise形式) | + +**表3** WorkInfo参数 +| 参数名 | 类型 | 描述 | +| -------- | -------- | -------- | +| workId | number | 延迟任务Id(必填) | +| bundleName | string | 延迟任务包名(必填) | +| abilityName | string | 延迟任务回调通知的组件名(必填) | +| networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | 网络类型 | +| isCharging | boolean | 是否充电 | +| chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | 充电类型 | +| batteryLevel | number | 电量 | +| batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | 电池状态 | +| storageRequest | [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) | 存储状态 | +| isRepeat | boolean | 是否循环任务 | +| repeatCycleTime | number | 循环间隔 | +| repeatCount | number | 循环次数 | +| parameters | [key: string]: number | 携带参数信息 | + +WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: + +- workId、bundleName、abilityName为必填项,bundleName需为本应用包名。 + +- 携带参数信息仅支持number、string、bool三种类型。 + +- 至少设置一个满足的条件,包括网络类型、充电类型、存储状态、电池状态、定时状态等。 + +- 对于重复任务,任务执行间隔至少20分钟。设置重复任务时间间隔时,须同时设置是否循环或循环次数中的一个。 + +**表4** 延迟任务回调接口 + +以下是延迟任务回调开发使用的相关接口,更多接口及使用方式请见[延迟任务回调](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md)文档。 +| 接口名 | 接口描述 | +| -------- | -------- | +| onWorkStart(work: WorkInfo): void | 延迟调度任务开始的回调 | +| onWorkStop(work: WorkInfo): void | 延迟调度任务结束的回调 | + + +## 开发步骤 + +延迟任务调度开发步骤分为两步:实现延迟任务调度扩展能力、实现延迟任务调度。 + +1. **延迟任务调度扩展能力**:实现WorkSchedulerExtensionAbility开始和结束的回调接口。 + +2. **延迟任务调度**:调用延迟任务接口,实现延迟任务申请、取消等功能。 + +### 实现延迟任务回调拓展能力 + +1. 新建工程目录。 + + 在工程entry Module对应的ets目录(./entry/src/main/ets)下,新建目录及ArkTS文件,例如新建一个目录并命名为extension。在extension目录下,新建一个ArkTS文件并命名为WorkSchedulerExtension.ets,用以实现延迟任务回调接口。 + +2. 导入模块。 + + ```ts + import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + ``` + +3. 实现WorkSchedulerExtension生命周期接口。 + + ```ts + export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { + // 延迟任务开始回调 + onWorkStart(workInfo) { + console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`); + } + + // 延迟任务结束回调 + onWorkStop(workInfo) { + console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`); + } + } + ``` + +4. 在[module.json5配置文件](../quick-start/module-configuration-file.md)中注册WorkSchedulerExtensionAbility,并设置如下标签: + + - type标签设置为“workScheduler”。 + + - srcEntry标签设置为当前ExtensionAbility组件所对应的代码路径。 + + ```json + { + "module": { + "extensionAbilities": [ + { + "name": "MyWorkSchedulerExtensionAbility", + "srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ts", + "label": "$string:WorkSchedulerExtensionAbility_label", + "description": "$string:WorkSchedulerExtensionAbility_desc", + "type": "workScheduler" + } + ] + } + } + ``` + + +### 实现延迟任务调度 + +1. 导入模块。 + + ```ts + import workScheduler from '@ohos.resourceschedule.workScheduler'; + ``` + +2. 申请延迟任务。 + + ```ts + private workInfo = { + workId: 1, + networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, + bundleName: 'com.example.application', + abilityName: 'MyWorkSchedulerExtensionAbility' + } + + try { + workScheduler.startWork(this.workInfo); + console.info(`startWork success`); + } catch (error) { + console.error(`startWork failed. code is ${error.code} message is ${error.message}`); + } + ``` + +3. 取消延迟任务。 + + ```ts + private workInfo = { + workId: 1, + networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, + bundleName: 'com.example.application', + abilityName: 'MyWorkSchedulerExtensionAbility' + } + + try { + workScheduler.stopWork(this.workInfo); + console.info(`stopWork success`); + } catch (error) { + console.error(`stopWork failed. code is ${error.code} message is ${error.message}`); + } + ``` + +## 相关实例 + +针对延迟任务调度的开发,有以下相关示例可供参考: + +- [WorkScheduler的创建与使用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/workscheduler-extensionability.md b/zh-cn/application-dev/task-management/workscheduler-extensionability.md deleted file mode 100644 index ec7837e972ddcabc868ad291f95a81c8d2fcd8eb..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/workscheduler-extensionability.md +++ /dev/null @@ -1,213 +0,0 @@ -# 延迟任务回调能力开发指导(WorkSchedulerExtensionAbility) - -对于实时性要求不高的任务或持久性任务,可以使用延迟任务,该机制会在应用满足应用设定条件(包括网络类型、充电类型、存储状态、电池状态、定时状态)时,根据系统当前状态,由系统统一决策调度时间。 - -WorkSchedulerExtensionAbility提供了延迟任务回调能力,在延迟任务开始和结束时,系统会调用回调接口来处理任务逻辑,开发者可在回调接口里面编写自己的任务逻辑。 - -## 运作机制 - -延迟任务调度运作机制如图1所示。 - - **图1** 延迟任务调度运作机制  - -![WorkSchedulerExtensionAbility](figures/WorkSchedulerExtensionAbility.png) - -应用通过[延迟任务API](../reference/apis/js-apis-resourceschedule-workScheduler.md)注册、删除、查询任务。 -应用服务侧进行条件检测和判断,若满足条件,则回调WorkSchedulerExtensionAbility拉起应用,执行onWorkStart、onWorkStop回调接口。 - -## 接口说明 - -WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见[接口文档](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md)。 - -| 接口名 | 描述 | -| -------- | -------- | -| onWorkStart(work: workScheduler.WorkInfo): void | 延迟任务调度开始回调。 | -| onWorkStop(work: workScheduler.WorkInfo): void | 延迟任务调度结束回调。 | - -## 开发步骤 - -在DevEco Studio工程中新建一个WorkScheduler工程,主要涉及如下关键步骤: - -- [实现延迟任务回调拓展能力](#实现延迟任务回调拓展能力):开发延迟任务生命周期回调接口WorkSchedulerExtensionAbility。 - -- [实现延迟任务调度能力](#实现延迟任务调度能力):开发延迟任务API,实现延迟任务注册、停止等功能。 - -- [配置文件](#配置文件):配置应用配置文件module.json5。 - -### 实现延迟任务回调拓展能力 - -1. 在工程根目录新建Module,模板选择为Ohos Library,命名为library。 - -2. 在library对应的ets目录(./library/src/main/ets)下,新建ArkTS文件并命名为workAbility.ets,用于实现延迟任务回调接口。 - - 导入模块。 - - ```ts - import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; - ``` - - 实现WorkSchedulerExtension生命周期接口。 - - ```ts - export default class workAbility extends WorkSchedulerExtensionAbility { - // 延迟任务开始回调 - onWorkStart(workInfo) { - console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`); - // 发送升级通知 - let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, ''); - notification.publish(notificationRequest, (err) => { - if (err) { - console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`); - } - console.log(`onWorkStart notification publish success`); - }); - } - - // 延迟任务结束回调 - onWorkStop(workInfo) { - // 发送升级完成通知 - let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', ''); - notification.publish(notificationRequest, (err) => { - if (err) { - console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`); - } - console.log(`onWorkStop notification publish success`); - }); - } - } - ``` - -3. 在工程entry Module对应的ets目录(./entry/src/main/ets)下,新建一个目录并命名为workAbility。 - 在workAbility目录下,新建一个ArkTS文件并命名为WorkTest.ets,实现延迟任务回调接口。 - - 导入模块。 - - ```ts - import { workAbility } from '@ohos/library' - ``` - - 继承workAbility,实现WorkSchedulerExtension生命周期接口。 - - ```ts - export default class WorkTest extends workAbility { - onWorkStart(workInfo) { - console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`); - super.onWorkStart(workInfo); - } - - onWorkStopTest(workInfo) { - super.onWorkStop(workInfo); - console.log(`onWorkStop value`); - } - } - ``` - -### 实现延迟任务调度能力 - -1. 在library对应的ets目录(./library/src/main/ets)下,新建TypeScript文件并命名为DelayWork.ts,用于实现延迟任务API。 - - 导入模块。 - - ```ts - import workScheduler from '@ohos.resourceschedule.workScheduler'; - ``` - - 封装延迟任务注册、停止接口。 - - ```ts - export default class DelayWork { - private workInfo = { - workId: 1, - networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, - bundleName: '', - abilityName: '' - } - // 注册延迟任务 - startWork(bundleName: string, abilityName: string) { - this.workInfo.bundleName = bundleName; - this.workInfo.abilityName = abilityName; - try { - workScheduler.startWork(this.workInfo); - console.log(`startWork success`); - } catch (error) { - Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`); - prompt.showToast({ - message: `${error.message}` - }); - } - } - - // 停止延迟任务 - stopWork(bundleName: string, abilityName: string) { - this.workInfo.bundleName = bundleName; - this.workInfo.abilityName = abilityName; - workScheduler.stopWork(this.workInfo, false); - console.log(`stopWork`); - } - } - ``` - -2. 在工程entry Module对应的index页面(./entry/src/main/ets/pages/index.ets)下,增加“升级”按钮,调用library封装的延迟任务注册接口。 - - 导入模块。 - - ```ts - import { workAbility } from '@ohos/library'; - ``` - - 增加“升级”按钮,调用library封装的延迟任务注册接口,传入bundleName和abilityName,其中abilityName为WorkTest。 - - ```ts - Button($r('app.string.upgrade')) - .width('60%') - .height(40) - .fontSize(30) - .onClick(() => { - this.work.startWork('ohos.samples.workscheduler', 'WorkTest'); - }); - ``` - - 在组件析构时,调用延迟任务停止接口。 - - ```ts - aboutToDisappear() { - this.work.stopWork('ohos.samples.workscheduler', 'WorkTest'); - } - ``` - -### 配置文件 - -1. 在工程entry Module对应的[module.json5配置文件](../quick-start/module-configuration-file.md)中注册WorkSchedulerExtensionAbility,type标签需要设置为“workScheduler”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。 - - ```json - { - "module": { - "extensionAbilities": [ - { - "name": "WorkTest", - "srcEntry": "./ets/workAbility/WorkTest.ets", - "label": "$string:WorkSchedulerExtensionAbility_label", - "description": "$string:WorkSchedulerExtensionAbility_desc", - "type": "workScheduler" - } - ] - } - } - ``` - -## 限制 - -为了降低WorkSchedulerExtensionAbility能力被三方应用滥用的风险,在WorkSchedulerExtensionAbility中限制以下接口的调用 - -- @ohos.backgroundTaskManager.d.ts -- @ohos.resourceschedule.backgroundTaskManager.d.ts -- @ohos.multimedia.camera.d.ts -- @ohos.multimedia.audio.d.ts -- @ohos.multimedia.media.d.ts - -## 相关实例 - -针对WorkSchedulerExtensionAbility开发,有以下相关示例可供参考: - -- [WorkScheduler的创建与使用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) - diff --git a/zh-cn/application-dev/tools/unpacking-tool.md b/zh-cn/application-dev/tools/unpacking-tool.md index babde0f2870f1f5301784d7c2782a17d5bc448a6..68e6b56a082ae042c8bb14b6d7c57cf22b27c50a 100644 --- a/zh-cn/application-dev/tools/unpacking-tool.md +++ b/zh-cn/application-dev/tools/unpacking-tool.md @@ -185,9 +185,9 @@ java -jar app_unpacking_tool.jar --mode